File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.778: download - view: text, annotated - select for diffs
Mon Nov 9 00:44:30 2020 UTC (3 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6943 <link> tag for css not needed if View Problem Text set to "no".

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.778 2020/11/09 00:44:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use Apache::lontexconvert();
   50: use String::Similarity;
   51: use HTML::Parser();
   52: use File::MMagic;
   53: use LONCAPA;
   54: 
   55: use POSIX qw(floor);
   56: 
   57: 
   58: 
   59: my %perm=();
   60: my %old_essays=();
   61: 
   62: #  These variables are used to recover from ssi errors
   63: 
   64: my $ssi_retries = 5;
   65: my $ssi_error;
   66: my $ssi_error_resource;
   67: my $ssi_error_message;
   68: 
   69: 
   70: sub ssi_with_retries {
   71:     my ($resource, $retries, %form) = @_;
   72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   73:     if ($response->is_error) {
   74: 	$ssi_error          = 1;
   75: 	$ssi_error_resource = $resource;
   76: 	$ssi_error_message  = $response->code . " " . $response->message;
   77:     }
   78: 
   79:     return $content;
   80: 
   81: }
   82: #
   83: #  Prodcuces an ssi retry failure error message to the user:
   84: #
   85: 
   86: sub ssi_print_error {
   87:     my ($r) = @_;
   88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   89:     $r->print('
   90: <br />
   91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   92: <p>
   93: '.&mt('Unable to retrieve a resource from a server:').'<br />
   94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   95: '.&mt('Error:').' '.$ssi_error_message.'
   96: </p>
   97: <p>'.
   98: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  100: '</p>');
  101:     return;
  102: }
  103: 
  104: #
  105: # --- Retrieve the parts from the metadata file.---
  106: # Returns an array of everything that the resources stores away
  107: #
  108: 
  109: sub getpartlist {
  110:     my ($symb,$errorref) = @_;
  111: 
  112:     my $navmap   = Apache::lonnavmaps::navmap->new();
  113:     unless (ref($navmap)) {
  114:         if (ref($errorref)) { 
  115:             $$errorref = 'navmap';
  116:             return;
  117:         }
  118:     }
  119:     my $res      = $navmap->getBySymb($symb);
  120:     my $partlist = $res->parts();
  121:     my $url      = $res->src();
  122:     my $toolsymb;
  123:     if ($url =~ /ext\.tool$/) {
  124:         $toolsymb = $symb;
  125:     }
  126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  127: 
  128:     my @stores;
  129:     foreach my $part (@{ $partlist }) {
  130: 	foreach my $key (@metakeys) {
  131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  132: 	}
  133:     }
  134:     return @stores;
  135: }
  136: 
  137: #--- Format fullname, username:domain if different for display
  138: #--- Use anywhere where the student names are listed
  139: sub nameUserString {
  140:     my ($type,$fullname,$uname,$udom) = @_;
  141:     if ($type eq 'header') {
  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  143:     } else {
  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  146:     }
  147: }
  148: 
  149: #--- Get the partlist and the response type for a given problem. ---
  150: #--- Count responseIDs, essayresponse items, and dropbox items ---
  151: #--- Sets response_error pointer to "1" if navmaps object broken ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  169:     my %vPart = 
  170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  171:     my (%response_types,%handgrade);
  172:     foreach my $part (@{ $partlist }) {
  173: 	next if (%vPart && !exists($vPart{$part}));
  174: 
  175: 	my @types = $res->responseType($part);
  176: 	my @ids = $res->responseIds($part);
  177: 	for (my $i=0; $i < scalar(@ids); $i++) {
  178:             $numresp ++;
  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  180:             if ($types[$i] eq 'essay') {
  181:                 $numessay ++;
  182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  183:                     $numdropbox ++;
  184:                 }
  185:             }
  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
  187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  188: 				     '.handgrade',$symb);
  189: 	}
  190:     }
  191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  192: }
  193: 
  194: sub flatten_responseType {
  195:     my ($responseType) = @_;
  196:     my @part_response_id =
  197: 	map { 
  198: 	    my $part = $_;
  199: 	    map {
  200: 		[$part,$_]
  201: 		} sort(keys(%{ $responseType->{$part} }));
  202: 	} sort(keys(%$responseType));
  203:     return @part_response_id;
  204: }
  205: 
  206: sub get_display_part {
  207:     my ($partID,$symb)=@_;
  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  209:     if (defined($display) and $display ne '') {
  210:         $display.= ' (<span class="LC_internal_info">'
  211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  212:     } else {
  213: 	$display=$partID;
  214:     }
  215:     return $display;
  216: }
  217: 
  218: #--- Show parts and response type
  219: sub showResourceInfo {
  220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  222:         return '<br clear="all">';
  223:     }
  224:     my $coltitle = &mt('Problem Part Shown');
  225:     if ($checkboxes) {
  226:         $coltitle = &mt('Problem Part');
  227:     } else {
  228:         my $checkedparts = 0;
  229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  231:                 $checkedparts ++;
  232:             }
  233:         }
  234:         if ($checkedparts == scalar(@{$partlist})) {
  235:             return '<br clear="all">';
  236:         }
  237:         if ($uploads) {
  238:             $coltitle = &mt('Problem Part Selected');
  239:         }
  240:     }
  241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  242:     if ($checkboxes) {
  243:         my $legend = &mt('Parts to display');
  244:         if ($uploads) {
  245:             $legend = &mt('Part(s) with dropbox');
  246:         }
  247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  248:                    '<span class="LC_nobreak">'.
  249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  252:                    &mt('Selected parts').'</label></span>'.
  253:                    '<div id="LC_partselector" style="display:none">';
  254:     }
  255:     $result .= &Apache::loncommon::start_data_table()
  256:               .&Apache::loncommon::start_data_table_header_row();
  257:     if ($checkboxes) {
  258:         $result .= '<th>'.&mt('Display?').'</th>';
  259:     }
  260:     $result .= '<th>'.$coltitle.'</th>'
  261:               .'<th>'.&mt('Res. ID').'</th>'
  262:               .'<th>'.&mt('Type').'</th>'
  263:               .&Apache::loncommon::end_data_table_header_row();
  264:     my %partsseen;
  265:     foreach my $partID (sort(keys(%$responseType))) {
  266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  267:             my $responsetype = $responseType->{$partID}->{$resID};
  268:             if ($uploads) {
  269:                 next unless ($responsetype eq 'essay');
  270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  271:             }
  272:             my $display_part=&get_display_part($partID,$symb);
  273:             if (exists($partsseen{$partID})) {
  274:                 $result.=&Apache::loncommon::continue_data_table_row();
  275:             } else {
  276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  277:                 $result.=&Apache::loncommon::start_data_table_row().
  278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  279:                 if ($checkboxes) {
  280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  282:                 } else {
  283:                     $result.=$display_part.'</td>';
  284:                 }
  285:             }
  286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  287:                     .'<td>'.&mt($responsetype).'</td>'
  288:                     .&Apache::loncommon::end_data_table_row();
  289:         }
  290:     }
  291:     $result.=&Apache::loncommon::end_data_table();
  292:     if ($checkboxes) {
  293:         $result .= '</div></fieldset>';
  294:     }
  295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  296:     if (!keys(%partsseen)) {
  297:         $result = '';
  298:         if ($uploads) {
  299:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  300:                    '<p class="LC_info">'.
  301:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  302:                    '</p>';
  303:         } else {
  304:             return '<br clear="all" />';
  305:         }
  306:     }
  307:     return $result;
  308: }
  309: 
  310: sub part_selector_js {
  311:     my $js = <<"END";
  312: function toggleParts(formname) {
  313:     if (document.getElementById('LC_partselector')) {
  314:         var index = '';
  315:         if (document.forms.length) {
  316:             for (var i=0; i<document.forms.length; i++) {
  317:                 if (document.forms[i].name == formname) {
  318:                     index = i;
  319:                     break;
  320:                 }
  321:             }
  322:         }
  323:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  324:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  325:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  326:                    var val = document.forms[index].elements['chooseparts'][i].value;
  327:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  328:                         document.getElementById('LC_partselector').style.display = 'block';
  329:                     } else {
  330:                         document.getElementById('LC_partselector').style.display = 'none';
  331:                     }
  332:                 }
  333:             }
  334:         }
  335:     }
  336: }
  337: END
  338:     return &Apache::lonhtmlcommon::scripttag($js);
  339: }
  340: 
  341: sub reset_caches {
  342:     &reset_analyze_cache();
  343:     &reset_perm();
  344:     &reset_old_essays();
  345: }
  346: 
  347: {
  348:     my %analyze_cache;
  349:     my %analyze_cache_formkeys;
  350: 
  351:     sub reset_analyze_cache {
  352: 	undef(%analyze_cache);
  353:         undef(%analyze_cache_formkeys);
  354:     }
  355: 
  356:     sub get_analyze {
  357: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  358: 	my $key = "$symb\0$uname\0$udom";
  359:         if ($type eq 'randomizetry') {
  360:             if ($trial ne '') {
  361:                 $key .= "\0".$trial;
  362:             }
  363:         }
  364: 	if (exists($analyze_cache{$key})) {
  365:             my $getupdate = 0;
  366:             if (ref($add_to_hash) eq 'HASH') {
  367:                 foreach my $item (keys(%{$add_to_hash})) {
  368:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  369:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  370:                             $getupdate = 1;
  371:                             last;
  372:                         }
  373:                     } else {
  374:                         $getupdate = 1;
  375:                     }
  376:                 }
  377:             }
  378:             if (!$getupdate) {
  379:                 return $analyze_cache{$key};
  380:             }
  381:         }
  382: 
  383: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  384: 	$url=&Apache::lonnet::clutter($url);
  385:         my %form = ('grade_target'      => 'analyze',
  386:                     'grade_domain'      => $udom,
  387:                     'grade_symb'        => $symb,
  388:                     'grade_courseid'    =>  $env{'request.course.id'},
  389:                     'grade_username'    => $uname,
  390:                     'grade_noincrement' => $no_increment);
  391:         if ($bubbles_per_row ne '') {
  392:             $form{'bubbles_per_row'} = $bubbles_per_row;
  393:         }
  394:         if ($type eq 'randomizetry') {
  395:             $form{'grade_questiontype'} = $type;
  396:             if ($rndseed ne '') {
  397:                 $form{'grade_rndseed'} = $rndseed;
  398:             }
  399:         }
  400:         if (ref($add_to_hash)) {
  401:             %form = (%form,%{$add_to_hash});
  402:         }
  403: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  404: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  406:         if (ref($add_to_hash) eq 'HASH') {
  407:             $analyze_cache_formkeys{$key} = $add_to_hash;
  408:         } else {
  409:             $analyze_cache_formkeys{$key} = {};
  410:         }
  411: 	return $analyze_cache{$key} = \%analyze;
  412:     }
  413: 
  414:     sub get_order {
  415: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  416: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  417: 	return $analyze->{"$partid.$respid.shown"};
  418:     }
  419: 
  420:     sub get_radiobutton_correct_foil {
  421: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  422: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  423:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  424:         if (ref($foils) eq 'ARRAY') {
  425: 	    foreach my $foil (@{$foils}) {
  426: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  427: 		    return $foil;
  428: 	        }
  429: 	    }
  430: 	}
  431:     }
  432: 
  433:     sub scantron_partids_tograde {
  434:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  435:         my (%analysis,@parts);
  436:         if (ref($resource)) {
  437:             my $symb = $resource->symb();
  438:             my $add_to_form;
  439:             if ($check_for_randomlist) {
  440:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  441:             }
  442:             if ($scancode) {
  443:                 if (ref($add_to_form) eq 'HASH') {
  444:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  445:                 } else {
  446:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  447:                 }
  448:             }
  449:             my $analyze =
  450:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  451:                              undef,undef,undef,$bubbles_per_row);
  452:             if (ref($analyze) eq 'HASH') {
  453:                 %analysis = %{$analyze};
  454:             }
  455:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  456:                 foreach my $part (@{$analysis{'parts'}}) {
  457:                     my ($id,$respid) = split(/\./,$part);
  458:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  459:                         push(@parts,$part);
  460:                     }
  461:                 }
  462:             }
  463:         }
  464:         return (\%analysis,\@parts);
  465:     }
  466: 
  467: }
  468: 
  469: #--- Clean response type for display
  470: #--- Currently filters option/rank/radiobutton/match/essay/Task
  471: #        response types only.
  472: sub cleanRecord {
  473:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  474: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  475:     my $grayFont = '<span class="LC_internal_info">';
  476:     if ($response =~ /^(option|rank)$/) {
  477: 	my %answer=&Apache::lonnet::str2hash($answer);
  478:         my @answer = %answer;
  479:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  480: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  481: 	my ($toprow,$bottomrow);
  482: 	foreach my $foil (@$order) {
  483: 	    if ($grading{$foil} == 1) {
  484: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  485: 	    } else {
  486: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  487: 	    }
  488: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  489: 	}
  490: 	return '<blockquote><table border="1">'.
  491: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  492: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  493: 	    $bottomrow.'</tr></table></blockquote>';
  494:     } elsif ($response eq 'match') {
  495: 	my %answer=&Apache::lonnet::str2hash($answer);
  496:         my @answer = %answer;
  497:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  498: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  499: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  500: 	my ($toprow,$middlerow,$bottomrow);
  501: 	foreach my $foil (@$order) {
  502: 	    my $item=shift(@items);
  503: 	    if ($grading{$foil} == 1) {
  504: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  505: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  506: 	    } else {
  507: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  508: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  509: 	    }
  510: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  511: 	}
  512: 	return '<blockquote><table border="1">'.
  513: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  514: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  515: 	    $middlerow.'</tr>'.
  516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  517: 	    $bottomrow.'</tr></table></blockquote>';
  518:     } elsif ($response eq 'radiobutton') {
  519: 	my %answer=&Apache::lonnet::str2hash($answer);
  520:         my @answer = %answer;
  521:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  522: 	my ($toprow,$bottomrow);
  523: 	my $correct = 
  524: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  525: 	foreach my $foil (@$order) {
  526: 	    if (exists($answer{$foil})) {
  527: 		if ($foil eq $correct) {
  528: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  529: 		} else {
  530: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  531: 		}
  532: 	    } else {
  533: 		$toprow.='<td>'.&mt('false').'</td>';
  534: 	    }
  535: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  536: 	}
  537: 	return '<blockquote><table border="1">'.
  538: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  539: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  540: 	    $bottomrow.'</tr></table></blockquote>';
  541:     } elsif ($response eq 'essay') {
  542: 	if (! exists ($env{'form.'.$symb})) {
  543: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  544: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  545: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  546: 
  547: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  548: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  549: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  550: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  551: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  552: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  553: 	}
  554:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  555: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  556:     } elsif ( $response eq 'organic') {
  557:         my $result=&mt('Smile representation: [_1]',
  558:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  559: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  560: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  561: 	return $result;
  562:     } elsif ( $response eq 'Task') {
  563: 	if ( $answer eq 'SUBMITTED') {
  564: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  565: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  566: 	    return $result;
  567: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  568: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  569: 			       keys(%{$record}));
  570: 	    return join('<br />',($version,@matches));
  571: 			       
  572: 			       
  573: 	} else {
  574: 	    my $result =
  575: 		'<p>'
  576: 		.&mt('Overall result: [_1]',
  577: 		     $record->{$version."resource.$respid.$partid.status"})
  578: 		.'</p>';
  579: 	    
  580: 	    $result .= '<ul>';
  581: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  582: 			     keys(%{$record}));
  583: 	    foreach my $grade (sort(@grade)) {
  584: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  585: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  586: 				     $dim, $record->{$grade}).
  587: 			  '</li>';
  588: 	    }
  589: 	    $result.='</ul>';
  590: 	    return $result;
  591: 	}
  592:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  593:         # Respect multiple input fields, see Bug #5409
  594: 	$answer = 
  595: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  596: 							      $answer);
  597: 	return $answer;
  598:     }
  599:     return &HTML::Entities::encode($answer, '"<>&');
  600: }
  601: 
  602: #-- A couple of common js functions
  603: sub commonJSfunctions {
  604:     my $request = shift;
  605:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  606:     function radioSelection(radioButton) {
  607: 	var selection=null;
  608: 	if (radioButton.length > 1) {
  609: 	    for (var i=0; i<radioButton.length; i++) {
  610: 		if (radioButton[i].checked) {
  611: 		    return radioButton[i].value;
  612: 		}
  613: 	    }
  614: 	} else {
  615: 	    if (radioButton.checked) return radioButton.value;
  616: 	}
  617: 	return selection;
  618:     }
  619: 
  620:     function pullDownSelection(selectOne) {
  621: 	var selection="";
  622: 	if (selectOne.length > 1) {
  623: 	    for (var i=0; i<selectOne.length; i++) {
  624: 		if (selectOne[i].selected) {
  625: 		    return selectOne[i].value;
  626: 		}
  627: 	    }
  628: 	} else {
  629:             // only one value it must be the selected one
  630: 	    return selectOne.value;
  631: 	}
  632:     }
  633: COMMONJSFUNCTIONS
  634: }
  635: 
  636: #--- Dumps the class list with usernames,list of sections,
  637: #--- section, ids and fullnames for each user.
  638: sub getclasslist {
  639:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  640:     my @getsec;
  641:     my @getgroup;
  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  643:     if (!ref($getsec)) {
  644: 	if ($getsec ne '' && $getsec ne 'all') {
  645: 	    @getsec=($getsec);
  646: 	}
  647:     } else {
  648: 	@getsec=@{$getsec};
  649:     }
  650:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  651:     if (!ref($getgroup)) {
  652: 	if ($getgroup ne '' && $getgroup ne 'all') {
  653: 	    @getgroup=($getgroup);
  654: 	}
  655:     } else {
  656: 	@getgroup=@{$getgroup};
  657:     }
  658:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  659: 
  660:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  661:     # Bail out if we were unable to get the classlist
  662:     return if (! defined($classlist));
  663:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  664:     #
  665:     my %sections;
  666:     my %fullnames;
  667:     my ($cdom,$cnum,$partlist);
  668:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  669:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  670:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  671:         my $res_error;
  672:         ($partlist) = &response_type($symb,\$res_error);
  673:     }
  674:     foreach my $student (keys(%$classlist)) {
  675:         my $end      = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  677:         my $start    = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  679:         my $id       = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  681:         my $section  = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  683:         my $fullname = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  685:         my $status   = 
  686:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  687:         my $group   = 
  688:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  689: 	# filter students according to status selected
  690: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  691: 	    if (!($stu_status =~ $status)) {
  692: 		delete($classlist->{$student});
  693: 		next;
  694: 	    }
  695: 	}
  696: 	# filter students according to groups selected
  697: 	my @stu_groups = split(/,/,$group);
  698: 	if (@getgroup) {
  699: 	    my $exclude = 1;
  700: 	    foreach my $grp (@getgroup) {
  701: 	        foreach my $stu_group (@stu_groups) {
  702: 	            if ($stu_group eq $grp) {
  703: 	                $exclude = 0;
  704:     	            } 
  705: 	        }
  706:     	        if (($grp eq 'none') && !$group) {
  707:         	    $exclude = 0;
  708:         	}
  709: 	    }
  710: 	    if ($exclude) {
  711: 	        delete($classlist->{$student});
  712: 		next;
  713: 	    }
  714: 	}
  715:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  716:             my $udom =
  717:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  718:             my $uname =
  719:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  720:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  721:                 if ($submitonly eq 'queued') {
  722:                     my %queue_status =
  723:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  724:                                                                 $udom,$uname);
  725:                     if (!defined($queue_status{'gradingqueue'})) {
  726:                         delete($classlist->{$student});
  727:                         next;
  728:                     }
  729:                 } else {
  730:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  731:                     my $submitted = 0;
  732:                     my $graded = 0;
  733:                     my $incorrect = 0;
  734:                     foreach (keys(%status)) {
  735:                         $submitted = 1 if ($status{$_} ne 'nothing');
  736:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  737:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  738: 
  739:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  740:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  741:                             $submitted = 0;
  742:                         }
  743:                     }
  744:                     if (!$submitted && ($submitonly eq 'yes' ||
  745:                                         $submitonly eq 'incorrect' ||
  746:                                         $submitonly eq 'graded')) {
  747:                         delete($classlist->{$student});
  748:                         next;
  749:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  750:                         delete($classlist->{$student});
  751:                         next;
  752:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  753:                         delete($classlist->{$student});
  754:                         next;
  755:                     }
  756:                 }
  757:             }
  758:         }
  759: 	$section = ($section ne '' ? $section : 'none');
  760: 	if (&canview($section)) {
  761: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  762: 		$sections{$section}++;
  763: 		if ($classlist->{$student}) {
  764: 		    $fullnames{$student}=$fullname;
  765: 		}
  766: 	    } else {
  767: 		delete($classlist->{$student});
  768: 	    }
  769: 	} else {
  770: 	    delete($classlist->{$student});
  771: 	}
  772:     }
  773:     my @sections = sort(keys(%sections));
  774:     return ($classlist,\@sections,\%fullnames);
  775: }
  776: 
  777: sub canmodify {
  778:     my ($sec)=@_;
  779:     if ($perm{'mgr'}) {
  780: 	if (!defined($perm{'mgr_section'})) {
  781: 	    # can modify whole class
  782: 	    return 1;
  783: 	} else {
  784: 	    if ($sec eq $perm{'mgr_section'}) {
  785: 		#can modify the requested section
  786: 		return 1;
  787: 	    } else {
  788: 		# can't modify the requested section
  789: 		return 0;
  790: 	    }
  791: 	}
  792:     }
  793:     #can't modify
  794:     return 0;
  795: }
  796: 
  797: sub canview {
  798:     my ($sec)=@_;
  799:     if ($perm{'vgr'}) {
  800: 	if (!defined($perm{'vgr_section'})) {
  801: 	    # can view whole class
  802: 	    return 1;
  803: 	} else {
  804: 	    if ($sec eq $perm{'vgr_section'}) {
  805: 		#can view the requested section
  806: 		return 1;
  807: 	    } else {
  808: 		# can't view the requested section
  809: 		return 0;
  810: 	    }
  811: 	}
  812:     }
  813:     #can't view
  814:     return 0;
  815: }
  816: 
  817: #--- Retrieve the grade status of a student for all the parts
  818: sub student_gradeStatus {
  819:     my ($symb,$udom,$uname,$partlist) = @_;
  820:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  821:     my %partstatus = ();
  822:     foreach (@$partlist) {
  823: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  824: 	$status              = 'nothing' if ($status eq '');
  825: 	$partstatus{$_}      = $status;
  826: 	my $subkey           = "resource.$_.submitted_by";
  827: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  828:     }
  829:     return %partstatus;
  830: }
  831: 
  832: # hidden form and javascript that calls the form
  833: # Use by verifyscript and viewgrades
  834: # Shows a student's view of problem and submission
  835: sub jscriptNform {
  836:     my ($symb) = @_;
  837:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  838:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  839: 	'    function viewOneStudent(user,domain) {'."\n".
  840: 	'	document.onestudent.student.value = user;'."\n".
  841: 	'	document.onestudent.userdom.value = domain;'."\n".
  842: 	'	document.onestudent.submit();'."\n".
  843: 	'    }'."\n".
  844: 	"\n");
  845:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  846: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  847: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  848: 	'<input type="hidden" name="command" value="submission" />'."\n".
  849: 	'<input type="hidden" name="student" value="" />'."\n".
  850: 	'<input type="hidden" name="userdom" value="" />'."\n".
  851: 	'</form>'."\n";
  852:     return $jscript;
  853: }
  854: 
  855: 
  856: 
  857: # Given the score (as a number [0-1] and the weight) what is the final
  858: # point value? This function will round to the nearest tenth, third,
  859: # or quarter if one of those is within the tolerance of .00001.
  860: sub compute_points {
  861:     my ($score, $weight) = @_;
  862:     
  863:     my $tolerance = .00001;
  864:     my $points = $score * $weight;
  865: 
  866:     # Check for nearness to 1/x.
  867:     my $check_for_nearness = sub {
  868:         my ($factor) = @_;
  869:         my $num = ($points * $factor) + $tolerance;
  870:         my $floored_num = floor($num);
  871:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  872:             return $floored_num / $factor;
  873:         }
  874:         return $points;
  875:     };
  876: 
  877:     $points = $check_for_nearness->(10);
  878:     $points = $check_for_nearness->(3);
  879:     $points = $check_for_nearness->(4);
  880:     
  881:     return $points;
  882: }
  883: 
  884: #------------------ End of general use routines --------------------
  885: 
  886: #
  887: # Find most similar essay
  888: #
  889: 
  890: sub most_similar {
  891:     my ($uname,$udom,$symb,$uessay)=@_;
  892: 
  893:     unless ($symb) { return ''; }
  894: 
  895:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  896: 
  897: # ignore spaces and punctuation
  898: 
  899:     $uessay=~s/\W+/ /gs;
  900: 
  901: # ignore empty submissions (occuring when only files are sent)
  902: 
  903:     unless ($uessay=~/\w+/s) { return ''; }
  904: 
  905: # these will be returned. Do not care if not at least 50 percent similar
  906:     my $limit=0.6;
  907:     my $sname='';
  908:     my $sdom='';
  909:     my $scrsid='';
  910:     my $sessay='';
  911: # go through all essays ...
  912:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  913: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  914: # ... except the same student
  915:         next if (($tname eq $uname) && ($tdom eq $udom));
  916: 	my $tessay=$old_essays{$symb}{$tkey};
  917: 	$tessay=~s/\W+/ /gs;
  918: # String similarity gives up if not even limit
  919: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  920: # Found one
  921: 	if ($tsimilar>$limit) {
  922: 	    $limit=$tsimilar;
  923: 	    $sname=$tname;
  924: 	    $sdom=$tdom;
  925: 	    $scrsid=$tcrsid;
  926: 	    $sessay=$old_essays{$symb}{$tkey};
  927: 	}
  928:     }
  929:     if ($limit>0.6) {
  930:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  931:     } else {
  932:        return ('','','','',0);
  933:     }
  934: }
  935: 
  936: #-------------------------------------------------------------------
  937: 
  938: #------------------------------------ Receipt Verification Routines
  939: #
  940: 
  941: sub initialverifyreceipt {
  942:    my ($request,$symb) = @_;
  943:    &commonJSfunctions($request);
  944:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  945:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  946:         '-<input type="text" name="receipt" size="4" />'.
  947:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  948:         '<input type="hidden" name="command" value="verify" />'.
  949:         "</form>\n";
  950: }
  951: 
  952: #--- Check whether a receipt number is valid.---
  953: sub verifyreceipt {
  954:     my ($request,$symb) = @_;
  955: 
  956:     my $courseid = $env{'request.course.id'};
  957:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  958: 	$env{'form.receipt'};
  959:     $receipt     =~ s/[^\-\d]//g;
  960: 
  961:     my $title =
  962: 	'<h3><span class="LC_info">'.
  963: 	&mt('Verifying Receipt Number [_1]',$receipt).
  964: 	'</span></h3>'."\n";
  965: 
  966:     my ($string,$contents,$matches) = ('','',0);
  967:     my (undef,undef,$fullname) = &getclasslist('all','0');
  968:     
  969:     my $receiptparts=0;
  970:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  971: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  972:     my $parts=['0'];
  973:     if ($receiptparts) {
  974:         my $res_error; 
  975:         ($parts)=&response_type($symb,\$res_error);
  976:         if ($res_error) {
  977:             return &navmap_errormsg();
  978:         } 
  979:     }
  980:     
  981:     my $header = 
  982: 	&Apache::loncommon::start_data_table().
  983: 	&Apache::loncommon::start_data_table_header_row().
  984: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  985: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  986: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  987:     if ($receiptparts) {
  988: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  989:     }
  990:     $header.=
  991: 	&Apache::loncommon::end_data_table_header_row();
  992: 
  993:     foreach (sort 
  994: 	     {
  995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  997: 		 }
  998: 		 return $a cmp $b;
  999: 	     } (keys(%$fullname))) {
 1000: 	my ($uname,$udom)=split(/\:/);
 1001: 	foreach my $part (@$parts) {
 1002: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
 1003: 		$contents.=
 1004: 		    &Apache::loncommon::start_data_table_row().
 1005: 		    '<td>&nbsp;'."\n".
 1006: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1007: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1008: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1009: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1010: 		if ($receiptparts) {
 1011: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1012: 		}
 1013: 		$contents.= 
 1014: 		    &Apache::loncommon::end_data_table_row()."\n";
 1015: 		
 1016: 		$matches++;
 1017: 	    }
 1018: 	}
 1019:     }
 1020:     if ($matches == 0) {
 1021:         $string = $title
 1022:                  .'<p class="LC_warning">'
 1023:                  .&mt('No match found for the above receipt number.')
 1024:                  .'</p>';
 1025:     } else {
 1026: 	$string = &jscriptNform($symb).$title.
 1027: 	    '<p>'.
 1028: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1029: 	    '</p>'.
 1030: 	    $header.
 1031: 	    $contents.
 1032: 	    &Apache::loncommon::end_data_table()."\n";
 1033:     }
 1034:     return $string;
 1035: }
 1036: 
 1037: #--- This is called by a number of programs.
 1038: #--- Called from the Grading Menu - View/Grade an individual student
 1039: #--- Also called directly when one clicks on the subm button 
 1040: #    on the problem page.
 1041: sub listStudents {
 1042:     my ($request,$symb,$submitonly,$divforres) = @_;
 1043: 
 1044:     my $is_tool   = ($symb =~ /ext\.tool$/);
 1045:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1046:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1047:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1048:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1049:     unless ($submitonly) {
 1050:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1051:     }
 1052: 
 1053:     my $result='';
 1054:     my $res_error;
 1055:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1056: 
 1057:     my $table;
 1058:     if (ref($partlist) eq 'ARRAY') {
 1059:         if (scalar(@$partlist) > 1 ) {
 1060:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1061:         } elsif ($divforres) {
 1062:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1063:         } else {
 1064:             $table = '<br clear="all" />';
 1065:         }
 1066:     }
 1067: 
 1068:     my %js_lt = &Apache::lonlocal::texthash (
 1069: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1070: 		'single'   => 'Please select the student before clicking on the Next button.',
 1071: 	     );
 1072:     &js_escape(\%js_lt);
 1073:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1074:     function checkSelect(checkBox) {
 1075: 	var ctr=0;
 1076: 	var sense="";
 1077: 	if (checkBox.length > 1) {
 1078: 	    for (var i=0; i<checkBox.length; i++) {
 1079: 		if (checkBox[i].checked) {
 1080: 		    ctr++;
 1081: 		}
 1082: 	    }
 1083: 	    sense = '$js_lt{'multiple'}';
 1084: 	} else {
 1085: 	    if (checkBox.checked) {
 1086: 		ctr = 1;
 1087: 	    }
 1088: 	    sense = '$js_lt{'single'}';
 1089: 	}
 1090: 	if (ctr == 0) {
 1091: 	    alert(sense);
 1092: 	    return false;
 1093: 	}
 1094: 	document.gradesub.submit();
 1095:     }
 1096: 
 1097:     function reLoadList(formname) {
 1098: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1099: 	formname.command.value = 'submission';
 1100: 	formname.submit();
 1101:     }
 1102: LISTJAVASCRIPT
 1103: 
 1104:     &commonJSfunctions($request);
 1105:     $request->print($result);
 1106: 
 1107:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1108: 	"\n".$table;
 1109: 
 1110:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1111:     unless ($is_tool) {
 1112:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1113:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1114:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1115:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1116:                       .&Apache::lonhtmlcommon::row_closure();
 1117:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1118:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1119:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1120:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1121:                       .&Apache::lonhtmlcommon::row_closure();
 1122:     }
 1123: 
 1124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1125:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1126:     $env{'form.Status'} = $saveStatus;
 1127:     my %optiontext;
 1128:     if ($is_tool) {
 1129:         %optiontext = &Apache::lonlocal::texthash (
 1130:                           lastonly => 'last transaction',
 1131:                           last     => 'last transaction with details',
 1132:                           datesub  => 'all transactions',
 1133:                           all      => 'all transactions with details',
 1134:                       );
 1135:     } else {
 1136:         %optiontext = &Apache::lonlocal::texthash (
 1137:                           lastonly => 'last submission',
 1138:                           last     => 'last submission with details',
 1139:                           datesub  => 'all submissions',
 1140:                           all      => 'all submissions with details',
 1141:                       );
 1142:     }
 1143:     my $submission_options =
 1144:         '<span class="LC_nobreak">'.
 1145:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1146:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1147:         '<span class="LC_nobreak">'.
 1148:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1149:         $optiontext{'last'}.' </label></span>'."\n".
 1150:         '<span class="LC_nobreak">'.
 1151:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1152:         $optiontext{'datesub'}.'</label></span>'."\n".
 1153:         '<span class="LC_nobreak">'.
 1154:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1155:         $optiontext{'all'}.'</label></span>';
 1156:     my $viewtitle;
 1157:     if ($is_tool) {
 1158:         $viewtitle = &mt('View Transactions');
 1159:     } else {
 1160:         $viewtitle = &mt('View Submissions');
 1161:     }
 1162:     my ($compmsg,$nocompmsg);
 1163:     $nocompmsg = ' checked="checked"';
 1164:     if ($numessay) {
 1165:         $compmsg = $nocompmsg;
 1166:         $nocompmsg = '';
 1167:     }
 1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1169:                   .$submission_options
 1170:                   .&Apache::lonhtmlcommon::row_closure()
 1171:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1172:                   .'<span class="LC_nobreak">'
 1173:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1174:                   .&mt('No').('&nbsp;'x2).'</label>'
 1175:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1176:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1177:                   .&Apache::lonhtmlcommon::row_closure();
 1178: 
 1179:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1180:                   .'<select name="increment">'
 1181:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1182:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1183:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1184:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1185:                   .'</select>';
 1186:     $gradeTable .= 
 1187:         &build_section_inputs().
 1188: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1189: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1190: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1191:     if (exists($env{'form.Status'})) {
 1192: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1193:     } else {
 1194:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1195:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1196:                       .&Apache::lonhtmlcommon::StatusOptions(
 1197:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1198:     }
 1199:     if ($numessay) {
 1200:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1201:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1202:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1203:     }
 1204:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1205:                   .&Apache::lonhtmlcommon::end_pick_box();
 1206:     my $regrademsg;
 1207:     if ($is_tool) {
 1208:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1209:     } else {
 1210:         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1211:     }
 1212:     $gradeTable .= '<p>'
 1213:                   .$regrademsg."\n"
 1214:                   .'<input type="hidden" name="command" value="processGroup" />'
 1215:                   .'</p>';
 1216: 
 1217: # checkall buttons
 1218:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1219:     $gradeTable.='<input type="button" '."\n".
 1220:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1221:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1222:     $gradeTable.=&check_buttons();
 1223:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1224:     $gradeTable.= &Apache::loncommon::start_data_table().
 1225: 	&Apache::loncommon::start_data_table_header_row();
 1226:     my $loop = 0;
 1227:     while ($loop < 2) {
 1228: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1229: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1230: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1231: 	    foreach my $part (sort(@$partlist)) {
 1232: 		my $display_part=
 1233: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1234: 		$gradeTable.=
 1235: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1236: 	    }
 1237: 	} elsif ($submitonly eq 'queued') {
 1238: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1239: 	}
 1240: 	$loop++;
 1241: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1242:     }
 1243:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1244: 
 1245:     my $ctr = 0;
 1246:     foreach my $student (sort 
 1247: 			 {
 1248: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1249: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1250: 			     }
 1251: 			     return $a cmp $b;
 1252: 			 }
 1253: 			 (keys(%$fullname))) {
 1254: 	my ($uname,$udom) = split(/:/,$student);
 1255: 
 1256: 	my %status = ();
 1257: 
 1258: 	if ($submitonly eq 'queued') {
 1259: 	    my %queue_status = 
 1260: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1261: 							$udom,$uname);
 1262: 	    next if (!defined($queue_status{'gradingqueue'}));
 1263: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1264: 	}
 1265: 
 1266: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1267: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1268: 	    my $submitted = 0;
 1269: 	    my $graded = 0;
 1270: 	    my $incorrect = 0;
 1271: 	    foreach (keys(%status)) {
 1272: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1273: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1274: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1275: 		
 1276: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1277: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1278: 		    $submitted = 0;
 1279: 		    my ($part)=split(/\./,$partid);
 1280: 		    $gradeTable.='<input type="hidden" name="'.
 1281: 			$student.':'.$part.':submitted_by" value="'.
 1282: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1283: 		}
 1284: 	    }
 1285: 	    
 1286: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1287: 				     $submitonly eq 'incorrect' ||
 1288: 				     $submitonly eq 'graded'));
 1289: 	    next if (!$graded && ($submitonly eq 'graded'));
 1290: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1291: 	}
 1292: 
 1293: 	$ctr++;
 1294: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1295:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1296: 	if ( $perm{'vgr'} eq 'F' ) {
 1297: 	    if ($ctr%2 ==1) {
 1298: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1299: 	    }
 1300: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1301:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1302:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1303: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1304: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1305: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1306: 
 1307: 	    if ($submitonly ne 'all') {
 1308: 		foreach (sort(keys(%status))) {
 1309: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1310: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1311: 		}
 1312: 	    }
 1313: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1314: 	    if ($ctr%2 ==0) {
 1315: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1316: 	    }
 1317: 	}
 1318:     }
 1319:     if ($ctr%2 ==1) {
 1320: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1321: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1322: 		foreach (@$partlist) {
 1323: 		    $gradeTable.='<td>&nbsp;</td>';
 1324: 		}
 1325: 	    } elsif ($submitonly eq 'queued') {
 1326: 		$gradeTable.='<td>&nbsp;</td>';
 1327: 	    }
 1328: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1329:     }
 1330: 
 1331:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1332:         '<input type="button" '.
 1333:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1334:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1335:     if ($ctr == 0) {
 1336: 	my $num_students=(scalar(keys(%$fullname)));
 1337: 	if ($num_students eq 0) {
 1338: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1339: 	} else {
 1340: 	    my $submissions='submissions';
 1341: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1342: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1343: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1344: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1345: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1346: 		    $num_students).
 1347: 		'</span><br />';
 1348: 	}
 1349:     } elsif ($ctr == 1) {
 1350: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1351:     }
 1352:     $request->print($gradeTable);
 1353:     return '';
 1354: }
 1355: 
 1356: #---- Called from the listStudents routine
 1357: 
 1358: sub check_script {
 1359:     my ($form,$type) = @_;
 1360:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1361:     function checkall() {
 1362:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1363:             ele = document.forms.'.$form.'.elements[i];
 1364:             if (ele.name == "'.$type.'") {
 1365:             document.forms.'.$form.'.elements[i].checked=true;
 1366:                                        }
 1367:         }
 1368:     }
 1369: 
 1370:     function checksec() {
 1371:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1372:             ele = document.forms.'.$form.'.elements[i];
 1373:            string = document.forms.'.$form.'.chksec.value;
 1374:            if
 1375:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1376:               document.forms.'.$form.'.elements[i].checked=true;
 1377:             }
 1378:         }
 1379:     }
 1380: 
 1381: 
 1382:     function uncheckall() {
 1383:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1384:             ele = document.forms.'.$form.'.elements[i];
 1385:             if (ele.name == "'.$type.'") {
 1386:             document.forms.'.$form.'.elements[i].checked=false;
 1387:                                        }
 1388:         }
 1389:     }
 1390: 
 1391: '."\n");
 1392:     return $chkallscript;
 1393: }
 1394: 
 1395: sub check_buttons {
 1396:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1397:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1398:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1399:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1400:     return $buttons;
 1401: }
 1402: 
 1403: #     Displays the submissions for one student or a group of students
 1404: sub processGroup {
 1405:     my ($request,$symb) = @_;
 1406:     my $ctr        = 0;
 1407:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1408:     my $total      = scalar(@stuchecked)-1;
 1409: 
 1410:     foreach my $student (@stuchecked) {
 1411: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1412: 	$env{'form.student'}        = $uname;
 1413: 	$env{'form.userdom'}        = $udom;
 1414: 	$env{'form.fullname'}       = $fullname;
 1415: 	&submission($request,$ctr,$total,$symb);
 1416: 	$ctr++;
 1417:     }
 1418:     return '';
 1419: }
 1420: 
 1421: #------------------------------------------------------------------------------------
 1422: #
 1423: #-------------------------- Next few routines handles grading by student, essentially
 1424: #                           handles essay response type problem/part
 1425: #
 1426: #--- Javascript to handle the submission page functionality ---
 1427: sub sub_page_js {
 1428:     my $request = shift;
 1429:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1430:     &js_escape(\$alertmsg);
 1431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1432:     function updateRadio(formname,id,weight) {
 1433: 	var gradeBox = formname["GD_BOX"+id];
 1434: 	var radioButton = formname["RADVAL"+id];
 1435: 	var oldpts = formname["oldpts"+id].value;
 1436: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1437: 	gradeBox.value = pts;
 1438: 	var resetbox = false;
 1439: 	if (isNaN(pts) || pts < 0) {
 1440: 	    alert("$alertmsg"+pts);
 1441: 	    for (var i=0; i<radioButton.length; i++) {
 1442: 		if (radioButton[i].checked) {
 1443: 		    gradeBox.value = i;
 1444: 		    resetbox = true;
 1445: 		}
 1446: 	    }
 1447: 	    if (!resetbox) {
 1448: 		formtextbox.value = "";
 1449: 	    }
 1450: 	    return;
 1451: 	}
 1452: 
 1453: 	if (pts > weight) {
 1454: 	    var resp = confirm("You entered a value ("+pts+
 1455: 			       ") greater than the weight for the part. Accept?");
 1456: 	    if (resp == false) {
 1457: 		gradeBox.value = oldpts;
 1458: 		return;
 1459: 	    }
 1460: 	}
 1461: 
 1462: 	for (var i=0; i<radioButton.length; i++) {
 1463: 	    radioButton[i].checked=false;
 1464: 	    if (pts == i && pts != "") {
 1465: 		radioButton[i].checked=true;
 1466: 	    }
 1467: 	}
 1468: 	updateSelect(formname,id);
 1469: 	formname["stores"+id].value = "0";
 1470:     }
 1471: 
 1472:     function writeBox(formname,id,pts) {
 1473: 	var gradeBox = formname["GD_BOX"+id];
 1474: 	if (checkSolved(formname,id) == 'update') {
 1475: 	    gradeBox.value = pts;
 1476: 	} else {
 1477: 	    var oldpts = formname["oldpts"+id].value;
 1478: 	    gradeBox.value = oldpts;
 1479: 	    var radioButton = formname["RADVAL"+id];
 1480: 	    for (var i=0; i<radioButton.length; i++) {
 1481: 		radioButton[i].checked=false;
 1482: 		if (i == oldpts) {
 1483: 		    radioButton[i].checked=true;
 1484: 		}
 1485: 	    }
 1486: 	}
 1487: 	formname["stores"+id].value = "0";
 1488: 	updateSelect(formname,id);
 1489: 	return;
 1490:     }
 1491: 
 1492:     function clearRadBox(formname,id) {
 1493: 	if (checkSolved(formname,id) == 'noupdate') {
 1494: 	    updateSelect(formname,id);
 1495: 	    return;
 1496: 	}
 1497: 	gradeSelect = formname["GD_SEL"+id];
 1498: 	for (var i=0; i<gradeSelect.length; i++) {
 1499: 	    if (gradeSelect[i].selected) {
 1500: 		var selectx=i;
 1501: 	    }
 1502: 	}
 1503: 	var stores = formname["stores"+id];
 1504: 	if (selectx == stores.value) { return };
 1505: 	var gradeBox = formname["GD_BOX"+id];
 1506: 	gradeBox.value = "";
 1507: 	var radioButton = formname["RADVAL"+id];
 1508: 	for (var i=0; i<radioButton.length; i++) {
 1509: 	    radioButton[i].checked=false;
 1510: 	}
 1511: 	stores.value = selectx;
 1512:     }
 1513: 
 1514:     function checkSolved(formname,id) {
 1515: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1516: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1517: 	    if (!reply) {return "noupdate";}
 1518: 	    formname.overRideScore.value = 'yes';
 1519: 	}
 1520: 	return "update";
 1521:     }
 1522: 
 1523:     function updateSelect(formname,id) {
 1524: 	formname["GD_SEL"+id][0].selected = true;
 1525: 	return;
 1526:     }
 1527: 
 1528: //=========== Check that a point is assigned for all the parts  ============
 1529:     function checksubmit(formname,val,total,parttot) {
 1530: 	formname.gradeOpt.value = val;
 1531: 	if (val == "Save & Next") {
 1532: 	    for (i=0;i<=total;i++) {
 1533: 		for (j=0;j<parttot;j++) {
 1534: 		    var partid = formname["partid"+i+"_"+j].value;
 1535: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1536: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1537: 			if (points == "") {
 1538: 			    var name = formname["name"+i].value;
 1539: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1540: 			    var resp = confirm("You did not assign a score for "+studentID+
 1541: 					       ", part "+partid+". Continue?");
 1542: 			    if (resp == false) {
 1543: 				formname["GD_BOX"+i+"_"+partid].focus();
 1544: 				return false;
 1545: 			    }
 1546: 			}
 1547: 		    }
 1548: 		}
 1549: 	    }
 1550: 	}
 1551: 	formname.submit();
 1552:     }
 1553: 
 1554: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1555:     function checkSubmitPage(formname,total) {
 1556: 	noscore = new Array(100);
 1557: 	var ptr = 0;
 1558: 	for (i=1;i<total;i++) {
 1559: 	    var partid = formname["q_"+i].value;
 1560: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1561: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1562: 		var status = formname["solved"+i+"_"+partid].value;
 1563: 		if (points == "" && status != "correct_by_student") {
 1564: 		    noscore[ptr] = i;
 1565: 		    ptr++;
 1566: 		}
 1567: 	    }
 1568: 	}
 1569: 	if (ptr != 0) {
 1570: 	    var sense = ptr == 1 ? ": " : "s: ";
 1571: 	    var prolist = "";
 1572: 	    if (ptr == 1) {
 1573: 		prolist = noscore[0];
 1574: 	    } else {
 1575: 		var i = 0;
 1576: 		while (i < ptr-1) {
 1577: 		    prolist += noscore[i]+", ";
 1578: 		    i++;
 1579: 		}
 1580: 		prolist += "and "+noscore[i];
 1581: 	    }
 1582: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1583: 	    if (resp == false) {
 1584: 		return false;
 1585: 	    }
 1586: 	}
 1587: 
 1588: 	formname.submit();
 1589:     }
 1590: SUBJAVASCRIPT
 1591: }
 1592: 
 1593: #--- javascript for grading message center
 1594: sub sub_grademessage_js {
 1595:     my $request = shift;
 1596:     my $iconpath = $request->dir_config('lonIconsURL');
 1597:     &commonJSfunctions($request);
 1598: 
 1599:     my $inner_js_msg_central= (<<INNERJS);
 1600: <script type="text/javascript">
 1601:     function checkInput() {
 1602:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1603:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1604:       var usrctr = document.msgcenter.usrctr.value;
 1605:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1606:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1607: 
 1608:       var msgchk = "";
 1609:       if (document.msgcenter.subchk.checked) {
 1610:          msgchk = "msgsub,";
 1611:       }
 1612:       var includemsg = 0;
 1613:       for (var i=1; i<=nmsg; i++) {
 1614:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1615:           var frmmsg = document.msgcenter["msg"+i];
 1616:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1617:           var showflg = opener.document.SCORE["shownOnce"+i];
 1618:           showflg.value = "1";
 1619:           var chkbox = document.msgcenter["msgn"+i];
 1620:           if (chkbox.checked) {
 1621:              msgchk += "savemsg"+i+",";
 1622:              includemsg = 1;
 1623:           }
 1624:       }
 1625:       if (document.msgcenter.newmsgchk.checked) {
 1626:          msgchk += "newmsg"+usrctr;
 1627:          includemsg = 1;
 1628:       }
 1629:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1630:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1631:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1632:       includemsg.value = msgchk;
 1633: 
 1634:       self.close()
 1635: 
 1636:     }
 1637: </script>
 1638: INNERJS
 1639: 
 1640:     my $start_page_msg_central =
 1641:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1642: 				       {'js_ready'  => 1,
 1643: 					'only_body' => 1,
 1644: 					'bgcolor'   =>'#FFFFFF',});
 1645:     my $end_page_msg_central =
 1646: 	&Apache::loncommon::end_page({'js_ready' => 1});
 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("<\\/table>");
 1776:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1777:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1778:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1779:     pDoc.write("<\\/form>");
 1780:     pDoc.write('$end_page_msg_central');
 1781:     pDoc.close();
 1782: }
 1783: 
 1784: SUBJAVASCRIPT
 1785: }
 1786: 
 1787: #--- javascript for essay type problem --
 1788: sub sub_page_kw_js {
 1789:     my $request = shift;
 1790: 
 1791:     unless ($env{'form.compmsg'}) {
 1792:         &commonJSfunctions($request);
 1793:     }
 1794: 
 1795:     my $inner_js_highlight_central= (<<INNERJS);
 1796: <script type="text/javascript">
 1797:     function updateChoice(flag) {
 1798:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1799:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1800:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1801:       opener.document.SCORE.refresh.value = "on";
 1802:       if (opener.document.SCORE.keywords.value!=""){
 1803:          opener.document.SCORE.submit();
 1804:       }
 1805:       self.close()
 1806:     }
 1807: </script>
 1808: INNERJS
 1809: 
 1810:     my $start_page_highlight_central =
 1811:         &Apache::loncommon::start_page('Highlight Central',
 1812:                                        $inner_js_highlight_central,
 1813:                                        {'js_ready'  => 1,
 1814:                                         'only_body' => 1,
 1815:                                         'bgcolor'   =>'#FFFFFF',});
 1816:     my $end_page_highlight_central =
 1817:         &Apache::loncommon::end_page({'js_ready' => 1});
 1818: 
 1819:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1820:     $docopen=~s/^document\.//;
 1821: 
 1822:     my %js_lt = &Apache::lonlocal::texthash(
 1823:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1824:                 plse => 'Please select a word or group of words from document and then click this link.',
 1825:                 adds => 'Add selection to keyword list? Edit if desired.',
 1826:                 col1 => 'red',
 1827:                 col2 => 'green',
 1828:                 col3 => 'blue',
 1829:                 siz1 => 'normal',
 1830:                 siz2 => '+1',
 1831:                 siz3 => '+2',
 1832:                 sty1 => 'normal',
 1833:                 sty2 => 'italic',
 1834:                 sty3 => 'bold',
 1835:              );
 1836:     my %html_js_lt = &Apache::lonlocal::texthash(
 1837:                 save => 'Save',
 1838:                 canc => 'Cancel',
 1839:                 kehi => 'Keyword Highlight Options',
 1840:                 txtc => 'Text Color',
 1841:                 font => 'Font Size',
 1842:                 fnst => 'Font Style',
 1843:              );
 1844:     &js_escape(\%js_lt);
 1845:     &html_escape(\%html_js_lt);
 1846:     &js_escape(\%html_js_lt);
 1847:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1848: 
 1849: //===================== Show list of keywords ====================
 1850:   function keywords(formname) {
 1851:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1852:     if (nret==null) return;
 1853:     formname.keywords.value = nret;
 1854: 
 1855:     if (formname.keywords.value != "") {
 1856:         formname.refresh.value = "on";
 1857:         formname.submit();
 1858:     }
 1859:     return;
 1860:   }
 1861: 
 1862: //===================== Script to add keyword(s) ==================
 1863:   function getSel() {
 1864:     if (document.getSelection) txt = document.getSelection();
 1865:     else if (document.selection) txt = document.selection.createRange().text;
 1866:     else return;
 1867:     if (typeof(txt) != 'string') {
 1868:         txt = String(txt);
 1869:     }
 1870:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1871:     if (cleantxt=="") {
 1872:         alert("$js_lt{'plse'}");
 1873:         return;
 1874:     }
 1875:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1876:     if (nret==null) return;
 1877:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1878:     if (document.SCORE.keywords.value != "") {
 1879:         document.SCORE.refresh.value = "on";
 1880:         document.SCORE.submit();
 1881:     }
 1882:     return;
 1883:   }
 1884: 
 1885: //====================== Script for keyword highlight options ==============
 1886:   function kwhighlight() {
 1887:     var kwclr    = document.SCORE.kwclr.value;
 1888:     var kwsize   = document.SCORE.kwsize.value;
 1889:     var kwstyle  = document.SCORE.kwstyle.value;
 1890:     var redsel = "";
 1891:     var grnsel = "";
 1892:     var blusel = "";
 1893:     var txtcol1 = "$js_lt{'col1'}";
 1894:     var txtcol2 = "$js_lt{'col2'}";
 1895:     var txtcol3 = "$js_lt{'col3'}";
 1896:     var txtsiz1 = "$js_lt{'siz1'}";
 1897:     var txtsiz2 = "$js_lt{'siz2'}";
 1898:     var txtsiz3 = "$js_lt{'siz3'}";
 1899:     var txtsty1 = "$js_lt{'sty1'}";
 1900:     var txtsty2 = "$js_lt{'sty2'}";
 1901:     var txtsty3 = "$js_lt{'sty3'}";
 1902:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1903:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1904:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1905:     var sznsel = "";
 1906:     var sz1sel = "";
 1907:     var sz2sel = "";
 1908:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1909:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1910:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1911:     var synsel = "";
 1912:     var syisel = "";
 1913:     var sybsel = "";
 1914:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1915:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1916:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1917:     highlightCentral();
 1918:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1919:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1920:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1921:     highlightend();
 1922:     return;
 1923:   }
 1924: 
 1925:   function highlightCentral() {
 1926: //    if (window.hwdWin) window.hwdWin.close();
 1927:     var xpos = (screen.width-400)/2;
 1928:     xpos = (xpos < 0) ? '0' : xpos;
 1929:     var ypos = (screen.height-330)/2-30;
 1930:     ypos = (ypos < 0) ? '0' : ypos;
 1931: 
 1932:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1933:     hwdWin.focus();
 1934:     var hDoc = hwdWin.document;
 1935:     hDoc.$docopen;
 1936:     hDoc.write('$start_page_highlight_central');
 1937:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1938:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1939: 
 1940:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1941:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1942:   }
 1943: 
 1944:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1945:     var hDoc = hwdWin.document;
 1946:     hDoc.write("<tr>");
 1947:     hDoc.write("<td align=\\"left\\">");
 1948:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1949:     hDoc.write("<td align=\\"left\\">");
 1950:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1951:     hDoc.write("<td align=\\"left\\">");
 1952:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1953:     hDoc.write("<\\/tr>");
 1954:   }
 1955: 
 1956:   function highlightend() { 
 1957:     var hDoc = hwdWin.document;
 1958:     hDoc.write("<\\/table><br \\/>");
 1959:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1960:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1961:     hDoc.write("<\\/form>");
 1962:     hDoc.write('$end_page_highlight_central');
 1963:     hDoc.close();
 1964:   }
 1965: 
 1966: SUBJAVASCRIPT
 1967: }
 1968: 
 1969: sub get_increment {
 1970:     my $increment = $env{'form.increment'};
 1971:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1972:         $increment != .1) {
 1973:         $increment = 1;
 1974:     }
 1975:     return $increment;
 1976: }
 1977: 
 1978: sub gradeBox_start {
 1979:     return (
 1980:         &Apache::loncommon::start_data_table()
 1981:        .&Apache::loncommon::start_data_table_header_row()
 1982:        .'<th>'.&mt('Part').'</th>'
 1983:        .'<th>'.&mt('Points').'</th>'
 1984:        .'<th>&nbsp;</th>'
 1985:        .'<th>'.&mt('Assign Grade').'</th>'
 1986:        .'<th>'.&mt('Weight').'</th>'
 1987:        .'<th>'.&mt('Grade Status').'</th>'
 1988:        .&Apache::loncommon::end_data_table_header_row()
 1989:     );
 1990: }
 1991: 
 1992: sub gradeBox_end {
 1993:     return (
 1994:         &Apache::loncommon::end_data_table()
 1995:     );
 1996: }
 1997: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1998: sub gradeBox {
 1999:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 2000:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2001: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2002:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2003:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2004:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2005:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2006:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2007: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2008:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2009:     my $display_part= &get_display_part($partid,$symb);
 2010:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2011: 				       [$partid]);
 2012:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2013:     if ($last_resets{$partid}) {
 2014:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2015:     }
 2016:     my $result=&Apache::loncommon::start_data_table_row();
 2017:     my $ctr = 0;
 2018:     my $thisweight = 0;
 2019:     my $increment = &get_increment();
 2020: 
 2021:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2022:     while ($thisweight<=$wgt) {
 2023: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2024:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2025: 	    $thisweight.')" value="'.$thisweight.'" '.
 2026: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2027: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2028:         $thisweight += $increment;
 2029: 	$ctr++;
 2030:     }
 2031:     $radio.='</tr></table>';
 2032: 
 2033:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2034: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2035: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2036: 	$wgt.')" /></td>'."\n";
 2037:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2038: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2039: 	' </td>'."\n";
 2040:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2041: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2042:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2043: 	$line.='<option></option>'.
 2044: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2045:     } else {
 2046: 	$line.='<option selected="selected"></option>'.
 2047: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2048:     }
 2049:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2050: 
 2051: 
 2052:     $result .= 
 2053: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2054:     $result.=&Apache::loncommon::end_data_table_row();
 2055:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2056:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2057: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2058: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2059: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2060:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2061:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2062:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2063:         $aggtries.'" />'."\n";
 2064:     my $res_error;
 2065:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2066:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2067:     if ($res_error) {
 2068:         return &navmap_errormsg();
 2069:     }
 2070:     return $result;
 2071: }
 2072: 
 2073: sub handback_box {
 2074:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2075:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2076:     return unless ($numessay);
 2077:     my (@respids);
 2078:     my @part_response_id = &flatten_responseType($responseType);
 2079:     foreach my $part_response_id (@part_response_id) {
 2080:     	my ($part,$resp) = @{ $part_response_id };
 2081:         if ($part eq $partid) {
 2082:             push(@respids,$resp);
 2083:         }
 2084:     }
 2085:     my $result;
 2086:     foreach my $respid (@respids) {
 2087: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2088: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2089: 	next if (!@$files);
 2090: 	my $file_counter = 0;
 2091: 	foreach my $file (@$files) {
 2092: 	    if ($file =~ /\/portfolio\//) {
 2093:                 $file_counter++;
 2094:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2095:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2096:     	        $file_disp = "$name.$ext";
 2097:     	        $file = $file_path.$file_disp;
 2098:     	        $result.=&mt('Return commented version of [_1] to student.',
 2099:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2100:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2101:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2102: 	    }
 2103: 	}
 2104:         if ($file_counter) {
 2105:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2106:                        '<span class="LC_info">'.
 2107:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2108:         }
 2109:     }
 2110:     return $result;    
 2111: }
 2112: 
 2113: sub show_problem {
 2114:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2115:     my $rendered;
 2116:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2117:     &Apache::lonxml::remember_problem_counter();
 2118:     if ($mode eq 'both' or $mode eq 'text') {
 2119: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2120: 						       $env{'request.course.id'},
 2121: 						       undef,\%form);
 2122:     }
 2123:     if ($removeform) {
 2124: 	$rendered=~s|<form(.*?)>||g;
 2125: 	$rendered=~s|</form>||g;
 2126: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2127:     }
 2128:     my $companswer;
 2129:     if ($mode eq 'both' or $mode eq 'answer') {
 2130: 	&Apache::lonxml::restore_problem_counter();
 2131: 	$companswer=
 2132: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2133: 						    $env{'request.course.id'},
 2134: 						    %form);
 2135:     }
 2136:     if ($removeform) {
 2137: 	$companswer=~s|<form(.*?)>||g;
 2138: 	$companswer=~s|</form>||g;
 2139: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2140:     }
 2141:     my $renderheading = &mt('View of the problem');
 2142:     my $answerheading = &mt('Correct answer');
 2143:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2144:         my $stu_fullname = $env{'form.fullname'};
 2145:         if ($stu_fullname eq '') {
 2146:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2147:         }
 2148:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2149:         if ($forwhom ne '') {
 2150:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2151:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2152:         }
 2153:     }
 2154:     $rendered=
 2155:         '<div class="LC_Box">'
 2156:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2157:        .$rendered
 2158:        .'</div>';
 2159:     $companswer=
 2160:         '<div class="LC_Box">'
 2161:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2162:        .$companswer
 2163:        .'</div>';
 2164:     my $result;
 2165:     if ($mode eq 'both') {
 2166:         $result=$rendered.$companswer;
 2167:     } elsif ($mode eq 'text') {
 2168:         $result=$rendered;
 2169:     } elsif ($mode eq 'answer') {
 2170:         $result=$companswer;
 2171:     }
 2172:     return $result;
 2173: }
 2174: 
 2175: sub files_exist {
 2176:     my ($r, $symb) = @_;
 2177:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2178:     foreach my $student (@students) {
 2179:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2180:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2181: 					      $udom,$uname);
 2182:         my ($string,$timestamp)= &get_last_submission(\%record);
 2183:         foreach my $submission (@$string) {
 2184:             my ($partid,$respid) =
 2185: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2186:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2187: 					   \%record);
 2188:             return 1 if (@$files);
 2189:         }
 2190:     }
 2191:     return 0;
 2192: }
 2193: 
 2194: sub download_all_link {
 2195:     my ($r,$symb) = @_;
 2196:     unless (&files_exist($r, $symb)) {
 2197:         $r->print(&mt('There are currently no submitted documents.'));
 2198:         return;
 2199:     }
 2200:     my $all_students = 
 2201: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2202: 
 2203:     my $parts =
 2204: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2205: 
 2206:     my $identifier = &Apache::loncommon::get_cgi_id();
 2207:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2208:                              'cgi.'.$identifier.'.symb' => $symb,
 2209:                              'cgi.'.$identifier.'.parts' => $parts,});
 2210:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2211: 	      &mt('Download All Submitted Documents').'</a>');
 2212:     return;
 2213: }
 2214: 
 2215: sub submit_download_link {
 2216:     my ($request,$symb) = @_;
 2217:     if (!$symb) { return ''; }
 2218:     my $res_error;
 2219:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2220:         &response_type($symb,\$res_error);
 2221:     if ($res_error) {
 2222:         $request->print(&mt('An error occurred retrieving response types'));
 2223:         return;
 2224:     }
 2225:     unless ($numessay) {
 2226:         $request->print(&mt('No essayresponse items found'));
 2227:         return;
 2228:     }
 2229:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2230:     if (@chosenparts) {
 2231:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2232:                                           undef,undef,1));
 2233:     }
 2234:     if ($numessay) {
 2235:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2236:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2237:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2238:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2239:         if (ref($fullname) eq 'HASH') {
 2240:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2241:             if (@students) {
 2242:                 @{$env{'form.stuinfo'}} = @students;
 2243:                 if ($numdropbox) {
 2244:                     &download_all_link($request,$symb);
 2245:                 } else {
 2246:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2247:                 }
 2248: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2249: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2250:             } else {
 2251:                 $request->print(&mt('No students match the criteria you selected'));
 2252:             }
 2253:         } else {
 2254:             $request->print(&mt('Could not retrieve student information'));
 2255:         }
 2256:     } else {
 2257:         $request->print(&mt('No essayresponse items found'));
 2258:     }
 2259:     return;
 2260: }
 2261: 
 2262: sub build_section_inputs {
 2263:     my $section_inputs;
 2264:     if ($env{'form.section'} eq '') {
 2265:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2266:     } else {
 2267:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2268:         foreach my $section (@sections) {
 2269:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2270:         }
 2271:     }
 2272:     return $section_inputs;
 2273: }
 2274: 
 2275: # --------------------------- show submissions of a student, option to grade 
 2276: sub submission {
 2277:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2278:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2279:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2280:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2281:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2282: 
 2283:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2284:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2285:     my $is_tool = ($symb =~ /ext\.tool$/);
 2286:     my ($essayurl,%coursedesc_by_cid);
 2287: 
 2288:     if (!&canview($usec)) {
 2289:         $request->print(
 2290:             '<span class="LC_warning">'.
 2291:             &mt('Unable to view requested student.').
 2292:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2293:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2294:             '</span>');
 2295: 	return;
 2296:     }
 2297: 
 2298:     my $res_error;
 2299:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2300:         &response_type($symb,\$res_error);
 2301:     if ($res_error) {
 2302:         $request->print(&navmap_errormsg());
 2303:         return;
 2304:     }
 2305: 
 2306:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2307:     unless ($is_tool) { 
 2308:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2309:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2310:     }
 2311:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2312:         $env{'form.compmsg'} = 1;
 2313:     }
 2314:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2315:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2316: 	'" src="'.$request->dir_config('lonIconsURL').
 2317: 	'/check.gif" height="16" border="0" />';
 2318: 
 2319:     # header info
 2320:     if ($counter == 0) {
 2321:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2322:         if (@chosenparts) {
 2323:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2324:         } elsif ($divforres) {
 2325:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2326:         } else {
 2327:             $request->print('<br clear="all" />');
 2328:         }
 2329: 	&sub_page_js($request);
 2330:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2331: 	&sub_page_kw_js($request) if ($numessay);
 2332: 
 2333: 	# option to display problem, only once else it cause problems 
 2334:         # with the form later since the problem has a form.
 2335: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2336: 	    my $mode;
 2337: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2338: 		$mode='both';
 2339: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2340: 		$mode='text';
 2341: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2342: 		$mode='answer';
 2343: 	    }
 2344: 	    &Apache::lonxml::clear_problem_counter();
 2345: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2346: 	}
 2347: 
 2348: 	my %keyhash = ();
 2349: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2350: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2351: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2352: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2353: 	}
 2354: 	# kwclr is the only variable that is guaranteed not to be blank
 2355: 	# if this subroutine has been called once.
 2356: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2357: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2358: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2359: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2360: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2361: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2362: 	}
 2363: 	if ($env{'form.compmsg'}) {
 2364: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2365: 		$keyhash{$symb.'_subject'} : $probtitle;
 2366: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2367: 	}
 2368: 
 2369: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2370: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2371: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2372: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2373: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2374: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2375: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2376: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2377: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2378: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2379: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2380: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2381: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2382: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2383: 			&build_section_inputs().
 2384: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2385: 			'<input type="hidden" name="NCT"'.
 2386: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2387: 	if ($env{'form.compmsg'}) {
 2388: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2389: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2390: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2391: 	}
 2392: 	if ($numessay) {
 2393: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2394: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2395: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2396: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2397: 	}
 2398: 
 2399: 	my ($cts,$prnmsg) = (1,'');
 2400: 	while ($cts <= $env{'form.savemsgN'}) {
 2401: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2402: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2403: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2404: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2405: 		'" />'."\n".
 2406: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2407: 	    $cts++;
 2408: 	}
 2409: 	$request->print($prnmsg);
 2410: 
 2411: 	if ($numessay) {
 2412: 
 2413:             my %lt = &Apache::lonlocal::texthash(
 2414:                           keyh => 'Keyword Highlighting for Essays',
 2415:                           keyw => 'Keyword Options',
 2416:                           list => 'List',
 2417:                           past => 'Paste Selection to List',
 2418:                           high => 'Highlight Attribute',
 2419:                      );
 2420: #
 2421: # Print out the keyword options line
 2422: #
 2423: 	    $request->print(
 2424:                 '<div class="LC_columnSection">'
 2425:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2426:                .&Apache::lonhtmlcommon::funclist_from_array(
 2427:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2428:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2429:  class="page">'.$lt{'past'}.'</a>',
 2430:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2431:                     {legend => $lt{'keyw'}})
 2432:                .'</fieldset></div>'
 2433:             );
 2434: 
 2435: #
 2436: # Load the other essays for similarity check
 2437: #
 2438:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2439:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2440:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2441:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2442:                 if ($cdom ne '' && $cnum ne '') {
 2443:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2444:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2445:                         my $apath = $1.'_'.$id;
 2446:                         $apath=~s/\W/\_/gs;
 2447:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2448:                     }
 2449:                 }
 2450:             } else {
 2451: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2452: 	        $apath=&escape($apath);
 2453: 	        $apath=~s/\W/\_/gs;
 2454:                 &init_old_essays($symb,$apath,$adom,$aname);
 2455:             }
 2456:         }
 2457:     }
 2458: 
 2459: # This is where output for one specific student would start
 2460:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2461:     $request->print(
 2462:         "\n\n"
 2463:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2464:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2465:        ."\n"
 2466:     );
 2467: 
 2468:     # Show additional functions if allowed
 2469:     if ($perm{'vgr'}) {
 2470:         $request->print(
 2471:             &Apache::loncommon::track_student_link(
 2472:                 'View recent activity',
 2473:                 $uname,$udom,'check')
 2474:            .' '
 2475:         );
 2476:     }
 2477:     if ($perm{'opa'}) {
 2478:         $request->print(
 2479:             &Apache::loncommon::pprmlink(
 2480:                 &mt('Set/Change parameters'),
 2481:                 $uname,$udom,$symb,'check'));
 2482:     }
 2483: 
 2484:     # Show Problem
 2485:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2486: 	my $mode;
 2487: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2488: 	    $mode='both';
 2489: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2490: 	    $mode='text';
 2491: 	} elsif ($env{'form.vAns'} eq 'all') {
 2492: 	    $mode='answer';
 2493: 	}
 2494: 	&Apache::lonxml::clear_problem_counter();
 2495: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2496:     }
 2497: 
 2498:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2499: 
 2500:     # Display student info
 2501:     $request->print(($counter == 0 ? '' : '<br />'));
 2502: 
 2503:     my $boxtitle = &mt('Submissions');
 2504:     if ($is_tool) {
 2505:         $boxtitle = &mt('Transactions')
 2506:     }
 2507:     my $result='<div class="LC_Box">'
 2508:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2509:     $result.='<input type="hidden" name="name'.$counter.
 2510:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2511:     if (($numresp > $numessay) && !$is_tool) {
 2512:         $result.='<p class="LC_info">'
 2513:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2514:                 ."</p>\n";
 2515:     }
 2516: 
 2517:     # If any part of the problem is an essayresponse, then check for collaborators
 2518:     my $fullname;
 2519:     my $col_fullnames = [];
 2520:     if ($numessay) {
 2521: 	(my $sub_result,$fullname,$col_fullnames)=
 2522: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2523: 				 $counter);
 2524: 	$result.=$sub_result;
 2525:     }
 2526:     $request->print($result."\n");
 2527: 
 2528:     # print student answer/submission
 2529:     # Options are (1) Last submission only
 2530:     #             (2) Last submission (with detailed information for that submission)
 2531:     #             (3) All transactions (by date)
 2532:     #             (4) The whole record (with detailed information for all transactions)
 2533: 
 2534:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2535: 
 2536:     my $lastsubonly;
 2537: 
 2538:     if ($$timestamp eq '') {
 2539:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2540:     } elsif ($is_tool) {
 2541:         $lastsubonly =
 2542:             '<div class="LC_grade_submissions_body">'
 2543:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2544:     } else {
 2545:         $lastsubonly =
 2546:             '<div class="LC_grade_submissions_body">'
 2547:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2548: 
 2549: 	my %seenparts;
 2550: 	my @part_response_id = &flatten_responseType($responseType);
 2551: 	foreach my $part (@part_response_id) {
 2552: 	    my ($partid,$respid) = @{ $part };
 2553: 	    my $display_part=&get_display_part($partid,$symb);
 2554: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2555: 		if (exists($seenparts{$partid})) { next; }
 2556: 		$seenparts{$partid}=1;
 2557:                 $request->print(
 2558:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2559:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2560:                                '<a href="javascript:viewSubmitter(\''.
 2561:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2562:                                '\');" target="_self">'.
 2563:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2564:                     '<br />');
 2565: 		next;
 2566: 	    }
 2567: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2568: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2569:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2570:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2571:                     ' <span class="LC_internal_info">'.
 2572:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2573:                     '</span>&nbsp; &nbsp;'.
 2574: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2575: 		next;
 2576: 	    }
 2577: 	    foreach my $submission (@$string) {
 2578: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2579: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2580: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2581: 		# Similarity check
 2582:                 my $similar='';
 2583:                 my ($type,$trial,$rndseed);
 2584:                 if ($hide eq 'rand') {
 2585:                     $type = 'randomizetry';
 2586:                     $trial = $record{"resource.$partid.tries"};
 2587:                     $rndseed = $record{"resource.$partid.rndseed"};
 2588:                 }
 2589: 	        if ($env{'form.checkPlag'}) {
 2590: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2591: 		    &most_similar($uname,$udom,$symb,$subval);
 2592: 		    if ($osim) {
 2593: 			$osim=int($osim*100.0);
 2594:                         if ($hide eq 'anon') {
 2595:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2596:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2597:                         } else {
 2598: 			    $similar='<hr />';
 2599:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2600:                                 $similar .= '<h3><span class="LC_warning">'.
 2601:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2602:                                                 $osim,
 2603:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2604:                                             '</span></h3>';
 2605:                             } else {
 2606:                                 my %old_course_desc;
 2607:                                 if ($ocrsid ne '') {
 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:                             }
 2637:                             $similar .= '<blockquote><i>'.
 2638:                                         &keywords_highlight($oessay).
 2639:                                         '</i></blockquote><hr />';
 2640:                         }
 2641: 	            }
 2642: 		}
 2643: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2644:                                      undef,$type,$trial,$rndseed);
 2645:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2646:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2647:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2648: 		    my $display_part=&get_display_part($partid,$symb);
 2649:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2650:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2651:                         ' <span class="LC_internal_info">'.
 2652:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2653:                         '</span>&nbsp; &nbsp;';
 2654: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2655: 		    if (@$files) {
 2656:                         if ($hide eq 'anon') {
 2657:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2658:                         } else {
 2659:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2660:                                         .'<br /><span class="LC_warning">';
 2661:                             if(@$files == 1) {
 2662:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2663:                             } else {
 2664:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2665:                             }
 2666:                             $lastsubonly .= '</span>';
 2667:                             foreach my $file (@$files) {
 2668:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2669:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2670:                             }
 2671:                         }
 2672: 			$lastsubonly.='<br />';
 2673:                     }
 2674:                     if ($hide eq 'anon') {
 2675:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2676:                     } else {
 2677:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2678:                         if ($draft) {
 2679:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2680:                         }
 2681:                         $subval =
 2682: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2683: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2684:                         if ($responsetype eq 'essay') {
 2685:                             $subval =~ s{\n}{<br />}g;
 2686:                         }
 2687:                         $lastsubonly.=$subval."\n";
 2688:                     }
 2689:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2690: 		    $lastsubonly.='</div>';
 2691: 		}
 2692:             }
 2693: 	}
 2694: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2695:     }
 2696:     $request->print($lastsubonly);
 2697:     if ($env{'form.lastSub'} eq 'datesub') {
 2698:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2699: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2700:     }
 2701:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2702:         my $identifier = (&canmodify($usec)? $counter : '');
 2703:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2704: 								 $env{'request.course.id'},
 2705: 								 $last,'.submission',
 2706: 								 'Apache::grades::keywords_highlight',
 2707:                                                                  $usec,$identifier));
 2708:     }
 2709:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2710: 	.$udom.'" />'."\n");
 2711:     # return if view submission with no grading option
 2712:     if (!&canmodify($usec)) {
 2713: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2714: 	return;
 2715:     } else {
 2716: 	$request->print('</div>'."\n");
 2717:     }
 2718: 
 2719:     # grading message center
 2720: 
 2721:     if ($env{'form.compmsg'}) {
 2722:         my $result='<div class="LC_Box">'.
 2723:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2724:                    '<div class="LC_grade_message_center_body">';
 2725:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2726:         my $msgfor = $givenn.' '.$lastname;
 2727:         if (scalar(@$col_fullnames) > 0) {
 2728:             my $lastone = pop(@$col_fullnames);
 2729:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2730:         }
 2731:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2732:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2733:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2734:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2735:                  ',\''.$msgfor.'\');" target="_self">'.
 2736:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2737:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2738:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2739:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2740:                  '<br />&nbsp;('.
 2741:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2742:                  '</div></div>';
 2743:         $request->print($result);
 2744:     }
 2745: 
 2746:     my %seen = ();
 2747:     my @partlist;
 2748:     my @gradePartRespid;
 2749:     my @part_response_id;
 2750:     if ($is_tool) {
 2751:         @part_response_id = ([0,'']);
 2752:     } else {
 2753:         @part_response_id = &flatten_responseType($responseType);
 2754:     }
 2755:     $request->print(
 2756:         '<div class="LC_Box">'
 2757:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2758:     );
 2759:     $request->print(&gradeBox_start());
 2760:     foreach my $part_response_id (@part_response_id) {
 2761:     	my ($partid,$respid) = @{ $part_response_id };
 2762: 	my $part_resp = join('_',@{ $part_response_id });
 2763: 	next if ($seen{$partid} > 0);
 2764: 	$seen{$partid}++;
 2765: 	push(@partlist,$partid);
 2766: 	push(@gradePartRespid,$partid.'.'.$respid);
 2767: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2768:     }
 2769:     $request->print(&gradeBox_end()); # </div>
 2770:     $request->print('</div>');
 2771: 
 2772:     $request->print('<div class="LC_grade_info_links">');
 2773:     $request->print('</div>');
 2774: 
 2775:     $result='<input type="hidden" name="partlist'.$counter.
 2776: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2777:     $result.='<input type="hidden" name="gradePartRespid'.
 2778: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2779:     my $ctr = 0;
 2780:     while ($ctr < scalar(@partlist)) {
 2781: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2782: 	    $partlist[$ctr].'" />'."\n";
 2783: 	$ctr++;
 2784:     }
 2785:     $request->print($result.''."\n");
 2786: 
 2787: # Done with printing info for one student
 2788: 
 2789:     $request->print('</div>');#LC_grade_show_user
 2790: 
 2791: 
 2792:     # print end of form
 2793:     if ($counter == $total) {
 2794:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2795: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2796: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2797: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2798: 	my $ntstu ='<select name="NTSTU">'.
 2799: 	    '<option>1</option><option>2</option>'.
 2800: 	    '<option>3</option><option>5</option>'.
 2801: 	    '<option>7</option><option>10</option></select>'."\n";
 2802: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2803: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2804:         $endform.=&mt('[_1]student(s)',$ntstu);
 2805: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2806: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2807: 	    '<input type="button" value="'.&mt('Next').'" '.
 2808: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2809:         $endform.='<span class="LC_warning">'.
 2810:                   &mt('(Next and Previous (student) do not save the scores.)').
 2811:                   '</span>'."\n" ;
 2812:         $endform.="<input type='hidden' value='".&get_increment().
 2813:             "' name='increment' />";
 2814: 	$endform.='</td></tr></table></form>';
 2815: 	$request->print($endform);
 2816:     }
 2817:     return '';
 2818: }
 2819: 
 2820: sub check_collaborators {
 2821:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2822:     my ($result,@col_fullnames);
 2823:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2824:     foreach my $part (keys(%$handgrade)) {
 2825: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2826: 					'.maxcollaborators',
 2827: 					$symb,$udom,$uname);
 2828: 	next if ($ncol <= 0);
 2829: 	$part =~ s/\_/\./g;
 2830: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2831: 	my (@good_collaborators, @bad_collaborators);
 2832: 	foreach my $possible_collaborator
 2833: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2834: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2835: 	    next if ($possible_collaborator eq '');
 2836: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2837: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2838: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2839: 	    # Doing this grep allows 'fuzzy' specification
 2840: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2841: 			       keys(%$classlist));
 2842: 	    if (! scalar(@matches)) {
 2843: 		push(@bad_collaborators, $possible_collaborator);
 2844: 	    } else {
 2845: 		push(@good_collaborators, @matches);
 2846: 	    }
 2847: 	}
 2848: 	if (scalar(@good_collaborators) != 0) {
 2849: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2850: 	    foreach my $name (@good_collaborators) {
 2851: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2852: 		push(@col_fullnames, $givenn.' '.$lastname);
 2853: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2854: 	    }
 2855: 	    $result.='</ol><br />'."\n";
 2856: 	    my ($part)=split(/\./,$part);
 2857: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2858: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2859: 		"\n";
 2860: 	}
 2861: 	if (scalar(@bad_collaborators) > 0) {
 2862: 	    $result.='<div class="LC_warning">';
 2863: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2864: 	    $result .= '</div>';
 2865: 	}         
 2866: 	if (scalar(@bad_collaborators > $ncol)) {
 2867: 	    $result .= '<div class="LC_warning">';
 2868: 	    $result .= &mt('This student has submitted too many '.
 2869: 		'collaborators.  Maximum is [_1].',$ncol);
 2870: 	    $result .= '</div>';
 2871: 	}
 2872:     }
 2873:     return ($result,$fullname,\@col_fullnames);
 2874: }
 2875: 
 2876: #--- Retrieve the last submission for all the parts
 2877: sub get_last_submission {
 2878:     my ($returnhash,$is_tool)=@_;
 2879:     my (@string,$timestamp,%lasthidden);
 2880:     if ($$returnhash{'version'}) {
 2881: 	my %lasthash=();
 2882: 	my ($version);
 2883: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2884: 	    foreach my $key (sort(split(/\:/,
 2885: 					$$returnhash{$version.':keys'}))) {
 2886: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2887: 		$timestamp = 
 2888: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2889: 	    }
 2890: 	}
 2891:         my (%typeparts,%randombytry);
 2892:         my $showsurv = 
 2893:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2894:         foreach my $key (sort(keys(%lasthash))) {
 2895:             if ($key =~ /\.type$/) {
 2896:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2897:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2898:                     ($lasthash{$key} eq 'randomizetry')) {
 2899:                     my ($ign,@parts) = split(/\./,$key);
 2900:                     pop(@parts);
 2901:                     my $id = join('.',@parts);
 2902:                     if ($lasthash{$key} eq 'randomizetry') {
 2903:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2904:                     } else {
 2905:                         unless ($showsurv) {
 2906:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2907:                         }
 2908:                     }
 2909:                     delete($lasthash{$key});
 2910:                 }
 2911:             }
 2912:         }
 2913:         my @hidden = keys(%typeparts);
 2914:         my @randomize = keys(%randombytry);
 2915: 	foreach my $key (keys(%lasthash)) {
 2916: 	    next if ($key !~ /\.submission$/);
 2917:             my $hide;
 2918:             if (@hidden) {
 2919:                 foreach my $id (@hidden) {
 2920:                     if ($key =~ /^\Q$id\E/) {
 2921:                         $hide = 'anon';
 2922:                         last;
 2923:                     }
 2924:                 }
 2925:             }
 2926:             unless ($hide) {
 2927:                 if (@randomize) {
 2928:                     foreach my $id (@randomize) {
 2929:                         if ($key =~ /^\Q$id\E/) {
 2930:                             $hide = 'rand';
 2931:                             last;
 2932:                         }
 2933:                     }
 2934:                 }
 2935:             }
 2936: 	    my ($partid,$foo) = split(/submission$/,$key);
 2937: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2938:             push(@string, join(':', $key, $hide, $draft, (
 2939:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2940:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2941: 	}
 2942:     }
 2943:     if (!@string) {
 2944:         my $msg;
 2945:         if ($is_tool) {
 2946:             $msg = &mt('No grade passed back.');
 2947:         } else {
 2948:             $msg = &mt('Nothing submitted - no attempts.');
 2949:         }
 2950: 	$string[0] =
 2951: 	    '<span class="LC_warning">'.$msg.'</span>';
 2952:     }
 2953:     return (\@string,\$timestamp);
 2954: }
 2955: 
 2956: #--- High light keywords, with style choosen by user.
 2957: sub keywords_highlight {
 2958:     my $string    = shift;
 2959:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2960:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2961:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2962:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2963:     foreach my $keyword (@keylist) {
 2964: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2965:     }
 2966:     return $string;
 2967: }
 2968: 
 2969: # For Tasks provide a mechanism to display previous version for one specific student
 2970: 
 2971: sub show_previous_task_version {
 2972:     my ($request,$symb) = @_;
 2973:     if ($symb eq '') {
 2974:         $request->print(
 2975:             '<span class="LC_error">'.
 2976:             &mt('Unable to handle ambiguous references.').
 2977:             '</span>');
 2978:         return '';
 2979:     }
 2980:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2981:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2982:     if (!&canview($usec)) {
 2983:         $request->print(
 2984:             '<span class="LC_warning">'.
 2985:             &mt('Unable to view previous version for requested student.').
 2986:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2987:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2988:             '</span>');
 2989:         return;
 2990:     }
 2991:     my $mode = 'both';
 2992:     my $isTask = ($symb =~/\.task$/);
 2993:     if ($isTask) {
 2994:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2995:             if ($env{'form.fullname'} eq '') {
 2996:                 $env{'form.fullname'} =
 2997:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2998:             }
 2999:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3000:             $request->print("\n\n".
 3001:                             '<div class="LC_grade_show_user">'.
 3002:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3003:                             '</h2>'."\n");
 3004:             &Apache::lonxml::clear_problem_counter();
 3005:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3006:                             {'previousversion' => $env{'form.previousversion'} }));
 3007:             $request->print("\n</div>");
 3008:         }
 3009:     }
 3010:     return;
 3011: }
 3012: 
 3013: sub choose_task_version_form {
 3014:     my ($symb,$uname,$udom,$nomenu) = @_;
 3015:     my $isTask = ($symb =~/\.task$/);
 3016:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3017:     if ($isTask) {
 3018:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3019:                                               $udom,$uname);
 3020:         if (($record{'resource.0.version'} eq '') ||
 3021:             ($record{'resource.0.version'} < 2)) {
 3022:             return ($record{'resource.0.version'},
 3023:                     $record{'resource.0.version'},$result,$js);
 3024:         } else {
 3025:             $current = $record{'resource.0.version'};
 3026:         }
 3027:         if ($env{'form.previousversion'}) {
 3028:             $displayed = $env{'form.previousversion'};
 3029:             $rowtitle = &mt('Choose another version:')
 3030:         } else {
 3031:             $displayed = $current;
 3032:             $rowtitle = &mt('Show earlier version:');
 3033:         }
 3034:         $result = '<div class="LC_left_float">';
 3035:         my $list;
 3036:         my $numversions = 0;
 3037:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3038:             if ($i == $current) {
 3039:                 if (!$env{'form.previousversion'} || $nomenu) {
 3040:                     next;
 3041:                 } else {
 3042:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3043:                     $numversions ++;
 3044:                 }
 3045:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3046:                 unless ($i == $env{'form.previousversion'}) {
 3047:                     $numversions ++;
 3048:                 }
 3049:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3050:             }
 3051:         }
 3052:         if ($numversions) {
 3053:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3054:             $result .=
 3055:                 '<form name="getprev" method="post" action=""'.
 3056:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3057:                 &Apache::loncommon::start_data_table().
 3058:                 &Apache::loncommon::start_data_table_row().
 3059:                 '<th align="left">'.$rowtitle.'</th>'.
 3060:                 '<td><select name="version">'.
 3061:                 '<option>'.&mt('Select').'</option>'.
 3062:                 $list.
 3063:                 '</select></td>'.
 3064:                 &Apache::loncommon::end_data_table_row();
 3065:             unless ($nomenu) {
 3066:                 $result .= &Apache::loncommon::start_data_table_row().
 3067:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3068:                 '<td><span class="LC_nobreak">'.
 3069:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3070:                 &mt('Yes').'</label>'.
 3071:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3072:                 '</span></td>'.
 3073:                 &Apache::loncommon::end_data_table_row();
 3074:             }
 3075:             $result .=
 3076:                 &Apache::loncommon::start_data_table_row().
 3077:                 '<th align="left">&nbsp;</th>'.
 3078:                 '<td>'.
 3079:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3080:                 '</td>'.
 3081:                 &Apache::loncommon::end_data_table_row().
 3082:                 &Apache::loncommon::end_data_table().
 3083:                 '</form>';
 3084:             $js = &previous_display_javascript($nomenu,$current);
 3085:         } elsif ($displayed && $nomenu) {
 3086:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3087:         } else {
 3088:             $result .= &mt('No previous versions to show for this student');
 3089:         }
 3090:         $result .= '</div>';
 3091:     }
 3092:     return ($current,$displayed,$result,$js);
 3093: }
 3094: 
 3095: sub previous_display_javascript {
 3096:     my ($nomenu,$current) = @_;
 3097:     my $js = <<"JSONE";
 3098: <script type="text/javascript">
 3099: // <![CDATA[
 3100: function previousVersion(uname,udom,symb) {
 3101:     var current = '$current';
 3102:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3103:     var prevstr = new RegExp("^\\\\d+\$");
 3104:     if (!prevstr.test(version)) {
 3105:         return false;
 3106:     }
 3107:     var url = '';
 3108:     if (version == current) {
 3109:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3110:     } else {
 3111:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3112:     }
 3113: JSONE
 3114:     if ($nomenu) {
 3115:         $js .= <<"JSTWO";
 3116:     document.location.href = url;
 3117: JSTWO
 3118:     } else {
 3119:         $js .= <<"JSTHREE";
 3120:     var newwin = 0;
 3121:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3122:         if (document.getprev.prevwin[i].checked == true) {
 3123:             newwin = document.getprev.prevwin[i].value;
 3124:         }
 3125:     }
 3126:     if (newwin == 1) {
 3127:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3128:         url = url+'&inhibitmenu=yes';
 3129:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3130:             previousWin = window.open(url,'',options,1);
 3131:         } else {
 3132:             previousWin.location.href = url;
 3133:         }
 3134:         previousWin.focus();
 3135:         return false;
 3136:     } else {
 3137:         document.location.href = url;
 3138:         return false;
 3139:     }
 3140: JSTHREE
 3141:     }
 3142:     $js .= <<"ENDJS";
 3143:     return false;
 3144: }
 3145: // ]]>
 3146: </script>
 3147: ENDJS
 3148: 
 3149: }
 3150: 
 3151: #--- Called from submission routine
 3152: sub processHandGrade {
 3153:     my ($request,$symb) = @_;
 3154:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3155:     my $button = $env{'form.gradeOpt'};
 3156:     my $ngrade = $env{'form.NCT'};
 3157:     my $ntstu  = $env{'form.NTSTU'};
 3158:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3159:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3160: 
 3161:     if ($button eq 'Save & Next') {
 3162: 	my $ctr = 0;
 3163: 	while ($ctr < $ngrade) {
 3164: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3165: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3166:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3167: 	    if ($errorflag eq 'no_score') {
 3168: 		$ctr++;
 3169: 		next;
 3170: 	    }
 3171: 	    if ($errorflag eq 'not_allowed') {
 3172: 		$request->print(
 3173:                     '<span class="LC_error">'
 3174:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3175:                    .'</span>');
 3176: 		$ctr++;
 3177: 		next;
 3178: 	    }
 3179:             if ($numhidden) {
 3180:                 $request->print(
 3181:                     '<span class="LC_info">'
 3182:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3183:                    .'</span><br />');
 3184:             }
 3185: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3186: 	    my ($subject,$message,$msgstatus) = ('','','');
 3187: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3188:             my ($feedurl,$showsymb) =
 3189: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3190: 	    my $messagetail;
 3191: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3192: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3193: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3194: 		$subject.=' ['.$restitle.']';
 3195: 		my (@msgnum) = split(/,/,$includemsg);
 3196: 		foreach (@msgnum) {
 3197: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3198: 		}
 3199: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3200: 		if ($env{'form.withgrades'.$ctr}) {
 3201: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3202: 		    $messagetail = " for <a href=\"".
 3203: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3204: 		}
 3205: 		$msgstatus = 
 3206:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3207: 						     $message.$messagetail,
 3208:                                                      undef,$feedurl,undef,
 3209:                                                      undef,undef,$showsymb,
 3210:                                                      $restitle);
 3211: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3212: 				$msgstatus.'<br />');
 3213: 	    }
 3214: 	    if ($env{'form.collaborator'.$ctr}) {
 3215: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3216: 		foreach my $collabstr (@collabstrs) {
 3217: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3218: 		    foreach my $collaborator (@collaborators) {
 3219: 			my ($errorflag,$pts,$wgt) = 
 3220: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3221: 					   $env{'form.unamedom'.$ctr},$part);
 3222: 			if ($errorflag eq 'not_allowed') {
 3223: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3224: 			    next;
 3225: 			} elsif ($message ne '') {
 3226: 			    my ($baseurl,$showsymb) = 
 3227: 				&get_feedurl_and_symb($symb,$collaborator,
 3228: 						      $udom);
 3229: 			    if ($env{'form.withgrades'.$ctr}) {
 3230: 				$messagetail = " for <a href=\"".
 3231:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3232: 			    }
 3233: 			    $msgstatus = 
 3234: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3235: 			}
 3236: 		    }
 3237: 		}
 3238: 	    }
 3239: 	    $ctr++;
 3240: 	}
 3241:     }
 3242: 
 3243:     my $res_error;
 3244:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3245:     if ($res_error) {
 3246:         $request->print(&navmap_errormsg());
 3247:         return;
 3248:     }
 3249: 
 3250:     my %keyhash = ();
 3251:     if ($numessay) {
 3252: 	# Keywords sorted in alphabatical order
 3253: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3254: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3255: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3256: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3257: 	$env{'form.keywords'} = join(' ',@keywords);
 3258: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3259: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3260: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3261: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3262: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3263:     }
 3264: 
 3265:     if ($env{'form.compmsg'}) {
 3266: 	# message center - Order of message gets changed. Blank line is eliminated.
 3267: 	# New messages are saved in env for the next student.
 3268: 	# All messages are saved in nohist_handgrade.db
 3269: 	my ($ctr,$idx) = (1,1);
 3270: 	while ($ctr <= $env{'form.savemsgN'}) {
 3271: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3272: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3273: 		$idx++;
 3274: 	    }
 3275: 	    $ctr++;
 3276: 	}
 3277: 	$ctr = 0;
 3278: 	while ($ctr < $ngrade) {
 3279: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3280: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3281: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3282: 	        $idx++;
 3283: 	    }
 3284: 	    $ctr++;
 3285: 	}
 3286: 	$env{'form.savemsgN'} = --$idx;
 3287: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3288:     }
 3289:     if (($numessay) || ($env{'form.compmsg'})) {
 3290:         my $putresult = &Apache::lonnet::put
 3291:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3292:     }
 3293: 
 3294:     # Called by Save & Refresh from Highlight Attribute Window
 3295:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3296:     if ($env{'form.refresh'} eq 'on') {
 3297: 	my ($ctr,$total) = (0,0);
 3298: 	while ($ctr < $ngrade) {
 3299: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3300: 	    $ctr++;
 3301: 	}
 3302: 	$env{'form.NTSTU'}=$ngrade;
 3303: 	$ctr = 0;
 3304: 	while ($ctr < $total) {
 3305: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3306: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3307: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3308: 	    &submission($request,$ctr,$total-1,$symb);
 3309: 	    $ctr++;
 3310: 	}
 3311: 	return '';
 3312:     }
 3313: 
 3314:     # Get the next/previous one or group of students
 3315:     my $firststu = $env{'form.unamedom0'};
 3316:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3317:     my $ctr = 2;
 3318:     while ($laststu eq '') {
 3319: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3320: 	$ctr++;
 3321: 	$laststu = $firststu if ($ctr > $ngrade);
 3322:     }
 3323: 
 3324:     my (@parsedlist,@nextlist);
 3325:     my ($nextflg) = 0;
 3326:     foreach my $item (sort 
 3327: 	     {
 3328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3330: 		 }
 3331: 		 return $a cmp $b;
 3332: 	     } (keys(%$fullname))) {
 3333: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3334: 	    push(@parsedlist,$item);
 3335: 	}
 3336: 	$nextflg = 1 if ($item eq $laststu);
 3337: 	if ($button eq 'Previous') {
 3338: 	    last if ($item eq $firststu);
 3339: 	    push(@parsedlist,$item);
 3340: 	}
 3341:     }
 3342:     $ctr = 0;
 3343:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3344:     foreach my $student (@parsedlist) {
 3345: 	my $submitonly=$env{'form.submitonly'};
 3346: 	my ($uname,$udom) = split(/:/,$student);
 3347: 	
 3348: 	if ($submitonly eq 'queued') {
 3349: 	    my %queue_status = 
 3350: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3351: 							$udom,$uname);
 3352: 	    next if (!defined($queue_status{'gradingqueue'}));
 3353: 	}
 3354: 
 3355: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3356: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3357: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3358: 	    my $submitted = 0;
 3359: 	    my $ungraded = 0;
 3360: 	    my $incorrect = 0;
 3361: 	    foreach my $item (keys(%status)) {
 3362: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3363: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3364: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3365: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3366: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3367: 		    $submitted = 0;
 3368: 		}
 3369: 	    }
 3370: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3371: 				     $submitonly eq 'incorrect' ||
 3372: 				     $submitonly eq 'graded'));
 3373: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3374: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3375: 	}
 3376: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3377: 	last if ($ctr == $ntstu);
 3378: 	$ctr++;
 3379:     }
 3380: 
 3381:     $ctr = 0;
 3382:     my $total = scalar(@nextlist)-1;
 3383: 
 3384:     foreach (sort(@nextlist)) {
 3385: 	my ($uname,$udom,$submitter) = split(/:/);
 3386: 	$env{'form.student'}  = $uname;
 3387: 	$env{'form.userdom'}  = $udom;
 3388: 	$env{'form.fullname'} = $$fullname{$_};
 3389: 	&submission($request,$ctr,$total,$symb);
 3390: 	$ctr++;
 3391:     }
 3392:     if ($total < 0) {
 3393: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3394: 	$request->print($the_end);
 3395:     }
 3396:     return '';
 3397: }
 3398: 
 3399: #---- Save the score and award for each student, if changed
 3400: sub saveHandGrade {
 3401:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3402:     my @version_parts;
 3403:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3404: 					   $env{'request.course.id'});
 3405:     if (!&canmodify($usec)) { return('not_allowed'); }
 3406:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3407:     my @parts_graded;
 3408:     my %newrecord  = ();
 3409:     my ($pts,$wgt,$totchg) = ('','',0);
 3410:     my %aggregate = ();
 3411:     my $aggregateflag = 0;
 3412:     if ($env{'form.HIDE'.$newflg}) {
 3413:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3414:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3415:         $totchg += $numchgs;
 3416:     }
 3417:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3418:     foreach my $new_part (@parts) {
 3419: 	#collaborator ($submi may vary for different parts
 3420: 	if ($submitter && $new_part ne $part) { next; }
 3421: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3422: 	if ($dropMenu eq 'excused') {
 3423: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3424: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3425: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3426: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3427: 		}
 3428: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3429: 	    }
 3430: 	} elsif ($dropMenu eq 'reset status'
 3431: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3432: 	    foreach my $key (keys(%record)) {
 3433: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3434: 	    }
 3435: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3436: 		"$env{'user.name'}:$env{'user.domain'}";
 3437:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3438: 
 3439:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3440: 					       [$new_part]);
 3441:             my $aggtries =$totaltries;
 3442:             if ($last_resets{$new_part}) {
 3443:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3444: 					   $new_part);
 3445:             }
 3446: 
 3447:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3448:             if ($aggtries > 0) {
 3449:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3450:                 $aggregateflag = 1;
 3451:             }
 3452: 	} elsif ($dropMenu eq '') {
 3453: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3454: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3455: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3456: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3457: 		next;
 3458: 	    }
 3459: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3460: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3461: 	    my $partial= $pts/$wgt;
 3462: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3463: 		#do not update score for part if not changed.
 3464:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3465: 		next;
 3466: 	    } else {
 3467: 	        push(@parts_graded,$new_part);
 3468: 	    }
 3469: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3470: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3471: 	    }
 3472: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3473: 	    if ($partial == 0) {
 3474: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3475: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3476: 		}
 3477: 	    } else {
 3478: 		if ($record{$reckey} ne 'correct_by_override') {
 3479: 		    $newrecord{$reckey} = 'correct_by_override';
 3480: 		}
 3481: 	    }	    
 3482: 	    if ($submitter && 
 3483: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3484: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3485: 	    }
 3486: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3487: 		"$env{'user.name'}:$env{'user.domain'}";
 3488: 	}
 3489: 	# unless problem has been graded, set flag to version the submitted files
 3490: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3491: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3492: 	        $dropMenu eq 'reset status')
 3493: 	   {
 3494: 	    push(@version_parts,$new_part);
 3495: 	}
 3496:     }
 3497:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3498:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3499: 
 3500:     if (%newrecord) {
 3501:         if (@version_parts) {
 3502:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3503:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3504: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3505: 	    foreach my $new_part (@version_parts) {
 3506: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3507: 				$new_part,\%newrecord);
 3508: 	    }
 3509:         }
 3510: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3511: 				$env{'request.course.id'},$domain,$stuname);
 3512: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3513: 				     $cdom,$cnum,$domain,$stuname);
 3514:     }
 3515:     if ($aggregateflag) {
 3516:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3517: 			      $cdom,$cnum);
 3518:     }
 3519:     return ('',$pts,$wgt,$totchg);
 3520: }
 3521: 
 3522: sub makehidden {
 3523:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3524:     return unless (ref($record) eq 'HASH');
 3525:     my %modified;
 3526:     my $numchanged = 0;
 3527:     if (exists($record->{$version.':keys'})) {
 3528:         my $partsregexp = $parts;
 3529:         $partsregexp =~ s/,/|/g;
 3530:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3531:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3532:                  my $item = $1;
 3533:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3534:                      $modified{$key} = $record->{$version.':'.$key};
 3535:                  }
 3536:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3537:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3538:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3539:                 $modified{$key} = $record->{$version.':'.$key};
 3540:             }
 3541:         }
 3542:         if (keys(%modified)) {
 3543:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3544:                                           $domain,$stuname,$tolog) eq 'ok') {
 3545:                 $numchanged ++;
 3546:             }
 3547:         }
 3548:     }
 3549:     return $numchanged;
 3550: }
 3551: 
 3552: sub check_and_remove_from_queue {
 3553:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3554:     my @ungraded_parts;
 3555:     foreach my $part (@{$parts}) {
 3556: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3557: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3558: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3559: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3560: 		) {
 3561: 	    push(@ungraded_parts, $part);
 3562: 	}
 3563:     }
 3564:     if ( !@ungraded_parts ) {
 3565: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3566: 					       $cnum,$domain,$stuname);
 3567:     }
 3568: }
 3569: 
 3570: sub handback_files {
 3571:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3572:     my $portfolio_root = '/userfiles/portfolio';
 3573:     my $res_error;
 3574:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3575:     if ($res_error) {
 3576:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3577:         return;
 3578:     }
 3579:     my @handedback;
 3580:     my $file_msg;
 3581:     my @part_response_id = &flatten_responseType($responseType);
 3582:     foreach my $part_response_id (@part_response_id) {
 3583:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3584: 	my $part_resp = join('_',@{ $part_response_id });
 3585:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3586:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3587:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3588:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3589:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3590:                     my ($directory,$answer_file) = 
 3591:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3592:                     my ($answer_name,$answer_ver,$answer_ext) =
 3593: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3594: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3595:                     my $getpropath = 1;
 3596:                     my ($dir_list,$listerror) =
 3597:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3598:                                                  $domain,$stuname,$getpropath);
 3599: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3600:                     # fix filename
 3601:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3602:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3603:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3604:             	                                $save_file_name);
 3605:                     if ($result !~ m|^/uploaded/|) {
 3606:                         $request->print('<br /><span class="LC_error">'.
 3607:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3608:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3609:                                         '</span>');
 3610:                     } else {
 3611:                         # mark the file as read only
 3612:                         push(@handedback,$save_file_name);
 3613: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3614: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3615: 			}
 3616:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3617: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3618:                     }
 3619:                     $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>'));
 3620:                 }
 3621:             }
 3622:         }
 3623:     }
 3624:     if (@handedback > 0) {
 3625:         $request->print('<br />');
 3626:         my @what = ($symb,$env{'request.course.id'},'handback');
 3627:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3628:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3629:         my ($subject,$message);
 3630:         if (scalar(@handedback) == 1) {
 3631:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3632:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3633:         } else {
 3634:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3635:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3636:         }
 3637:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3638:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3639:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3640:         my ($feedurl,$showsymb) =
 3641:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3642:         my $restitle = &Apache::lonnet::gettitle($symb);
 3643:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3644:         my $msgstatus =
 3645:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3646:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3647:                  $restitle);
 3648:         if ($msgstatus) {
 3649:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3650:         }
 3651:     }
 3652:     return;
 3653: }
 3654: 
 3655: sub get_feedurl_and_symb {
 3656:     my ($symb,$uname,$udom) = @_;
 3657:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3658:     $url = &Apache::lonnet::clutter($url);
 3659:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3660: 					$symb,$udom,$uname);
 3661:     if ($encrypturl =~ /^yes$/i) {
 3662: 	&Apache::lonenc::encrypted(\$url,1);
 3663: 	&Apache::lonenc::encrypted(\$symb,1);
 3664:     }
 3665:     return ($url,$symb);
 3666: }
 3667: 
 3668: sub get_submitted_files {
 3669:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3670:     my @files;
 3671:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3672:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3673:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3674:     	    push(@files,$file_url.$file);
 3675:         }
 3676:     }
 3677:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3678:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3679:     }
 3680:     return (\@files);
 3681: }
 3682: 
 3683: # ----------- Provides number of tries since last reset.
 3684: sub get_num_tries {
 3685:     my ($record,$last_reset,$part) = @_;
 3686:     my $timestamp = '';
 3687:     my $num_tries = 0;
 3688:     if ($$record{'version'}) {
 3689:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3690:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3691:                 $timestamp = $$record{$version.':timestamp'};
 3692:                 if ($timestamp > $last_reset) {
 3693:                     $num_tries ++;
 3694:                 } else {
 3695:                     last;
 3696:                 }
 3697:             }
 3698:         }
 3699:     }
 3700:     return $num_tries;
 3701: }
 3702: 
 3703: # ----------- Determine decrements required in aggregate totals 
 3704: sub decrement_aggs {
 3705:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3706:     my %decrement = (
 3707:                         attempts => 0,
 3708:                         users => 0,
 3709:                         correct => 0
 3710:                     );
 3711:     $decrement{'attempts'} = $aggtries;
 3712:     if ($solvedstatus =~ /^correct/) {
 3713:         $decrement{'correct'} = 1;
 3714:     }
 3715:     if ($aggtries == $totaltries) {
 3716:         $decrement{'users'} = 1;
 3717:     }
 3718:     foreach my $type (keys(%decrement)) {
 3719:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3720:     }
 3721:     return;
 3722: }
 3723: 
 3724: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3725: sub get_last_resets {
 3726:     my ($symb,$courseid,$partids) =@_;
 3727:     my %last_resets;
 3728:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3729:     my $cname = $env{'course.'.$courseid.'.num'};
 3730:     my @keys;
 3731:     foreach my $part (@{$partids}) {
 3732: 	push(@keys,"$symb\0$part\0resettime");
 3733:     }
 3734:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3735: 				     $cdom,$cname);
 3736:     foreach my $part (@{$partids}) {
 3737: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3738:     }
 3739:     return %last_resets;
 3740: }
 3741: 
 3742: # ----------- Handles creating versions for portfolio files as answers
 3743: sub version_portfiles {
 3744:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3745:     my $version_parts = join('|',@$v_flag);
 3746:     my @returned_keys;
 3747:     my $parts = join('|', @$parts_graded);
 3748:     foreach my $key (keys(%$record)) {
 3749:         my $new_portfiles;
 3750:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3751:             my @versioned_portfiles;
 3752:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3753:             if (@portfiles) {
 3754:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3755:                                                       \@versioned_portfiles);
 3756:             }
 3757:             $$record{$key} = join(',',@versioned_portfiles);
 3758:             push(@returned_keys,$key);
 3759:         }
 3760:     } 
 3761:     return (@returned_keys);   
 3762: }
 3763: 
 3764: #--------------------------------------------------------------------------------------
 3765: #
 3766: #-------------------------- Next few routines handles grading by section or whole class
 3767: #
 3768: #--- Javascript to handle grading by section or whole class
 3769: sub viewgrades_js {
 3770:     my ($request) = shift;
 3771: 
 3772:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3773:     &js_escape(\$alertmsg);
 3774:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3775:    function writePoint(partid,weight,point) {
 3776: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3777: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3778: 	if (point == "textval") {
 3779: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3780: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3781: 		alert("$alertmsg"+parseFloat(point));
 3782: 		var resetbox = false;
 3783: 		for (var i=0; i<radioButton.length; i++) {
 3784: 		    if (radioButton[i].checked) {
 3785: 			textbox.value = i;
 3786: 			resetbox = true;
 3787: 		    }
 3788: 		}
 3789: 		if (!resetbox) {
 3790: 		    textbox.value = "";
 3791: 		}
 3792: 		return;
 3793: 	    }
 3794: 	    if (parseFloat(point) > parseFloat(weight)) {
 3795: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3796: 				   ") greater than the weight for the part. Accept?");
 3797: 		if (resp == false) {
 3798: 		    textbox.value = "";
 3799: 		    return;
 3800: 		}
 3801: 	    }
 3802: 	    for (var i=0; i<radioButton.length; i++) {
 3803: 		radioButton[i].checked=false;
 3804: 		if (parseFloat(point) == i) {
 3805: 		    radioButton[i].checked=true;
 3806: 		}
 3807: 	    }
 3808: 
 3809: 	} else {
 3810: 	    textbox.value = parseFloat(point);
 3811: 	}
 3812: 	for (i=0;i<document.classgrade.total.value;i++) {
 3813: 	    var user = document.classgrade["ctr"+i].value;
 3814: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3815: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3816: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3817: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3818: 	    if (saveval != "correct") {
 3819: 		scorename.value = point;
 3820: 		if (selname[0].selected != true) {
 3821: 		    selname[0].selected = true;
 3822: 		}
 3823: 	    }
 3824: 	}
 3825: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3826:     }
 3827: 
 3828:     function writeRadText(partid,weight) {
 3829: 	var selval   = document.classgrade["SELVAL_"+partid];
 3830: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3831:         var override = document.classgrade["FORCE_"+partid].checked;
 3832: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3833: 	if (selval[1].selected || selval[2].selected) {
 3834: 	    for (var i=0; i<radioButton.length; i++) {
 3835: 		radioButton[i].checked=false;
 3836: 
 3837: 	    }
 3838: 	    textbox.value = "";
 3839: 
 3840: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3841: 		var user = document.classgrade["ctr"+i].value;
 3842: 		user = user.replace(new RegExp(':', 'g'),"_");
 3843: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3844: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3845: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3846: 		if ((saveval != "correct") || override) {
 3847: 		    scorename.value = "";
 3848: 		    if (selval[1].selected) {
 3849: 			selname[1].selected = true;
 3850: 		    } else {
 3851: 			selname[2].selected = true;
 3852: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3853: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3854: 		    }
 3855: 		}
 3856: 	    }
 3857: 	} else {
 3858: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3859: 		var user = document.classgrade["ctr"+i].value;
 3860: 		user = user.replace(new RegExp(':', 'g'),"_");
 3861: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3862: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3863: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3864: 		if ((saveval != "correct") || override) {
 3865: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3866: 		    selname[0].selected = true;
 3867: 		}
 3868: 	    }
 3869: 	}	    
 3870:     }
 3871: 
 3872:     function changeSelect(partid,user) {
 3873: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3874: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3875: 	var point  = textbox.value;
 3876: 	var weight = document.classgrade["weight_"+partid].value;
 3877: 
 3878: 	if (isNaN(point) || parseFloat(point) < 0) {
 3879: 	    alert("$alertmsg"+parseFloat(point));
 3880: 	    textbox.value = "";
 3881: 	    return;
 3882: 	}
 3883: 	if (parseFloat(point) > parseFloat(weight)) {
 3884: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3885: 			       ") greater than the weight of the part. Accept?");
 3886: 	    if (resp == false) {
 3887: 		textbox.value = "";
 3888: 		return;
 3889: 	    }
 3890: 	}
 3891: 	selval[0].selected = true;
 3892:     }
 3893: 
 3894:     function changeOneScore(partid,user) {
 3895: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3896: 	if (selval[1].selected || selval[2].selected) {
 3897: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3898: 	    if (selval[2].selected) {
 3899: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3900: 	    }
 3901:         }
 3902:     }
 3903: 
 3904:     function resetEntry(numpart) {
 3905: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3906: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3907: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3908: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3909: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3910: 	    for (var i=0; i<radioButton.length; i++) {
 3911: 		radioButton[i].checked=false;
 3912: 
 3913: 	    }
 3914: 	    textbox.value = "";
 3915: 	    selval[0].selected = true;
 3916: 
 3917: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3918: 		var user = document.classgrade["ctr"+i].value;
 3919: 		user = user.replace(new RegExp(':', 'g'),"_");
 3920: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3921: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3922: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3923: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3924: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3925: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3926: 		if (saveselval == "excused") {
 3927: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3928: 		} else {
 3929: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3930: 		}
 3931: 	    }
 3932: 	}
 3933:     }
 3934: 
 3935: VIEWJAVASCRIPT
 3936: }
 3937: 
 3938: #--- show scores for a section or whole class w/ option to change/update a score
 3939: sub viewgrades {
 3940:     my ($request,$symb) = @_;
 3941:     my ($is_tool,$toolsymb);
 3942:     if ($symb =~ /ext\.tool$/) {
 3943:         $is_tool = 1;
 3944:         $toolsymb = $symb;
 3945:     }
 3946:     &viewgrades_js($request);
 3947: 
 3948:     #need to make sure we have the correct data for later EXT calls, 
 3949:     #thus invalidate the cache
 3950:     &Apache::lonnet::devalidatecourseresdata(
 3951:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3952:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3953:     &Apache::lonnet::clear_EXT_cache_status();
 3954: 
 3955:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3956: 
 3957:     #view individual student submission form - called using Javascript viewOneStudent
 3958:     $result.=&jscriptNform($symb);
 3959: 
 3960:     #beginning of class grading form
 3961:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3962:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3963: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3964: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3965: 	&build_section_inputs().
 3966: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3967: 
 3968:     #retrieve selected groups
 3969:     my (@groups,$group_display);
 3970:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3971:     if (grep(/^all$/,@groups)) {
 3972:         @groups = ('all');
 3973:     } elsif (grep(/^none$/,@groups)) {
 3974:         @groups = ('none');
 3975:     } elsif (@groups > 0) {
 3976:         $group_display = join(', ',@groups);
 3977:     }
 3978: 
 3979:     my ($common_header,$specific_header,@sections,$section_display);
 3980:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3981:     if (grep(/^all$/,@sections)) {
 3982:         @sections = ('all');
 3983:         if ($group_display) {
 3984:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3985:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3986:         } elsif (grep(/^none$/,@groups)) {
 3987:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3988:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3989:         } else {
 3990: 	    $common_header = &mt('Assign Common Grade to Class');
 3991:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3992:         }
 3993:     } elsif (grep(/^none$/,@sections)) {
 3994:         @sections = ('none');
 3995:         if ($group_display) {
 3996:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3997:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3998:         } elsif (grep(/^none$/,@groups)) {
 3999:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4000:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4001:         } else {
 4002:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4003: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4004:         }
 4005:     } else {
 4006:         $section_display = join (", ",@sections);
 4007:         if ($group_display) {
 4008:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4009:                                  $section_display,$group_display);
 4010:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4011:                                    $section_display,$group_display);
 4012:         } elsif (grep(/^none$/,@groups)) {
 4013:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4014:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4015:         } else {
 4016:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4017: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4018:         }
 4019:     }
 4020:     my %submit_types = &substatus_options();
 4021:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4022: 
 4023:     if ($env{'form.submitonly'} eq 'all') {
 4024:         $result.= '<h3>'.$common_header.'</h3>';
 4025:     } else {
 4026:         my $text;
 4027:         if ($is_tool) {
 4028:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4029:         } else {
 4030:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4031:         }
 4032:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4033:     }
 4034:     $result .= &Apache::loncommon::start_data_table();
 4035:     #radio buttons/text box for assigning points for a section or class.
 4036:     #handles different parts of a problem
 4037:     my $res_error;
 4038:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4039:     if ($res_error) {
 4040:         return &navmap_errormsg();
 4041:     }
 4042:     my %weight = ();
 4043:     my $ctsparts = 0;
 4044:     my %seen = ();
 4045:     my @part_response_id;
 4046:     if ($is_tool) {
 4047:         @part_response_id = ([0,'']);
 4048:     } else {
 4049:         @part_response_id = &flatten_responseType($responseType);
 4050:     }
 4051:     foreach my $part_response_id (@part_response_id) {
 4052:     	my ($partid,$respid) = @{ $part_response_id };
 4053: 	my $part_resp = join('_',@{ $part_response_id });
 4054: 	next if $seen{$partid};
 4055: 	$seen{$partid}++;
 4056: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4057: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4058: 
 4059: 	my $display_part=&get_display_part($partid,$symb);
 4060: 	my $radio.='<table border="0"><tr>';  
 4061: 	my $ctr = 0;
 4062: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4063: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4064: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4065: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4066: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4067: 	    $ctr++;
 4068: 	}
 4069: 	$radio.='</tr></table>';
 4070: 	my $line = '<input type="text" name="TEXTVAL_'.
 4071: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4072: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4073: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4074:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4075:             '<select name="SELVAL_'.$partid.'" '.
 4076:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4077:                 $weight{$partid}.')"> '.
 4078: 	    '<option selected="selected"> </option>'.
 4079: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4080: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4081: 	    '</select></td>'.
 4082:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4083: 	$line.='<input type="hidden" name="partid_'.
 4084: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4085: 	$line.='<input type="hidden" name="weight_'.
 4086: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4087: 
 4088: 	$result.=
 4089: 	    &Apache::loncommon::start_data_table_row()."\n".
 4090: 	    '<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>'.
 4091: 	    &Apache::loncommon::end_data_table_row()."\n";
 4092: 	$ctsparts++;
 4093:     }
 4094:     $result.=&Apache::loncommon::end_data_table()."\n".
 4095: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4096:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4097: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4098: 
 4099:     #table listing all the students in a section/class
 4100:     #header of table
 4101:     if ($env{'form.submitonly'} eq 'all') {
 4102:         $result.= '<h3>'.$specific_header.'</h3>';
 4103:     } else {
 4104:         my $text;
 4105:         if ($is_tool) {
 4106:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4107:         } else {
 4108:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4109:         }
 4110:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4111:     }
 4112:     $result.= &Apache::loncommon::start_data_table().
 4113: 	      &Apache::loncommon::start_data_table_header_row().
 4114: 	      '<th>'.&mt('No.').'</th>'.
 4115: 	      '<th>'.&nameUserString('header')."</th>\n";
 4116:     my $partserror;
 4117:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4118:     if ($partserror) {
 4119:         return &navmap_errormsg();
 4120:     }
 4121:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4122:     my @partids = ();
 4123:     foreach my $part (@parts) {
 4124: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4125:         my $narrowtext = &mt('Tries');
 4126: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4127: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4128: 	my ($partid) = &split_part_type($part);
 4129:         push(@partids,$partid);
 4130: #
 4131: # FIXME: Looks like $display looks at English text
 4132: #
 4133: 	my $display_part=&get_display_part($partid,$symb);
 4134: 	if ($display =~ /^Partial Credit Factor/) {
 4135: 	    $result.='<th>'.
 4136: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4137: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4138: 	    next;
 4139: 	    
 4140: 	} else {
 4141: 	    if ($display =~ /Problem Status/) {
 4142: 		my $grade_status_mt = &mt('Grade Status');
 4143: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4144: 	    }
 4145: 	    my $part_mt = &mt('Part:');
 4146: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4147: 	}
 4148: 
 4149: 	$result.='<th>'.$display.'</th>'."\n";
 4150:     }
 4151:     $result.=&Apache::loncommon::end_data_table_header_row();
 4152: 
 4153:     my %last_resets = 
 4154: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4155: 
 4156:     #get info for each student
 4157:     #list all the students - with points and grade status
 4158:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4159:     my $ctr = 0;
 4160:     foreach (sort 
 4161: 	     {
 4162: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4163: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4164: 		 }
 4165: 		 return $a cmp $b;
 4166: 	     } (keys(%$fullname))) {
 4167: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4168: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4169:     }
 4170:     $result.=&Apache::loncommon::end_data_table();
 4171:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4172:     $result.='<input type="button" value="'.&mt('Save').'" '.
 4173: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4174:     if ($ctr == 0) {
 4175:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4176:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4177:                 '<span class="LC_warning">';
 4178:         if ($env{'form.submitonly'} eq 'all') {
 4179:             if (grep(/^all$/,@sections)) {
 4180:                 if (grep(/^all$/,@groups)) {
 4181:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4182:                                    $stu_status);
 4183:                 } elsif (grep(/^none$/,@groups)) {
 4184:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4185:                                    $stu_status); 
 4186:                 } else {
 4187:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4188:                                    $group_display,$stu_status);
 4189:                 }
 4190:             } elsif (grep(/^none$/,@sections)) {
 4191:                 if (grep(/^all$/,@groups)) {
 4192:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4193:                                    $stu_status);
 4194:                 } elsif (grep(/^none$/,@groups)) {
 4195:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4196:                                    $stu_status);
 4197:                 } else {
 4198:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4199:                                    $group_display,$stu_status);
 4200:                 }
 4201:             } else {
 4202:                 if (grep(/^all$/,@groups)) {
 4203:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4204:                                    $section_display,$stu_status);
 4205:                 } elsif (grep(/^none$/,@groups)) {
 4206:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4207:                                    $section_display,$stu_status);
 4208:                 } else {
 4209:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4210:                                    $section_display,$group_display,$stu_status);
 4211:                 }
 4212:             }
 4213:         } else {
 4214:             if (grep(/^all$/,@sections)) {
 4215:                 if (grep(/^all$/,@groups)) {
 4216:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4217:                                    $stu_status,$submission_status);
 4218:                 } elsif (grep(/^none$/,@groups)) {
 4219:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4220:                                    $stu_status,$submission_status);
 4221:                 } else {
 4222:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4223:                                    $group_display,$stu_status,$submission_status);
 4224:                 }
 4225:             } elsif (grep(/^none$/,@sections)) {
 4226:                 if (grep(/^all$/,@groups)) {
 4227:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4228:                                    $stu_status,$submission_status);
 4229:                 } elsif (grep(/^none$/,@groups)) {
 4230:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4231:                                    $stu_status,$submission_status);
 4232:                 } else {
 4233:                     $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.',
 4234:                                    $group_display,$stu_status,$submission_status);
 4235:                 }
 4236:             } else {
 4237:                 if (grep(/^all$/,@groups)) {
 4238: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4239: 	                           $section_display,$stu_status,$submission_status);
 4240:                 } elsif (grep(/^none$/,@groups)) {
 4241:                     $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.',
 4242:                                    $section_display,$stu_status,$submission_status);
 4243:                 } else {
 4244:                     $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.',
 4245:                                    $section_display,$group_display,$stu_status,$submission_status);
 4246:                 }
 4247:             }
 4248:         }
 4249: 	$result .= '</span><br />';
 4250:     }
 4251:     return $result;
 4252: }
 4253: 
 4254: #--- call by previous routine to display each student who satisfies submission filter. 
 4255: sub viewstudentgrade {
 4256:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4257:     my ($uname,$udom) = split(/:/,$student);
 4258:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4259:     my $submitonly = $env{'form.submitonly'};
 4260:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4261:         my %partstatus = ();
 4262:         if (ref($parts) eq 'ARRAY') {
 4263:             foreach my $apart (@{$parts}) {
 4264:                 my ($part,$type) = &split_part_type($apart);
 4265:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4266:                 $status = 'nothing' if ($status eq '');
 4267:                 $partstatus{$part}      = $status;
 4268:                 my $subkey = "resource.$part.submitted_by";
 4269:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4270:             }
 4271:             my $submitted = 0;
 4272:             my $graded = 0;
 4273:             my $incorrect = 0;
 4274:             foreach my $key (keys(%partstatus)) {
 4275:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4276:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4277:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4278: 
 4279:                 my $partid = (split(/\./,$key))[1];
 4280:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4281:                     $submitted = 0;
 4282:                 }
 4283:             }
 4284:             return if (!$submitted && ($submitonly eq 'yes' ||
 4285:                                        $submitonly eq 'incorrect' ||
 4286:                                        $submitonly eq 'graded'));
 4287:             return if (!$graded && ($submitonly eq 'graded'));
 4288:             return if (!$incorrect && $submitonly eq 'incorrect');
 4289:         }
 4290:     }
 4291:     if ($submitonly eq 'queued') {
 4292:         my ($cdom,$cnum) = split(/_/,$courseid);
 4293:         my %queue_status =
 4294:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4295:                                                     $udom,$uname);
 4296:         return if (!defined($queue_status{'gradingqueue'}));
 4297:     }
 4298:     $$ctr++;
 4299:     my %aggregates = ();
 4300:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4301: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4302: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4303: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4304: 	'\');" target="_self">'.$fullname.'</a> '.
 4305: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4306:     $student=~s/:/_/; # colon doen't work in javascript for names
 4307:     foreach my $apart (@$parts) {
 4308: 	my ($part,$type) = &split_part_type($apart);
 4309: 	my $score=$record{"resource.$part.$type"};
 4310:         $result.='<td align="center">';
 4311:         my ($aggtries,$totaltries);
 4312:         unless (exists($aggregates{$part})) {
 4313: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4314: 	    $aggtries = $totaltries;
 4315:             if ($$last_resets{$part}) {  
 4316:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4317: 					   $part);
 4318:             }
 4319:             $result.='<input type="hidden" name="'.
 4320:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4321:             $result.='<input type="hidden" name="'.
 4322:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4323:             $aggregates{$part} = 1;
 4324:         }
 4325: 	if ($type eq 'awarded') {
 4326: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4327: 	    $result.='<input type="hidden" name="'.
 4328: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4329: 	    $result.='<input type="text" name="'.
 4330: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4331:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4332: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4333: 	} elsif ($type eq 'solved') {
 4334: 	    my ($status,$foo)=split(/_/,$score,2);
 4335: 	    $status = 'nothing' if ($status eq '');
 4336: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4337: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4338: 	    $result.='&nbsp;<select name="'.
 4339: 		'GD_'.$student.'_'.$part.'_solved" '.
 4340:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4341: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4342: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4343: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4344: 	    $result.="</select>&nbsp;</td>\n";
 4345: 	} else {
 4346: 	    $result.='<input type="hidden" name="'.
 4347: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4348: 		    "\n";
 4349: 	    $result.='<input type="text" name="'.
 4350: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4351: 		'value="'.$score.'" size="4" /></td>'."\n";
 4352: 	}
 4353:     }
 4354:     $result.=&Apache::loncommon::end_data_table_row();
 4355:     return $result;
 4356: }
 4357: 
 4358: #--- change scores for all the students in a section/class
 4359: #    record does not get update if unchanged
 4360: sub editgrades {
 4361:     my ($request,$symb) = @_;
 4362:     my $toolsymb;
 4363:     if ($symb =~ /ext\.tool$/) {
 4364:         $toolsymb = $symb;
 4365:     }
 4366: 
 4367:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4368:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4369:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4370: 
 4371:     my $result= &Apache::loncommon::start_data_table().
 4372: 	&Apache::loncommon::start_data_table_header_row().
 4373: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4374: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4375:     my %scoreptr = (
 4376: 		    'correct'  =>'correct_by_override',
 4377: 		    'incorrect'=>'incorrect_by_override',
 4378: 		    'excused'  =>'excused',
 4379: 		    'ungraded' =>'ungraded_attempted',
 4380:                     'credited' =>'credit_attempted',
 4381: 		    'nothing'  => '',
 4382: 		    );
 4383:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4384: 
 4385:     my (@partid);
 4386:     my %weight = ();
 4387:     my %columns = ();
 4388:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4389: 
 4390:     my $partserror;
 4391:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4392:     if ($partserror) {
 4393:         return &navmap_errormsg();
 4394:     }
 4395:     my $header;
 4396:     while ($ctr < $env{'form.totalparts'}) {
 4397: 	my $partid = $env{'form.partid_'.$ctr};
 4398: 	push(@partid,$partid);
 4399: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4400: 	$ctr++;
 4401:     }
 4402:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4403:     my $totcolspan = 0;
 4404:     foreach my $partid (@partid) {
 4405: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4406: 	    '<th align="center">'.&mt('New Score').'</th>';
 4407: 	$columns{$partid}=2;
 4408: 	foreach my $stores (@parts) {
 4409: 	    my ($part,$type) = &split_part_type($stores);
 4410: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4411: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4412: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4413: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4414:             my $narrowtext = &mt('Tries');
 4415: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4416: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4417: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4418: 	    $columns{$partid}+=2;
 4419: 	}
 4420:         $totcolspan += $columns{$partid};
 4421:     }
 4422:     foreach my $partid (@partid) {
 4423: 	my $display_part=&get_display_part($partid,$symb);
 4424: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4425: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4426: 	    '</th>';
 4427: 
 4428:     }
 4429:     $result .= &Apache::loncommon::end_data_table_header_row().
 4430: 	&Apache::loncommon::start_data_table_header_row().
 4431: 	$header.
 4432: 	&Apache::loncommon::end_data_table_header_row();
 4433:     my @noupdate;
 4434:     my ($updateCtr,$noupdateCtr) = (1,1);
 4435:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4436: 	my $user = $env{'form.ctr'.$i};
 4437: 	my ($uname,$udom)=split(/:/,$user);
 4438: 	my %newrecord;
 4439: 	my $updateflag = 0;
 4440: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4441: 	my $canmodify = &canmodify($usec);
 4442: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4443: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4444: 	if (!$canmodify) {
 4445: 	    push(@noupdate,
 4446: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4447: 		 &mt('Not allowed to modify student')."</span></td>");
 4448: 	    next;
 4449: 	}
 4450:         my %aggregate = ();
 4451:         my $aggregateflag = 0;
 4452: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4453: 	foreach (@partid) {
 4454: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4455: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4456: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4457: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4458: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4459: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4460: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4461: 	    my $score;
 4462: 	    if ($partial eq '') {
 4463: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4464: 	    } elsif ($partial > 0) {
 4465: 		$score = 'correct_by_override';
 4466: 	    } elsif ($partial == 0) {
 4467: 		$score = 'incorrect_by_override';
 4468: 	    }
 4469: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4470: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4471: 
 4472: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4473: 		"$env{'user.name'}:$env{'user.domain'}";
 4474: 	    if ($dropMenu eq 'reset status' &&
 4475: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4476: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4477: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4478: 		$newrecord{'resource.'.$_.'.award'} = '';
 4479: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4480: 		$updateflag = 1;
 4481:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4482:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4483:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4484:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4485:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4486:                     $aggregateflag = 1;
 4487:                 }
 4488: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4489: 		$updateflag = 1;
 4490: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4491: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4492: 		$rec_update++;
 4493: 	    }
 4494: 
 4495: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4496: 		'<td align="center">'.$awarded.
 4497: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4498: 
 4499: 
 4500: 	    my $partid=$_;
 4501: 	    foreach my $stores (@parts) {
 4502: 		my ($part,$type) = &split_part_type($stores);
 4503: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4504: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4505: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4506: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4507: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4508: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4509: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4510: 		    $updateflag=1;
 4511: 		}
 4512: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4513: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4514: 	    }
 4515: 	}
 4516: 	$line.="\n";
 4517: 
 4518: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4519: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4520: 
 4521: 	if ($updateflag) {
 4522: 	    $count++;
 4523: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4524: 				    $udom,$uname);
 4525: 
 4526: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4527: 					      $cnum,$udom,$uname)) {
 4528: 		# need to figure out if should be in queue.
 4529: 		my %record =  
 4530: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4531: 					     $udom,$uname);
 4532: 		my $all_graded = 1;
 4533: 		my $none_graded = 1;
 4534: 		foreach my $part (@parts) {
 4535: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4536: 			$all_graded = 0;
 4537: 		    } else {
 4538: 			$none_graded = 0;
 4539: 		    }
 4540: 		}
 4541: 
 4542: 		if ($all_graded || $none_graded) {
 4543: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4544: 							   $symb,$cdom,$cnum,
 4545: 							   $udom,$uname);
 4546: 		}
 4547: 	    }
 4548: 
 4549: 	    $result.=&Apache::loncommon::start_data_table_row().
 4550: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4551: 		&Apache::loncommon::end_data_table_row();
 4552: 	    $updateCtr++;
 4553: 	} else {
 4554: 	    push(@noupdate,
 4555: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4556: 	    $noupdateCtr++;
 4557: 	}
 4558:         if ($aggregateflag) {
 4559:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4560: 				  $cdom,$cnum);
 4561:         }
 4562:     }
 4563:     if (@noupdate) {
 4564:         my $numcols=$totcolspan+2;
 4565: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4566: 	    '<td align="center" colspan="'.$numcols.'">'.
 4567: 	    &mt('No Changes Occurred For the Students Below').
 4568: 	    '</td>'.
 4569: 	    &Apache::loncommon::end_data_table_row();
 4570: 	foreach my $line (@noupdate) {
 4571: 	    $result.=
 4572: 		&Apache::loncommon::start_data_table_row().
 4573: 		$line.
 4574: 		&Apache::loncommon::end_data_table_row();
 4575: 	}
 4576:     }
 4577:     $result .= &Apache::loncommon::end_data_table();
 4578:     my $msg = '<p><b>'.
 4579: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4580: 	    $rec_update,$count).'</b><br />'.
 4581: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4582: 	'</b></p>';
 4583:     return $title.$msg.$result;
 4584: }
 4585: 
 4586: sub split_part_type {
 4587:     my ($partstr) = @_;
 4588:     my ($temp,@allparts)=split(/_/,$partstr);
 4589:     my $type=pop(@allparts);
 4590:     my $part=join('_',@allparts);
 4591:     return ($part,$type);
 4592: }
 4593: 
 4594: #------------- end of section for handling grading by section/class ---------
 4595: #
 4596: #----------------------------------------------------------------------------
 4597: 
 4598: 
 4599: #----------------------------------------------------------------------------
 4600: #
 4601: #-------------------------- Next few routines handles grading by csv upload
 4602: #
 4603: #--- Javascript to handle csv upload
 4604: sub csvupload_javascript_reverse_associate {
 4605:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4606:     my $error2=&mt('You need to specify at least one grading field');
 4607:   &js_escape(\$error1);
 4608:   &js_escape(\$error2);
 4609:   return(<<ENDPICK);
 4610:   function verify(vf) {
 4611:     var foundsomething=0;
 4612:     var founduname=0;
 4613:     var foundID=0;
 4614:     var foundclicker=0;
 4615:     for (i=0;i<=vf.nfields.value;i++) {
 4616:       tw=eval('vf.f'+i+'.selectedIndex');
 4617:       if (i==0 && tw!=0) { foundID=1; }
 4618:       if (i==1 && tw!=0) { founduname=1; }
 4619:       if (i==2 && tw!=0) { foundclicker=1; }
 4620:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4621:     }
 4622:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4623: 	alert('$error1');
 4624: 	return;
 4625:     }
 4626:     if (foundsomething==0) {
 4627: 	alert('$error2');
 4628: 	return;
 4629:     }
 4630:     vf.submit();
 4631:   }
 4632:   function flip(vf,tf) {
 4633:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4634:     var i;
 4635:     for (i=0;i<=vf.nfields.value;i++) {
 4636:       //can not pick the same destination field for both name and domain
 4637:       if (((i ==0)||(i ==1)) && 
 4638:           ((tf==0)||(tf==1)) && 
 4639:           (i!=tf) &&
 4640:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4641:         eval('vf.f'+i+'.selectedIndex=0;')
 4642:       }
 4643:     }
 4644:   }
 4645: ENDPICK
 4646: }
 4647: 
 4648: sub csvupload_javascript_forward_associate {
 4649:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4650:     my $error2=&mt('You need to specify at least one grading field');
 4651:   &js_escape(\$error1);
 4652:   &js_escape(\$error2);
 4653:   return(<<ENDPICK);
 4654:   function verify(vf) {
 4655:     var foundsomething=0;
 4656:     var founduname=0;
 4657:     var foundID=0;
 4658:     var foundclicker=0;
 4659:     for (i=0;i<=vf.nfields.value;i++) {
 4660:       tw=eval('vf.f'+i+'.selectedIndex');
 4661:       if (tw==1) { foundID=1; }
 4662:       if (tw==2) { founduname=1; }
 4663:       if (tw==3) { foundclicker=1; }
 4664:       if (tw>4) { foundsomething=1; }
 4665:     }
 4666:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4667: 	alert('$error1');
 4668: 	return;
 4669:     }
 4670:     if (foundsomething==0) {
 4671: 	alert('$error2');
 4672: 	return;
 4673:     }
 4674:     vf.submit();
 4675:   }
 4676:   function flip(vf,tf) {
 4677:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4678:     var i;
 4679:     //can not pick the same destination field twice
 4680:     for (i=0;i<=vf.nfields.value;i++) {
 4681:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4682:         eval('vf.f'+i+'.selectedIndex=0;')
 4683:       }
 4684:     }
 4685:   }
 4686: ENDPICK
 4687: }
 4688: 
 4689: sub csvuploadmap_header {
 4690:     my ($request,$symb,$datatoken,$distotal)= @_;
 4691:     my $javascript;
 4692:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4693: 	$javascript=&csvupload_javascript_reverse_associate();
 4694:     } else {
 4695: 	$javascript=&csvupload_javascript_forward_associate();
 4696:     }
 4697: 
 4698:     $symb = &Apache::lonenc::check_encrypt($symb);
 4699:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4700:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4701:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4702:     my $reverse=&mt("Reverse Association");
 4703:     $request->print(<<ENDPICK);
 4704: <br />
 4705: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4706: <input type="hidden" name="associate"  value="" />
 4707: <input type="hidden" name="phase"      value="three" />
 4708: <input type="hidden" name="datatoken"  value="$datatoken" />
 4709: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4710: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4711: <input type="hidden" name="upfile_associate" 
 4712:                                        value="$env{'form.upfile_associate'}" />
 4713: <input type="hidden" name="symb"       value="$symb" />
 4714: <input type="hidden" name="command"    value="csvuploadoptions" />
 4715: <hr />
 4716: ENDPICK
 4717:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4718:     return '';
 4719: 
 4720: }
 4721: 
 4722: sub csvupload_fields {
 4723:     my ($symb,$errorref) = @_;
 4724:     my $toolsymb;
 4725:     if ($symb =~ /ext\.tool$/) {
 4726:         $toolsymb = $symb;
 4727:     }
 4728:     my (@parts) = &getpartlist($symb,$errorref);
 4729:     if (ref($errorref)) {
 4730:         if ($$errorref) {
 4731:             return;
 4732:         }
 4733:     }
 4734: 
 4735:     my @fields=(['ID','Student/Employee ID'],
 4736: 		['username','Student Username'],
 4737: 		['clicker','Clicker ID'],
 4738: 		['domain','Student Domain']);
 4739:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4740:     foreach my $part (sort(@parts)) {
 4741: 	my @datum;
 4742: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4743: 	my $name=$part;
 4744: 	if (!$display) { $display = $name; }
 4745: 	@datum=($name,$display);
 4746: 	if ($name=~/^stores_(.*)_awarded/) {
 4747: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4748: 	}
 4749: 	push(@fields,\@datum);
 4750:     }
 4751:     return (@fields);
 4752: }
 4753: 
 4754: sub csvuploadmap_footer {
 4755:     my ($request,$i,$keyfields) =@_;
 4756:     my $buttontext = &mt('Assign Grades');
 4757:     $request->print(<<ENDPICK);
 4758: </table>
 4759: <input type="hidden" name="nfields" value="$i" />
 4760: <input type="hidden" name="keyfields" value="$keyfields" />
 4761: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4762: </form>
 4763: ENDPICK
 4764: }
 4765: 
 4766: sub checkforfile_js {
 4767:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4768:     &js_escape(\$alertmsg);
 4769:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4770:     function checkUpload(formname) {
 4771: 	if (formname.upfile.value == "") {
 4772: 	    alert("$alertmsg");
 4773: 	    return false;
 4774: 	}
 4775: 	formname.submit();
 4776:     }
 4777: CSVFORMJS
 4778:     return $result;
 4779: }
 4780: 
 4781: sub upcsvScores_form {
 4782:     my ($request,$symb) = @_;
 4783:     if (!$symb) {return '';}
 4784:     my $result=&checkforfile_js();
 4785:     $result.=&Apache::loncommon::start_data_table().
 4786:              &Apache::loncommon::start_data_table_header_row().
 4787:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4788:              &Apache::loncommon::end_data_table_header_row().
 4789:              &Apache::loncommon::start_data_table_row().'<td>';
 4790:     my $upload=&mt("Upload Scores");
 4791:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4792:     my $ignore=&mt('Ignore First Line');
 4793:     $symb = &Apache::lonenc::check_encrypt($symb);
 4794:     $result.=<<ENDUPFORM;
 4795: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4796: <input type="hidden" name="symb" value="$symb" />
 4797: <input type="hidden" name="command" value="csvuploadmap" />
 4798: $upfile_select
 4799: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4800: </form>
 4801: ENDUPFORM
 4802:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4803:                            &mt("How do I create a CSV file from a spreadsheet")).
 4804:              '</td>'.
 4805:             &Apache::loncommon::end_data_table_row().
 4806:             &Apache::loncommon::end_data_table();
 4807:     return $result;
 4808: }
 4809: 
 4810: 
 4811: sub csvuploadmap {
 4812:     my ($request,$symb) = @_;
 4813:     if (!$symb) {return '';}
 4814: 
 4815:     my $datatoken;
 4816:     if (!$env{'form.datatoken'}) {
 4817: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4818:     } else {
 4819: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4820:         if ($datatoken ne '') {
 4821: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4822:         }
 4823:     }
 4824:     my @records=&Apache::loncommon::upfile_record_sep();
 4825:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4826:     my ($i,$keyfields);
 4827:     if (@records) {
 4828:         my $fieldserror;
 4829: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4830:         if ($fieldserror) {
 4831:             $request->print(&navmap_errormsg());
 4832:             return;
 4833:         }
 4834: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4835: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4836: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4837: 							  \@fields);
 4838: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4839: 	    chop($keyfields);
 4840: 	} else {
 4841: 	    unshift(@fields,['none','']);
 4842: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4843: 							    \@fields);
 4844:             foreach my $rec (@records) {
 4845:                 my %temp = &Apache::loncommon::record_sep($rec);
 4846:                 if (%temp) {
 4847:                     $keyfields=join(',',sort(keys(%temp)));
 4848:                     last;
 4849:                 }
 4850:             }
 4851: 	}
 4852:     }
 4853:     &csvuploadmap_footer($request,$i,$keyfields);
 4854: 
 4855:     return '';
 4856: }
 4857: 
 4858: sub csvuploadoptions {
 4859:     my ($request,$symb)= @_;
 4860:     my $overwrite=&mt('Overwrite any existing score');
 4861:     $request->print(<<ENDPICK);
 4862: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4863: <input type="hidden" name="command"    value="csvuploadassign" />
 4864: <p>
 4865: <label>
 4866:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4867:    $overwrite
 4868: </label>
 4869: </p>
 4870: ENDPICK
 4871:     my %fields=&get_fields();
 4872:     if (!defined($fields{'domain'})) {
 4873: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4874: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4875:     }
 4876:     foreach my $key (sort(keys(%env))) {
 4877: 	if ($key !~ /^form\.(.*)$/) { next; }
 4878: 	my $cleankey=$1;
 4879: 	if ($cleankey eq 'command') { next; }
 4880: 	$request->print('<input type="hidden" name="'.$cleankey.
 4881: 			'"  value="'.$env{$key}.'" />'."\n");
 4882:     }
 4883:     # FIXME do a check for any duplicated user ids...
 4884:     # FIXME do a check for any invalid user ids?...
 4885:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4886: <hr /></form>'."\n");
 4887:     return '';
 4888: }
 4889: 
 4890: sub get_fields {
 4891:     my %fields;
 4892:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4893:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4894: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4895: 	    if ($env{'form.f'.$i} ne 'none') {
 4896: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4897: 	    }
 4898: 	} else {
 4899: 	    if ($env{'form.f'.$i} ne 'none') {
 4900: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4901: 	    }
 4902: 	}
 4903:     }
 4904:     return %fields;
 4905: }
 4906: 
 4907: sub csvuploadassign {
 4908:     my ($request,$symb) = @_;
 4909:     if (!$symb) {return '';}
 4910:     my $error_msg = '';
 4911:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4912:     if ($datatoken ne '') { 
 4913:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4914:     }
 4915:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4916:     my %fields=&get_fields();
 4917:     my $courseid=$env{'request.course.id'};
 4918:     my ($classlist) = &getclasslist('all',0);
 4919:     my @notallowed;
 4920:     my @skipped;
 4921:     my @warnings;
 4922:     my $countdone=0;
 4923:     foreach my $grade (@gradedata) {
 4924: 	my %entries=&Apache::loncommon::record_sep($grade);
 4925: 	my $domain;
 4926: 	if ($entries{$fields{'domain'}}) {
 4927: 	    $domain=$entries{$fields{'domain'}};
 4928: 	} else {
 4929: 	    $domain=$env{'form.default_domain'};
 4930: 	}
 4931: 	$domain=~s/\s//g;
 4932: 	my $username=$entries{$fields{'username'}};
 4933: 	$username=~s/\s//g;
 4934: 	if (!$username) {
 4935: 	    my $id=$entries{$fields{'ID'}};
 4936: 	    $id=~s/\s//g;
 4937:             if ($id ne '') {
 4938: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4939: 	        $username=$ids{$id};
 4940:             } else {
 4941:                 if ($entries{$fields{'clicker'}}) {
 4942:                     my $clicker = $entries{$fields{'clicker'}};
 4943:                     $clicker=~s/\s//g;
 4944:                     if ($clicker ne '') {
 4945:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4946:                         if ($clickers{$clicker} ne '') {  
 4947:                             my $match = 0;
 4948:                             my @inclass;
 4949:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4950:                                 if (exists($$classlist{"$poss:$domain"})) {
 4951:                                     $username = $poss;
 4952:                                     push(@inclass,$poss);
 4953:                                     $match ++;
 4954:                                     
 4955:                                 }
 4956:                             }
 4957:                             if ($match > 1) {
 4958:                                 undef($username); 
 4959:                                 $request->print('<p class="LC_warning">'.
 4960:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4961:                                                 $clicker,join(', ',@inclass)).'</p>');
 4962:                             }
 4963:                         }
 4964:                     }
 4965:                 }
 4966:             }
 4967: 	}
 4968: 	if (!exists($$classlist{"$username:$domain"})) {
 4969: 	    my $id=$entries{$fields{'ID'}};
 4970: 	    $id=~s/\s//g;
 4971:             my $clicker = $entries{$fields{'clicker'}};
 4972:             $clicker=~s/\s//g;
 4973:             if ($clicker) {
 4974:                 push(@skipped,"$clicker:$domain");
 4975: 	    } elsif ($id) {
 4976: 		push(@skipped,"$id:$domain");
 4977: 	    } else {
 4978: 		push(@skipped,"$username:$domain");
 4979: 	    }
 4980: 	    next;
 4981: 	}
 4982: 	my $usec=$classlist->{"$username:$domain"}[5];
 4983: 	if (!&canmodify($usec)) {
 4984: 	    push(@notallowed,"$username:$domain");
 4985: 	    next;
 4986: 	}
 4987: 	my %points;
 4988: 	my %grades;
 4989: 	foreach my $dest (keys(%fields)) {
 4990: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4991: 		$dest eq 'domain') { next; }
 4992: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4993: 	    if ($dest=~/stores_(.*)_points/) {
 4994: 		my $part=$1;
 4995: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4996: 					      $symb,$domain,$username);
 4997:                 if ($wgt) {
 4998:                     $entries{$fields{$dest}}=~s/\s//g;
 4999:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5000:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5001:                                           : 'correct_by_override';
 5002:                     if ($pcr>1) {
 5003:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5004:                     }
 5005:                     $grades{"resource.$part.awarded"}=$pcr;
 5006:                     $grades{"resource.$part.solved"}=$award;
 5007:                     $points{$part}=1;
 5008:                 } else {
 5009:                     $error_msg = "<br />" .
 5010:                         &mt("Some point values were assigned"
 5011:                             ." for problems with a weight "
 5012:                             ."of zero. These values were "
 5013:                             ."ignored.");
 5014:                 }
 5015: 	    } else {
 5016: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5017: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5018: 		my $store_key=$dest;
 5019: 		$store_key=~s/^stores/resource/;
 5020: 		$store_key=~s/_/\./g;
 5021: 		$grades{$store_key}=$entries{$fields{$dest}};
 5022: 	    }
 5023: 	}
 5024: 	if (! %grades) {
 5025:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5026:         } else {
 5027: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5028: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5029: 					   $env{'request.course.id'},
 5030: 					   $domain,$username);
 5031: 	   if ($result eq 'ok') {
 5032: # Successfully stored
 5033: 	      $request->print('.');
 5034: # Remove from grading queue
 5035:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5036:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5037:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5038:                                              $domain,$username);
 5039:               $countdone++;
 5040:            } else {
 5041: 	      $request->print("<p><span class=\"LC_error\">".
 5042:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5043:                                   "$username:$domain",$result)."</span></p>");
 5044: 	   }
 5045: 	   $request->rflush();
 5046:         }
 5047:     }
 5048:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5049:     if (@warnings) {
 5050:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5051:         $request->print(join(', ',@warnings));
 5052:     }
 5053:     if (@skipped) {
 5054: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5055:         $request->print(join(', ',@skipped));
 5056:     }
 5057:     if (@notallowed) {
 5058: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5059: 	$request->print(join(', ',@notallowed));
 5060:     }
 5061:     $request->print("<br />\n");
 5062:     return $error_msg;
 5063: }
 5064: #------------- end of section for handling csv file upload ---------
 5065: #
 5066: #-------------------------------------------------------------------
 5067: #
 5068: #-------------- Next few routines handle grading by page/sequence
 5069: #
 5070: #--- Select a page/sequence and a student to grade
 5071: sub pickStudentPage {
 5072:     my ($request,$symb) = @_;
 5073: 
 5074:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5075:     &js_escape(\$alertmsg);
 5076:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5077: 
 5078: function checkPickOne(formname) {
 5079:     if (radioSelection(formname.student) == null) {
 5080: 	alert("$alertmsg");
 5081: 	return;
 5082:     }
 5083:     ptr = pullDownSelection(formname.selectpage);
 5084:     formname.page.value = formname["page"+ptr].value;
 5085:     formname.title.value = formname["title"+ptr].value;
 5086:     formname.submit();
 5087: }
 5088: 
 5089: LISTJAVASCRIPT
 5090:     &commonJSfunctions($request);
 5091: 
 5092:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5093:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5094:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5095:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5096: 
 5097:     my $result='<h3><span class="LC_info">&nbsp;'.
 5098: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5099: 
 5100:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5101:     my $map_error;
 5102:     my ($titles,$symbx) = &getSymbMap($map_error);
 5103:     if ($map_error) {
 5104:         $request->print(&navmap_errormsg());
 5105:         return; 
 5106:     }
 5107:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5108: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5109: #    my $type=($curpage =~ /\.(page|sequence)/);
 5110: 
 5111:     # Collection of hidden fields
 5112:     my $ctr=0;
 5113:     foreach (@$titles) {
 5114:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5115:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5116:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5117:         $ctr++;
 5118:     }
 5119:     $result.='<input type="hidden" name="page" />'."\n".
 5120:         '<input type="hidden" name="title" />'."\n";
 5121: 
 5122:     $result.=&build_section_inputs();
 5123:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5124:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5125: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5126: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5127: 
 5128:     # Show grading options
 5129:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5130:     my $select = '<select name="selectpage">'."\n";
 5131:     $ctr=0;
 5132:     foreach (@$titles) {
 5133: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5134: 	$select.='<option value="'.$ctr.'"'.
 5135: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5136: 	    '>'.$showtitle.'</option>'."\n";
 5137: 	$ctr++;
 5138:     }
 5139:     $select.= '</select>';
 5140: 
 5141:     $result.=
 5142:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5143:        .$select
 5144:        .&Apache::lonhtmlcommon::row_closure();
 5145: 
 5146:     $result.=
 5147:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5148:        .'<label><input type="radio" name="vProb" value="no"'
 5149:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5150:        .'<label><input type="radio" name="vProb" value="yes" />'
 5151:            .&mt('yes').'</label>'."\n"
 5152:        .&Apache::lonhtmlcommon::row_closure();
 5153: 
 5154:     $result.=
 5155:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5156:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5157:            .&mt('none').' </label>'."\n"
 5158:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5159:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5160:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5161:            .&mt('all submissions with details').' </label>'
 5162:        .&Apache::lonhtmlcommon::row_closure();
 5163:     
 5164:     $result.=
 5165:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5166:        .'<input type="text" name="CODE" value="" />'
 5167:        .&Apache::lonhtmlcommon::row_closure(1)
 5168:        .&Apache::lonhtmlcommon::end_pick_box();
 5169: 
 5170:     # Show list of students to select for grading
 5171:     $result.='<br /><input type="button" '.
 5172:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5173: 
 5174:     $request->print($result);
 5175: 
 5176:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5177: 	&Apache::loncommon::start_data_table().
 5178: 	&Apache::loncommon::start_data_table_header_row().
 5179: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5180: 	'<th>'.&nameUserString('header').'</th>'.
 5181: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5182: 	'<th>'.&nameUserString('header').'</th>'.
 5183: 	&Apache::loncommon::end_data_table_header_row();
 5184:  
 5185:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5186:     my $ptr = 1;
 5187:     foreach my $student (sort 
 5188: 			 {
 5189: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5190: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5191: 			     }
 5192: 			     return $a cmp $b;
 5193: 			 } (keys(%$fullname))) {
 5194: 	my ($uname,$udom) = split(/:/,$student);
 5195: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5196:                                   : '</td>');
 5197: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5198: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5199: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5200: 	$studentTable.=
 5201: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5202:                          : '');
 5203: 	$ptr++;
 5204:     }
 5205:     if ($ptr%2 == 0) {
 5206: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5207: 	    &Apache::loncommon::end_data_table_row();
 5208:     }
 5209:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5210:     $studentTable.='<input type="button" '.
 5211:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5212: 
 5213:     $request->print($studentTable);
 5214: 
 5215:     return '';
 5216: }
 5217: 
 5218: sub getSymbMap {
 5219:     my ($map_error) = @_;
 5220:     my $navmap = Apache::lonnavmaps::navmap->new();
 5221:     unless (ref($navmap)) {
 5222:         if (ref($map_error)) {
 5223:             $$map_error = 'navmap';
 5224:         }
 5225:         return;
 5226:     }
 5227:     my %symbx = ();
 5228:     my @titles = ();
 5229:     my $minder = 0;
 5230: 
 5231:     # Gather every sequence that has problems.
 5232:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5233: 					       1,0,1);
 5234:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5235: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5236: 	    my $title = $minder.'.'.
 5237: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5238: 	    push(@titles, $title); # minder in case two titles are identical
 5239: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5240: 	    $minder++;
 5241: 	}
 5242:     }
 5243:     return \@titles,\%symbx;
 5244: }
 5245: 
 5246: #
 5247: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5248: sub displayPage {
 5249:     my ($request,$symb) = @_;
 5250:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5251:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5252:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5253:     my $pageTitle = $env{'form.page'};
 5254:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5255:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5256:     my $usec=$classlist->{$env{'form.student'}}[5];
 5257: 
 5258:     #need to make sure we have the correct data for later EXT calls, 
 5259:     #thus invalidate the cache
 5260:     &Apache::lonnet::devalidatecourseresdata(
 5261:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5262:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5263:     &Apache::lonnet::clear_EXT_cache_status();
 5264: 
 5265:     if (!&canview($usec)) {
 5266:         $request->print(
 5267:             '<span class="LC_warning">'.
 5268:             &mt('Unable to view requested student. ([_1])',
 5269:                     $env{'form.student'}).
 5270:             '</span>');
 5271:         return;
 5272:     }
 5273:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5274:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5275: 	'</h3>'."\n";
 5276:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5277:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5278: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5279:     } else {
 5280: 	delete($env{'form.CODE'});
 5281:     }
 5282:     &sub_page_js($request);
 5283:     $request->print($result);
 5284: 
 5285:     my $navmap = Apache::lonnavmaps::navmap->new();
 5286:     unless (ref($navmap)) {
 5287:         $request->print(&navmap_errormsg());
 5288:         return;
 5289:     }
 5290:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5291:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5292:     if (!$map) {
 5293: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5294: 	return; 
 5295:     }
 5296:     my $iterator = $navmap->getIterator($map->map_start(),
 5297: 					$map->map_finish());
 5298: 
 5299:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5300: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5301: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5302: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5303: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5304: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5305: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5306: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5307: 
 5308:     if (defined($env{'form.CODE'})) {
 5309: 	$studentTable.=
 5310: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5311:     }
 5312:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5313: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5314: 
 5315:     $studentTable.='&nbsp;<span class="LC_info">'.
 5316:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5317:         '</span>'."\n".
 5318: 	&Apache::loncommon::start_data_table().
 5319: 	&Apache::loncommon::start_data_table_header_row().
 5320: 	'<th>'.&mt('Prob.').'</th>'.
 5321: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5322: 	&Apache::loncommon::end_data_table_header_row();
 5323: 
 5324:     &Apache::lonxml::clear_problem_counter();
 5325:     my ($depth,$question,$prob) = (1,1,1);
 5326:     $iterator->next(); # skip the first BEGIN_MAP
 5327:     my $curRes = $iterator->next(); # for "current resource"
 5328:     while ($depth > 0) {
 5329:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5330:         if($curRes == $iterator->END_MAP) { $depth--; }
 5331: 
 5332:         if (ref($curRes) && $curRes->is_gradable()) {
 5333: 	    my $parts = $curRes->parts();
 5334:             my $title = $curRes->compTitle();
 5335: 	    my $symbx = $curRes->symb();
 5336:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5337: 	    $studentTable.=
 5338: 		&Apache::loncommon::start_data_table_row().
 5339: 		'<td align="center" valign="top" >'.$prob.
 5340: 		(scalar(@{$parts}) == 1 ? '' 
 5341: 		                        : '<br />('.&mt('[_1]parts',
 5342: 							scalar(@{$parts}).'&nbsp;').')'
 5343: 		 ).
 5344: 		 '</td>';
 5345: 	    $studentTable.='<td valign="top">';
 5346: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5347:             if ($is_tool) {
 5348:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5349:             } else {
 5350: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5351: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5352: 					         undef,'both',\%form);
 5353: 	        } else {
 5354: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5355: 		    $companswer =~ s|<form(.*?)>||g;
 5356: 		    $companswer =~ s|</form>||g;
 5357: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5358: #		        $companswer =~ s/$1/ /ms;
 5359: #		        $request->print('match='.$1."<br />\n");
 5360: #		    }
 5361: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5362: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5363: 		}
 5364: 	    }
 5365: 
 5366: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5367: 
 5368: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5369: 		if ($record{'version'} eq '') {
 5370:                     my $msg = &mt('No recorded submission for this problem.');
 5371:                     if ($is_tool) {
 5372:                         $msg = &mt('No recorded transactions for this external tool');
 5373:                     }
 5374: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5375: 		} else {
 5376: 		    my %responseType = ();
 5377: 		    foreach my $partid (@{$parts}) {
 5378: 			my @responseIds =$curRes->responseIds($partid);
 5379: 			my @responseType =$curRes->responseType($partid);
 5380: 			my %responseIds;
 5381: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5382: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5383: 			}
 5384: 			$responseType{$partid} = \%responseIds;
 5385: 		    }
 5386: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5387: 		}
 5388: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5389: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5390:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5391: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5392: 									$env{'request.course.id'},
 5393: 									'','.submission',undef,
 5394:                                                                         $usec,$identifier);
 5395:  
 5396: 	    }
 5397: 	    if (&canmodify($usec)) {
 5398:             $studentTable.=&gradeBox_start();
 5399: 		foreach my $partid (@{$parts}) {
 5400: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5401: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5402: 		    $question++;
 5403: 		}
 5404:             $studentTable.=&gradeBox_end();
 5405: 		$prob++;
 5406: 	    }
 5407: 	    $studentTable.='</td></tr>';
 5408: 
 5409: 	}
 5410:         $curRes = $iterator->next();
 5411:     }
 5412: 
 5413:     $studentTable.=
 5414:         '</table>'."\n".
 5415:         '<input type="button" value="'.&mt('Save').'" '.
 5416:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5417:         '</form>'."\n";
 5418:     $request->print($studentTable);
 5419: 
 5420:     return '';
 5421: }
 5422: 
 5423: sub displaySubByDates {
 5424:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5425:     my $isCODE=0;
 5426:     my $isTask = ($symb =~/\.task$/);
 5427:     my $is_tool = ($symb =~/\.tool$/);
 5428:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5429:     my $studentTable=&Apache::loncommon::start_data_table().
 5430: 	&Apache::loncommon::start_data_table_header_row().
 5431: 	'<th>'.&mt('Date/Time').'</th>'.
 5432: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5433:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5434: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5435: 	'<th>'.&mt('Status').'</th>'.
 5436: 	&Apache::loncommon::end_data_table_header_row();
 5437:     my ($version);
 5438:     my %mark;
 5439:     my %orders;
 5440:     $mark{'correct_by_student'} = $checkIcon;
 5441:     if (!exists($$record{'1:timestamp'})) {
 5442:         if ($is_tool) {
 5443:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5444:         } else {
 5445:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5446:         }
 5447:     }
 5448: 
 5449:     my $interaction;
 5450:     my $no_increment = 1;
 5451:     my (%lastrndseed,%lasttype);
 5452:     for ($version=1;$version<=$$record{'version'};$version++) {
 5453: 	my $timestamp = 
 5454: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5455: 	if (exists($$record{$version.':resource.0.version'})) {
 5456: 	    $interaction = $$record{$version.':resource.0.version'};
 5457: 	}
 5458:         if ($isTask && $env{'form.previousversion'}) {
 5459:             next unless ($interaction == $env{'form.previousversion'});
 5460:         }
 5461: 	my $where = ($isTask ? "$version:resource.$interaction"
 5462: 		             : "$version:resource");
 5463: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5464: 	    '<td>'.$timestamp.'</td>';
 5465: 	if ($isCODE) {
 5466: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5467: 	}
 5468:         if ($isTask) {
 5469:             $studentTable.='<td>'.$interaction.'</td>';
 5470:         }
 5471: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5472: 	my @displaySub = ();
 5473: 	foreach my $partid (@{$parts}) {
 5474:             my ($hidden,$type);
 5475:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5476:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5477:                 $hidden = 1;
 5478:             }
 5479:             my @matchKey;
 5480:             if ($isTask) {
 5481:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5482:             } elsif ($is_tool) {
 5483:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5484:             } else {
 5485:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5486:             }
 5487: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5488: 	    my $display_part=&get_display_part($partid,$symb);
 5489: 	    foreach my $matchKey (@matchKey) {
 5490: 		if (exists($$record{$version.':'.$matchKey}) &&
 5491: 		    $$record{$version.':'.$matchKey} ne '') {
 5492:                     if ($is_tool) {
 5493:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5494:                     } else {
 5495: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5496: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5497:                         $displaySub[0].='<span class="LC_nobreak">';
 5498:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5499:                                        .' <span class="LC_internal_info">'
 5500:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5501:                                        .'</span>'
 5502:                                        .' <b>';
 5503:                         if ($hidden) {
 5504:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5505:                         } else {
 5506:                             my ($trial,$rndseed,$newvariation);
 5507:                             if ($type eq 'randomizetry') {
 5508:                                 $trial = $$record{"$where.$partid.tries"};
 5509:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5510:                             }
 5511: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5512: 			        $displaySub[0].=&mt('Trial not counted');
 5513: 		            } else {
 5514: 			        $displaySub[0].=&mt('Trial: [_1]',
 5515: 					        $$record{"$where.$partid.tries"});
 5516:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5517:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5518:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5519:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5520:                                     }
 5521:                                 }
 5522:                                 $lastrndseed{$partid} = $rndseed;
 5523:                                 $lasttype{$partid} = $type;
 5524: 		            }
 5525: 		            my $responseType=($isTask ? 'Task'
 5526:                                               : $responseType->{$partid}->{$responseId});
 5527: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5528: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5529: 			        $orders{$partid}->{$responseId}=
 5530: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5531:                                                $no_increment,$type,$trial,$rndseed);
 5532: 		            }
 5533: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5534: 		            $displaySub[0].='&nbsp; '.
 5535: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5536:                         }
 5537:                     }
 5538: 		}
 5539: 	    }
 5540: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5541: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5542: 				    $$record{"$where.$partid.checkedin"},
 5543: 				    $$record{"$where.$partid.checkedin.slot"}).
 5544: 					'<br />';
 5545: 	    }
 5546: 	    if (exists $$record{"$where.$partid.award"}) {
 5547: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5548: 		    lc($$record{"$where.$partid.award"}).' '.
 5549: 		    $mark{$$record{"$where.$partid.solved"}}.
 5550: 		    '<br />';
 5551: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5552: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5553: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5554: 		}
 5555: 	    }
 5556: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5557: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5558: 		unless ($is_tool) {
 5559: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5560: 		}
 5561: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5562: 		$displaySub[2].=
 5563: 		    $$record{"$version:resource.$partid.regrader"};
 5564:                 unless ($is_tool) {
 5565: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5566:                 }
 5567: 	    }
 5568: 	}
 5569: 	# needed because old essay regrader has not parts info
 5570: 	if (exists $$record{"$version:resource.regrader"}) {
 5571: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5572: 	}
 5573: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5574: 	if ($displaySub[2]) {
 5575: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5576: 	}
 5577: 	$studentTable.='&nbsp;</td>'.
 5578: 	    &Apache::loncommon::end_data_table_row();
 5579:     }
 5580:     $studentTable.=&Apache::loncommon::end_data_table();
 5581:     return $studentTable;
 5582: }
 5583: 
 5584: sub updateGradeByPage {
 5585:     my ($request,$symb) = @_;
 5586: 
 5587:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5588:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5589:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5590:     my $pageTitle = $env{'form.page'};
 5591:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5592:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5593:     my $usec=$classlist->{$env{'form.student'}}[5];
 5594:     if (!&canmodify($usec)) {
 5595: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5596: 	return;
 5597:     }
 5598:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5599:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5600: 	'</h3>'."\n";
 5601: 
 5602:     $request->print($result);
 5603: 
 5604: 
 5605:     my $navmap = Apache::lonnavmaps::navmap->new();
 5606:     unless (ref($navmap)) {
 5607:         $request->print(&navmap_errormsg());
 5608:         return;
 5609:     }
 5610:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5611:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5612:     if (!$map) {
 5613: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5614: 	return; 
 5615:     }
 5616:     my $iterator = $navmap->getIterator($map->map_start(),
 5617: 					$map->map_finish());
 5618: 
 5619:     my $studentTable=
 5620: 	&Apache::loncommon::start_data_table().
 5621: 	&Apache::loncommon::start_data_table_header_row().
 5622: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5623: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5624: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5625: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5626: 	&Apache::loncommon::end_data_table_header_row();
 5627: 
 5628:     $iterator->next(); # skip the first BEGIN_MAP
 5629:     my $curRes = $iterator->next(); # for "current resource"
 5630:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5631:     while ($depth > 0) {
 5632:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5633:         if($curRes == $iterator->END_MAP) { $depth--; }
 5634: 
 5635:         if (ref($curRes) && $curRes->is_problem()) {
 5636: 	    my $parts = $curRes->parts();
 5637:             my $title = $curRes->compTitle();
 5638: 	    my $symbx = $curRes->symb();
 5639: 	    $studentTable.=
 5640: 		&Apache::loncommon::start_data_table_row().
 5641: 		'<td align="center" valign="top" >'.$prob.
 5642: 		(scalar(@{$parts}) == 1 ? '' 
 5643:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5644: 		.')').'</td>';
 5645: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5646: 
 5647: 	    my %newrecord=();
 5648: 	    my @displayPts=();
 5649:             my %aggregate = ();
 5650:             my $aggregateflag = 0;
 5651:             if ($env{'form.HIDE'.$prob}) {
 5652:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5653:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5654:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5655:                 $hideflag += $numchgs;
 5656:             }
 5657: 	    foreach my $partid (@{$parts}) {
 5658: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5659: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5660: 
 5661: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5662: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5663: 		my $partial = $newpts/$wgt;
 5664: 		my $score;
 5665: 		if ($partial > 0) {
 5666: 		    $score = 'correct_by_override';
 5667: 		} elsif ($newpts ne '') { #empty is taken as 0
 5668: 		    $score = 'incorrect_by_override';
 5669: 		}
 5670: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5671: 		if ($dropMenu eq 'excused') {
 5672: 		    $partial = '';
 5673: 		    $score = 'excused';
 5674: 		} elsif ($dropMenu eq 'reset status'
 5675: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5676: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5677: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5678: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5679: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5680: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5681: 		    $changeflag++;
 5682: 		    $newpts = '';
 5683:                     
 5684:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5685:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5686:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5687:                     if ($aggtries > 0) {
 5688:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5689:                         $aggregateflag = 1;
 5690:                     }
 5691: 		}
 5692: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5693: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5694: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5695: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5696: 		    '&nbsp;<br />';
 5697: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5698: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5699: 		    '&nbsp;<br />';
 5700: 		$question++;
 5701: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5702: 
 5703: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5704: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5705: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5706: 		    if (scalar(keys(%newrecord)) > 0);
 5707: 
 5708: 		$changeflag++;
 5709: 	    }
 5710: 	    if (scalar(keys(%newrecord)) > 0) {
 5711: 		my %record = 
 5712: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5713: 					     $udom,$uname);
 5714: 
 5715: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5716: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5717: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5718: 		    $newrecord{'resource.CODE'} = '';
 5719: 		}
 5720: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5721: 					$udom,$uname);
 5722: 		%record = &Apache::lonnet::restore($symbx,
 5723: 						   $env{'request.course.id'},
 5724: 						   $udom,$uname);
 5725: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5726: 					     $cdom,$cnum,$udom,$uname);
 5727: 	    }
 5728: 	    
 5729:             if ($aggregateflag) {
 5730:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5731:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5732:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5733:             }
 5734: 
 5735: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5736: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5737: 		&Apache::loncommon::end_data_table_row();
 5738: 
 5739: 	    $prob++;
 5740: 	}
 5741:         $curRes = $iterator->next();
 5742:     }
 5743: 
 5744:     $studentTable.=&Apache::loncommon::end_data_table();
 5745:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5746: 		  &mt('The scores were changed for [quant,_1,problem].',
 5747: 		  $changeflag).'<br />');
 5748:     my $hidemsg=($hideflag == 0 ? '' :
 5749:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5750:                      $hideflag).'<br />');
 5751:     $request->print($hidemsg.$grademsg.$studentTable);
 5752: 
 5753:     return '';
 5754: }
 5755: 
 5756: #-------- end of section for handling grading by page/sequence ---------
 5757: #
 5758: #-------------------------------------------------------------------
 5759: 
 5760: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5761: #
 5762: #------ start of section for handling grading by page/sequence ---------
 5763: 
 5764: =pod
 5765: 
 5766: =head1 Bubble sheet grading routines
 5767: 
 5768:   For this documentation:
 5769: 
 5770:    'scanline' refers to the full line of characters
 5771:    from the file that we are parsing that represents one entire sheet
 5772: 
 5773:    'bubble line' refers to the data
 5774:    representing the line of bubbles that are on the physical bubblesheet
 5775: 
 5776: 
 5777: The overall process is that a scanned in bubblesheet data is uploaded
 5778: into a course. When a user wants to grade, they select a
 5779: sequence/folder of resources, a file of bubblesheet info, and pick
 5780: one of the predefined configurations for what each scanline looks
 5781: like.
 5782: 
 5783: Next each scanline is checked for any errors of either 'missing
 5784: bubbles' (it's an error because it may have been mis-scanned
 5785: because too light bubbling), 'double bubble' (each bubble line should
 5786: have no more than one letter picked), invalid or duplicated CODE,
 5787: invalid student/employee ID
 5788: 
 5789: If the CODE option is used that determines the randomization of the
 5790: homework problems, either way the student/employee ID is looked up into a
 5791: username:domain.
 5792: 
 5793: During the validation phase the instructor can choose to skip scanlines. 
 5794: 
 5795: After the validation phase, there are now 3 bubblesheet files
 5796: 
 5797:   scantron_original_filename (unmodified original file)
 5798:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5799:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5800: 
 5801: Also there is a separate hash nohist_scantrondata that contains extra
 5802: correction information that isn't representable in the bubblesheet
 5803: file (see &scantron_getfile() for more information)
 5804: 
 5805: After all scanlines are either valid, marked as valid or skipped, then
 5806: foreach line foreach problem in the picked sequence, an ssi request is
 5807: made that simulates a user submitting their selected letter(s) against
 5808: the homework problem.
 5809: 
 5810: =over 4
 5811: 
 5812: 
 5813: 
 5814: =item defaultFormData
 5815: 
 5816:   Returns html hidden inputs used to hold context/default values.
 5817: 
 5818:  Arguments:
 5819:   $symb - $symb of the current resource 
 5820: 
 5821: =cut
 5822: 
 5823: sub defaultFormData {
 5824:     my ($symb)=@_;
 5825:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5826: }
 5827: 
 5828: 
 5829: =pod 
 5830: 
 5831: =item getSequenceDropDown
 5832: 
 5833:    Return html dropdown of possible sequences to grade
 5834:  
 5835:  Arguments:
 5836:    $symb - $symb of the current resource
 5837:    $map_error - ref to scalar which will container error if
 5838:                 $navmap object is unavailable in &getSymbMap().
 5839: 
 5840: =cut
 5841: 
 5842: sub getSequenceDropDown {
 5843:     my ($symb,$map_error)=@_;
 5844:     my $result='<select name="selectpage">'."\n";
 5845:     my ($titles,$symbx) = &getSymbMap($map_error);
 5846:     if (ref($map_error)) {
 5847:         return if ($$map_error);
 5848:     }
 5849:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5850:     my $ctr=0;
 5851:     foreach (@$titles) {
 5852: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5853: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5854: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5855: 	    '>'.$showtitle.'</option>'."\n";
 5856: 	$ctr++;
 5857:     }
 5858:     $result.= '</select>';
 5859:     return $result;
 5860: }
 5861: 
 5862: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5863:                                    # key is zero-based index - 0, 1, 2 ...
 5864: 
 5865: my %first_bubble_line;             # First bubble line no. for each bubble.
 5866: 
 5867: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5868:                                    # matchresponse or rankresponse, where 
 5869:                                    # an individual response can have multiple 
 5870:                                    # lines
 5871: 
 5872: my %responsetype_per_response;     # responsetype for each response
 5873: 
 5874: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5875:                                    # numbered response. Needed when randomorder
 5876:                                    # or randompick are in use. Key is ID, value 
 5877:                                    # is response number.
 5878: 
 5879: # Save and restore the bubble lines array to the form env.
 5880: 
 5881: 
 5882: sub save_bubble_lines {
 5883:     foreach my $line (keys(%bubble_lines_per_response)) {
 5884: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5885: 	$env{"form.scantron.first_bubble_line.$line"} =
 5886: 	    $first_bubble_line{$line};
 5887:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5888:             $subdivided_bubble_lines{$line};
 5889:         $env{"form.scantron.responsetype.$line"} =
 5890:             $responsetype_per_response{$line};
 5891:     }
 5892:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5893:         my $line = $masterseq_id_responsenum{$resid};
 5894:         $env{"form.scantron.residpart.$line"} = $resid;
 5895:     }
 5896: }
 5897: 
 5898: 
 5899: sub restore_bubble_lines {
 5900:     my $line = 0;
 5901:     %bubble_lines_per_response = ();
 5902:     %masterseq_id_responsenum = ();
 5903:     while ($env{"form.scantron.bubblelines.$line"}) {
 5904: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5905: 	$bubble_lines_per_response{$line} = $value;
 5906: 	$first_bubble_line{$line}  =
 5907: 	    $env{"form.scantron.first_bubble_line.$line"};
 5908:         $subdivided_bubble_lines{$line} =
 5909:             $env{"form.scantron.sub_bubblelines.$line"};
 5910:         $responsetype_per_response{$line} =
 5911:             $env{"form.scantron.responsetype.$line"};
 5912:         my $id = $env{"form.scantron.residpart.$line"};
 5913:         $masterseq_id_responsenum{$id} = $line;
 5914: 	$line++;
 5915:     }
 5916: }
 5917: 
 5918: =pod 
 5919: 
 5920: =item scantron_filenames
 5921: 
 5922:    Returns a list of the scantron files in the current course 
 5923: 
 5924: =cut
 5925: 
 5926: sub scantron_filenames {
 5927:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5929:     my $getpropath = 1;
 5930:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5931:                                                         $cname,$getpropath);
 5932:     my @possiblenames;
 5933:     if (ref($dirlist) eq 'ARRAY') {
 5934:         foreach my $filename (sort(@{$dirlist})) {
 5935: 	    ($filename)=split(/&/,$filename);
 5936: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5937: 	    $filename=~s/^scantron_orig_//;
 5938: 	    push(@possiblenames,$filename);
 5939:         }
 5940:     }
 5941:     return @possiblenames;
 5942: }
 5943: 
 5944: =pod 
 5945: 
 5946: =item scantron_uploads
 5947: 
 5948:    Returns  html drop-down list of scantron files in current course.
 5949: 
 5950:  Arguments:
 5951:    $file2grade - filename to set as selected in the dropdown
 5952: 
 5953: =cut
 5954: 
 5955: sub scantron_uploads {
 5956:     my ($file2grade) = @_;
 5957:     my $result=	'<select name="scantron_selectfile">';
 5958:     $result.="<option></option>";
 5959:     foreach my $filename (sort(&scantron_filenames())) {
 5960: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5961:     }
 5962:     $result.="</select>";
 5963:     return $result;
 5964: }
 5965: 
 5966: =pod 
 5967: 
 5968: =item scantron_scantab
 5969: 
 5970:   Returns html drop down of the scantron formats in the scantronformat.tab
 5971:   file.
 5972: 
 5973: =cut
 5974: 
 5975: sub scantron_scantab {
 5976:     my $result='<select name="scantron_format">'."\n";
 5977:     $result.='<option></option>'."\n";
 5978:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5979:     if (@lines > 0) {
 5980:         foreach my $line (@lines) {
 5981:             next if (($line =~ /^\#/) || ($line eq ''));
 5982: 	    my ($name,$descrip)=split(/:/,$line);
 5983: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5984:         }
 5985:     }
 5986:     $result.='</select>'."\n";
 5987:     return $result;
 5988: }
 5989: 
 5990: =pod 
 5991: 
 5992: =item scantron_CODElist
 5993: 
 5994:   Returns html drop down of the saved CODE lists from current course,
 5995:   generated from earlier printings.
 5996: 
 5997: =cut
 5998: 
 5999: sub scantron_CODElist {
 6000:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6001:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6002:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6003:     my $namechoice='<option></option>';
 6004:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6005: 	if ($name =~ /^error: 2 /) { next; }
 6006: 	if ($name =~ /^type\0/) { next; }
 6007: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6008:     }
 6009:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6010:     return $namechoice;
 6011: }
 6012: 
 6013: =pod 
 6014: 
 6015: =item scantron_CODEunique
 6016: 
 6017:   Returns the html for "Each CODE to be used once" radio.
 6018: 
 6019: =cut
 6020: 
 6021: sub scantron_CODEunique {
 6022:     my $result='<span class="LC_nobreak">
 6023:                  <label><input type="radio" name="scantron_CODEunique"
 6024:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6025:                 </span>
 6026:                 <span class="LC_nobreak">
 6027:                  <label><input type="radio" name="scantron_CODEunique"
 6028:                         value="no" />'.&mt('No').' </label>
 6029:                 </span>';
 6030:     return $result;
 6031: }
 6032: 
 6033: =pod 
 6034: 
 6035: =item scantron_selectphase
 6036: 
 6037:   Generates the initial screen to start the bubblesheet process.
 6038:   Allows for - starting a grading run.
 6039:              - downloading existing scan data (original, corrected
 6040:                                                 or skipped info)
 6041: 
 6042:              - uploading new scan data
 6043: 
 6044:  Arguments:
 6045:   $r          - The Apache request object
 6046:   $file2grade - name of the file that contain the scanned data to score
 6047: 
 6048: =cut
 6049: 
 6050: sub scantron_selectphase {
 6051:     my ($r,$file2grade,$symb) = @_;
 6052:     if (!$symb) {return '';}
 6053:     my $map_error;
 6054:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6055:     if ($map_error) {
 6056:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6057:         return;
 6058:     }
 6059:     my $default_form_data=&defaultFormData($symb);
 6060:     my $file_selector=&scantron_uploads($file2grade);
 6061:     my $format_selector=&scantron_scantab();
 6062:     my $CODE_selector=&scantron_CODElist();
 6063:     my $CODE_unique=&scantron_CODEunique();
 6064:     my $result;
 6065: 
 6066:     $ssi_error = 0;
 6067: 
 6068:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6069: 
 6070: 	# Chunk of form to prompt for a scantron file upload.
 6071: 
 6072:         $r->print('
 6073:     <br />');
 6074:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6075:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6076:     my $csec= $env{'request.course.sec'};
 6077:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6078:     &js_escape(\$alertmsg);
 6079:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6080:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6081:     function checkUpload(formname) {
 6082: 	if (formname.upfile.value == "") {
 6083: 	    alert("'.$alertmsg.'");
 6084: 	    return false;
 6085: 	}
 6086: 	formname.submit();
 6087:     }'."\n".$formatjs));
 6088:     $r->print('
 6089:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6090:                 '.$default_form_data.'
 6091:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6092:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6093:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6094:                 <input name="command" value="scantronupload_save" type="hidden" />
 6095:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6096:               '.&Apache::loncommon::start_data_table_header_row().'
 6097:                 <th>
 6098:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6099:                 </th>
 6100:               '.&Apache::loncommon::end_data_table_header_row().'
 6101:               '.&Apache::loncommon::start_data_table_row().'
 6102:             <td>
 6103:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6104:     if ($formatoptions) {
 6105:         $r->print('</td>
 6106:                  '.&Apache::loncommon::end_data_table_row().'
 6107:                  '.&Apache::loncommon::start_data_table_row().'
 6108:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6109:                  </td>
 6110:                  '.&Apache::loncommon::end_data_table_row().'
 6111:                  '.&Apache::loncommon::start_data_table_row().'
 6112:                  <td>'
 6113:         );
 6114:     } else {
 6115:         $r->print(' <br />');
 6116:     }
 6117:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6118:               </td>
 6119:              '.&Apache::loncommon::end_data_table_row().'
 6120:              '.&Apache::loncommon::end_data_table().'
 6121:              </form>'
 6122:     );
 6123: 
 6124:     }
 6125: 
 6126:     # Chunk of form to prompt for a file to grade and how:
 6127: 
 6128:     $result.= '
 6129:     <br />
 6130:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6131:     <input type="hidden" name="command" value="scantron_warning" />
 6132:     '.$default_form_data.'
 6133:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6134:        '.&Apache::loncommon::start_data_table_header_row().'
 6135:             <th colspan="2">
 6136:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6137:             </th>
 6138:        '.&Apache::loncommon::end_data_table_header_row().'
 6139:        '.&Apache::loncommon::start_data_table_row().'
 6140:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6141:        '.&Apache::loncommon::end_data_table_row().'
 6142:        '.&Apache::loncommon::start_data_table_row().'
 6143:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6144:        '.&Apache::loncommon::end_data_table_row().'
 6145:        '.&Apache::loncommon::start_data_table_row().'
 6146:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6147:        '.&Apache::loncommon::end_data_table_row().'
 6148:        '.&Apache::loncommon::start_data_table_row().'
 6149:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6150:        '.&Apache::loncommon::end_data_table_row().'
 6151:        '.&Apache::loncommon::start_data_table_row().'
 6152:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6153:        '.&Apache::loncommon::end_data_table_row().'
 6154:        '.&Apache::loncommon::start_data_table_row().'
 6155: 	    <td> '.&mt('Options:').' </td>
 6156:             <td>
 6157: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6158:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6159:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6160: 	    </td>
 6161:        '.&Apache::loncommon::end_data_table_row().'
 6162:        '.&Apache::loncommon::start_data_table_row().'
 6163:             <td colspan="2">
 6164:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6165:             </td>
 6166:        '.&Apache::loncommon::end_data_table_row().'
 6167:     '.&Apache::loncommon::end_data_table().'
 6168:     </form>
 6169: ';
 6170:    
 6171:     $r->print($result);
 6172: 
 6173:     # Chunk of the form that prompts to view a scoring office file,
 6174:     # corrected file, skipped records in a file.
 6175: 
 6176:     $r->print('
 6177:    <br />
 6178:    <form action="/adm/grades" name="scantron_download">
 6179:      '.$default_form_data.'
 6180:      <input type="hidden" name="command" value="scantron_download" />
 6181:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6182:        '.&Apache::loncommon::start_data_table_header_row().'
 6183:               <th>
 6184:                 &nbsp;'.&mt('Download a scoring office file').'
 6185:               </th>
 6186:        '.&Apache::loncommon::end_data_table_header_row().'
 6187:        '.&Apache::loncommon::start_data_table_row().'
 6188:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6189:                 <br />
 6190:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6191:        '.&Apache::loncommon::end_data_table_row().'
 6192:      '.&Apache::loncommon::end_data_table().'
 6193:    </form>
 6194:    <br />
 6195: ');
 6196: 
 6197:     &Apache::lonpickcode::code_list($r,2);
 6198: 
 6199:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6200:              $default_form_data."\n".
 6201:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6202:              &Apache::loncommon::start_data_table_header_row()."\n".
 6203:              '<th colspan="2">
 6204:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6205:              '</th>'."\n".
 6206:               &Apache::loncommon::end_data_table_header_row()."\n".
 6207:               &Apache::loncommon::start_data_table_row()."\n".
 6208:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6209:               '<td> '.$sequence_selector.' </td>'.
 6210:               &Apache::loncommon::end_data_table_row()."\n".
 6211:               &Apache::loncommon::start_data_table_row()."\n".
 6212:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6213:               '<td> '.$file_selector.' </td>'."\n".
 6214:               &Apache::loncommon::end_data_table_row()."\n".
 6215:               &Apache::loncommon::start_data_table_row()."\n".
 6216:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6217:               '<td> '.$format_selector.' </td>'."\n".
 6218:               &Apache::loncommon::end_data_table_row()."\n".
 6219:               &Apache::loncommon::start_data_table_row()."\n".
 6220:               '<td> '.&mt('Options').' </td>'."\n".
 6221:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6222:               &Apache::loncommon::end_data_table_row()."\n".
 6223:               &Apache::loncommon::start_data_table_row()."\n".
 6224:               '<td colspan="2">'."\n".
 6225:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6226:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6227:               '</td>'."\n".
 6228:               &Apache::loncommon::end_data_table_row()."\n".
 6229:               &Apache::loncommon::end_data_table()."\n".
 6230:               '</form><br />');
 6231:     return;
 6232: }
 6233: 
 6234: =pod 
 6235: 
 6236: =item username_to_idmap
 6237: 
 6238:     creates a hash keyed by student/employee ID with values of the corresponding
 6239:     student username:domain. If a single ID occurs for more than one student,
 6240:     the status of the student is checked, and if Active, the value in the hash
 6241:     will be set to the Active student.
 6242: 
 6243:   Arguments:
 6244: 
 6245:     $classlist - reference to the class list hash. This is a hash
 6246:                  keyed by student name:domain  whose elements are references
 6247:                  to arrays containing various chunks of information
 6248:                  about the student. (See loncoursedata for more info).
 6249: 
 6250:   Returns
 6251:     %idmap - the constructed hash
 6252: 
 6253: =cut
 6254: 
 6255: sub username_to_idmap {
 6256:     my ($classlist)= @_;
 6257:     my %idmap;
 6258:     foreach my $student (keys(%$classlist)) {
 6259:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6260:         unless ($id eq '') {
 6261:             if (!exists($idmap{$id})) {
 6262:                 $idmap{$id} = $student;
 6263:             } else {
 6264:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6265:                 if ($status eq 'Active') {
 6266:                     $idmap{$id} = $student;
 6267:                 }
 6268:             }
 6269:         }
 6270:     }
 6271:     return %idmap;
 6272: }
 6273: 
 6274: =pod
 6275: 
 6276: =item scantron_fixup_scanline
 6277: 
 6278:    Process a requested correction to a scanline.
 6279: 
 6280:   Arguments:
 6281:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6282:     $scan_data         - hash of correction information 
 6283:                           (see &scantron_getfile())
 6284:     $line              - existing scanline
 6285:     $whichline         - line number of the passed in scanline
 6286:     $field             - type of change to process 
 6287:                          (either 
 6288:                           'ID'     -> correct the student/employee ID
 6289:                           'CODE'   -> correct the CODE
 6290:                           'answer' -> fixup the submitted answers)
 6291:     
 6292:    $args               - hash of additional info,
 6293:                           - 'ID' 
 6294:                                'newid' -> studentID to use in replacement
 6295:                                           of existing one
 6296:                           - 'CODE' 
 6297:                                'CODE_ignore_dup' - set to true if duplicates
 6298:                                                    should be ignored.
 6299: 	                       'CODE' - is new code or 'use_unfound'
 6300:                                         if the existing unfound code should
 6301:                                         be used as is
 6302:                           - 'answer'
 6303:                                'response' - new answer or 'none' if blank
 6304:                                'question' - the bubble line to change
 6305:                                'questionnum' - the question identifier,
 6306:                                                may include subquestion. 
 6307: 
 6308:   Returns:
 6309:     $line - the modified scanline
 6310: 
 6311:   Side effects: 
 6312:     $scan_data - may be updated
 6313: 
 6314: =cut
 6315: 
 6316: 
 6317: sub scantron_fixup_scanline {
 6318:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6319:     if ($field eq 'ID') {
 6320: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6321: 	    return ($line,1,'New value too large');
 6322: 	}
 6323: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6324: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6325: 				     $args->{'newid'});
 6326: 	}
 6327: 	substr($line,$$scantron_config{'IDstart'}-1,
 6328: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6329: 	if ($args->{'newid'}=~/^\s*$/) {
 6330: 	    &scan_data($scan_data,"$whichline.user",
 6331: 		       $args->{'username'}.':'.$args->{'domain'});
 6332: 	}
 6333:     } elsif ($field eq 'CODE') {
 6334: 	if ($args->{'CODE_ignore_dup'}) {
 6335: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6336: 	}
 6337: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6338: 	if ($args->{'CODE'} ne 'use_unfound') {
 6339: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6340: 		return ($line,1,'New CODE value too large');
 6341: 	    }
 6342: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6343: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6344: 	    }
 6345: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6346: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6347: 	}
 6348:     } elsif ($field eq 'answer') {
 6349: 	my $length=$scantron_config->{'Qlength'};
 6350: 	my $off=$scantron_config->{'Qoff'};
 6351: 	my $on=$scantron_config->{'Qon'};
 6352: 	my $answer=${off}x$length;
 6353: 	if ($args->{'response'} eq 'none') {
 6354: 	    &scan_data($scan_data,
 6355: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6356: 	} else {
 6357: 	    if ($on eq 'letter') {
 6358: 		my @alphabet=('A'..'Z');
 6359: 		$answer=$alphabet[$args->{'response'}];
 6360: 	    } elsif ($on eq 'number') {
 6361: 		$answer=$args->{'response'}+1;
 6362: 		if ($answer == 10) { $answer = '0'; }
 6363: 	    } else {
 6364: 		substr($answer,$args->{'response'},1)=$on;
 6365: 	    }
 6366: 	    &scan_data($scan_data,
 6367: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6368: 	}
 6369: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6370: 	substr($line,$where-1,$length)=$answer;
 6371:     }
 6372:     return $line;
 6373: }
 6374: 
 6375: =pod
 6376: 
 6377: =item scan_data
 6378: 
 6379:     Edit or look up  an item in the scan_data hash.
 6380: 
 6381:   Arguments:
 6382:     $scan_data  - The hash (see scantron_getfile)
 6383:     $key        - shorthand of the key to edit (actual key is
 6384:                   scantronfilename_key).
 6385:     $data        - New value of the hash entry.
 6386:     $delete      - If true, the entry is removed from the hash.
 6387: 
 6388:   Returns:
 6389:     The new value of the hash table field (undefined if deleted).
 6390: 
 6391: =cut
 6392: 
 6393: 
 6394: sub scan_data {
 6395:     my ($scan_data,$key,$value,$delete)=@_;
 6396:     my $filename=$env{'form.scantron_selectfile'};
 6397:     if (defined($value)) {
 6398: 	$scan_data->{$filename.'_'.$key} = $value;
 6399:     }
 6400:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6401:     return $scan_data->{$filename.'_'.$key};
 6402: }
 6403: 
 6404: # ----- These first few routines are general use routines.----
 6405: 
 6406: # Return the number of occurences of a pattern in a string.
 6407: 
 6408: sub occurence_count {
 6409:     my ($string, $pattern) = @_;
 6410: 
 6411:     my @matches = ($string =~ /$pattern/g);
 6412: 
 6413:     return scalar(@matches);
 6414: }
 6415: 
 6416: 
 6417: # Take a string known to have digits and convert all the
 6418: # digits into letters in the range J,A..I.
 6419: 
 6420: sub digits_to_letters {
 6421:     my ($input) = @_;
 6422: 
 6423:     my @alphabet = ('J', 'A'..'I');
 6424: 
 6425:     my @input    = split(//, $input);
 6426:     my $output ='';
 6427:     for (my $i = 0; $i < scalar(@input); $i++) {
 6428: 	if ($input[$i] =~ /\d/) {
 6429: 	    $output .= $alphabet[$input[$i]];
 6430: 	} else {
 6431: 	    $output .= $input[$i];
 6432: 	}
 6433:     }
 6434:     return $output;
 6435: }
 6436: 
 6437: =pod 
 6438: 
 6439: =item scantron_parse_scanline
 6440: 
 6441:   Decodes a scanline from the selected bubblesheet file
 6442: 
 6443:  Arguments:
 6444:     line             - The text of the bubblesheet file line to process
 6445:     whichline        - Line number
 6446:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6447:     scan_data        - Hash of extra information about the scanline
 6448:                        (see scantron_getfile for more information)
 6449:     just_header      - True if should not process question answers but only
 6450:                        the stuff to the left of the answers.
 6451:     randomorder      - True if randomorder in use
 6452:     randompick       - True if randompick in use
 6453:     sequence         - Exam folder URL
 6454:     master_seq       - Ref to array containing symbs in exam folder
 6455:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6456:                        (corresponding values are resource objects)
 6457:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6458:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6459:                        are refs to an array of resource objects, ordered
 6460:                        according to order used for CODE, when randomorder
 6461:                        and or randompick are in use.
 6462:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6463:                        for current line to question number used for same question
 6464:                         in "Master Sequence" (as seen by Course Coordinator).
 6465:     startline        - Ref to hash where key is question number (0 is first)
 6466:                        and value is number of first bubble line for current 
 6467:                        student or code-based randompick and/or randomorder.
 6468:     totalref         - Ref of scalar used to score total number of bubble
 6469:                        lines needed for responses in a scan line (used when
 6470:                        randompick in use. 
 6471:     
 6472:  Returns:
 6473:    Hash containing the result of parsing the scanline
 6474: 
 6475:    Keys are all proceeded by the string 'scantron.'
 6476: 
 6477:        CODE    - the CODE in use for this scanline
 6478:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6479:                  by the operator
 6480:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6481:                             CODEs were selected, but the usage has been
 6482:                             forced by the operator
 6483:        ID  - student/employee ID
 6484:        PaperID - if used, the ID number printed on the sheet when the 
 6485:                  paper was scanned
 6486:        FirstName - first name from the sheet
 6487:        LastName  - last name from the sheet
 6488: 
 6489:      if just_header was not true these key may also exist
 6490: 
 6491:        missingerror - a list of bubble ranges that are considered to be answers
 6492:                       to a single question that don't have any bubbles filled in.
 6493:                       Of the form questionnumber:firstbubblenumber:count.
 6494:        doubleerror  - a list of bubble ranges that are considered to be answers
 6495:                       to a single question that have more than one bubble filled in.
 6496:                       Of the form questionnumber::firstbubblenumber:count
 6497:    
 6498:                 In the above, count is the number of bubble responses in the
 6499:                 input line needed to represent the possible answers to the question.
 6500:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6501:                 per line would have count = 2.
 6502: 
 6503:        maxquest     - the number of the last bubble line that was parsed
 6504: 
 6505:        (<number> starts at 1)
 6506:        <number>.answer - zero or more letters representing the selected
 6507:                          letters from the scanline for the bubble line 
 6508:                          <number>.
 6509:                          if blank there was either no bubble or there where
 6510:                          multiple bubbles, (consult the keys missingerror and
 6511:                          doubleerror if this is an error condition)
 6512: 
 6513: =cut
 6514: 
 6515: sub scantron_parse_scanline {
 6516:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6517:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6518:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6519: 
 6520:     my %record;
 6521:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6522:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6523: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6524: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6525: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6526: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6527: 	    $record{'scantron.CODE'}=substr($data,
 6528: 					    $$scantron_config{'CODEstart'}-1,
 6529: 					    $$scantron_config{'CODElength'});
 6530: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6531: 		$record{'scantron.useCODE'}=1;
 6532: 	    }
 6533: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6534: 		$record{'scantron.CODE_ignore_dup'}=1;
 6535: 	    }
 6536: 	} else {
 6537: 	    #FIXME interpret first N questions
 6538: 	}
 6539:     }
 6540:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6541: 				  $$scantron_config{'IDlength'});
 6542:     $record{'scantron.PaperID'}=
 6543: 	substr($data,$$scantron_config{'PaperID'}-1,
 6544: 	       $$scantron_config{'PaperIDlength'});
 6545:     $record{'scantron.FirstName'}=
 6546: 	substr($data,$$scantron_config{'FirstName'}-1,
 6547: 	       $$scantron_config{'FirstNamelength'});
 6548:     $record{'scantron.LastName'}=
 6549: 	substr($data,$$scantron_config{'LastName'}-1,
 6550: 	       $$scantron_config{'LastNamelength'});
 6551:     if ($just_header) { return \%record; }
 6552: 
 6553:     my @alphabet=('A'..'Z');
 6554:     my $questnum=0;
 6555:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6556: 
 6557:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6558:     if ($randompick || $randomorder) {
 6559:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6560:                                          $master_seq,$symb_to_resource,
 6561:                                          $partids_by_symb,$orderedforcode,
 6562:                                          $respnumlookup,$startline);
 6563:         if ($total) {
 6564:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6565:         }
 6566:         if (ref($totalref)) {
 6567:             $$totalref = $total;
 6568:         }
 6569:     }
 6570:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6571:     chomp($questions);		# Get rid of any trailing \n.
 6572:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6573:     while (length($questions)) {
 6574:         my $answers_needed;
 6575:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6576:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6577:         } else {
 6578: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6579:         }
 6580:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6581:                              || 1;
 6582:         $questnum++;
 6583:         my $quest_id = $questnum;
 6584:         my $currentquest = substr($questions,0,$answer_length);
 6585:         $questions       = substr($questions,$answer_length);
 6586:         if (length($currentquest) < $answer_length) { next; }
 6587: 
 6588:         my $subdivided;
 6589:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6590:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6591:         } else {
 6592:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6593:         }
 6594:         if ($subdivided =~ /,/) {
 6595:             my $subquestnum = 1;
 6596:             my $subquestions = $currentquest;
 6597:             my @subanswers_needed = split(/,/,$subdivided);
 6598:             foreach my $subans (@subanswers_needed) {
 6599:                 my $subans_length =
 6600:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6601:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6602:                 $subquestions   = substr($subquestions,$subans_length);
 6603:                 $quest_id = "$questnum.$subquestnum";
 6604:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6605:                     ($$scantron_config{'Qon'} eq 'number')) {
 6606:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6607:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6608:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6609:                         $randomorder,$randompick,$respnumlookup);
 6610:                 } else {
 6611:                     $ansnum = &scantron_validator_positional($ansnum,
 6612:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6613:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6614:                         $randomorder,$randompick,$respnumlookup);
 6615:                 }
 6616:                 $subquestnum ++;
 6617:             }
 6618:         } else {
 6619:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6620:                 ($$scantron_config{'Qon'} eq 'number')) {
 6621:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6622:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6623:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6624:                     $randomorder,$randompick,$respnumlookup);
 6625:             } else {
 6626:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6627:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6628:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6629:                     $randomorder,$randompick,$respnumlookup);
 6630:             }
 6631:         }
 6632:     }
 6633:     $record{'scantron.maxquest'}=$questnum;
 6634:     return \%record;
 6635: }
 6636: 
 6637: sub get_master_seq {
 6638:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6639:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6640:                    (ref($symb_to_resource) eq 'HASH'));
 6641:     my $resource_error;
 6642:     foreach my $resource (@{$resources}) {
 6643:         my $ressymb;
 6644:         if (ref($resource)) {
 6645:             $ressymb = $resource->symb();
 6646:             push(@{$master_seq},$ressymb);
 6647:             $symb_to_resource->{$ressymb} = $resource;
 6648:         } else {
 6649:             $resource_error = 1;
 6650:             last;
 6651:         }
 6652:     }
 6653:     return $resource_error;
 6654: }
 6655: 
 6656: sub get_respnum_lookups {
 6657:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6658:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6659:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6660:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6661:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6662:                    (ref($startline) eq 'HASH'));
 6663:     my ($user,$scancode);
 6664:     if ((exists($record->{'scantron.CODE'})) &&
 6665:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6666:         $scancode = $record->{'scantron.CODE'};
 6667:     } else {
 6668:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6669:     }
 6670:     my @mapresources =
 6671:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6672:                      $orderedforcode);
 6673:     my $total = 0;
 6674:     my $count = 0;
 6675:     foreach my $resource (@mapresources) {
 6676:         my $id = $resource->id();
 6677:         my $symb = $resource->symb();
 6678:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6679:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6680:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6681:                 if ($respnum ne '') {
 6682:                     $respnumlookup->{$count} = $respnum;
 6683:                     $startline->{$count} = $total;
 6684:                     $total += $bubble_lines_per_response{$respnum};
 6685:                     $count ++;
 6686:                 }
 6687:             }
 6688:         }
 6689:     }
 6690:     return $total;
 6691: }
 6692: 
 6693: sub scantron_validator_lettnum {
 6694:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6695:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6696:         $randompick,$respnumlookup) = @_;
 6697: 
 6698:     # Qon 'letter' implies for each slot in currquest we have:
 6699:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6700:     #    about anything else (esp. a value of Qoff) for missing
 6701:     #    bubbles.
 6702:     #
 6703:     # Qon 'number' implies each slot gives a digit that indexes the
 6704:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6705:     #    and * or ? for double bubbles on a single line.
 6706:     #
 6707: 
 6708:     my $matchon;
 6709:     if ($$scantron_config{'Qon'} eq 'letter') {
 6710:         $matchon = '[A-Z]';
 6711:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6712:         $matchon = '\d';
 6713:     }
 6714:     my $occurrences = 0;
 6715:     my $responsenum = $questnum-1;
 6716:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6717:        $responsenum = $respnumlookup->{$questnum-1} 
 6718:     }
 6719:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6720:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6721:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6722:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6723:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6724:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6725:         my @singlelines = split('',$currquest);
 6726:         foreach my $entry (@singlelines) {
 6727:             $occurrences = &occurence_count($entry,$matchon);
 6728:             if ($occurrences > 1) {
 6729:                 last;
 6730:             }
 6731:         }
 6732:     } else {
 6733:         $occurrences = &occurence_count($currquest,$matchon); 
 6734:     }
 6735:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6736:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6737:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6738:             my $bubble = substr($currquest,$ans,1);
 6739:             if ($bubble =~ /$matchon/ ) {
 6740:                 if ($$scantron_config{'Qon'} eq 'number') {
 6741:                     if ($bubble == 0) {
 6742:                         $bubble = 10; 
 6743:                     }
 6744:                     $record->{"scantron.$ansnum.answer"} = 
 6745:                         $alphabet->[$bubble-1];
 6746:                 } else {
 6747:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6748:                 }
 6749:             } else {
 6750:                 $record->{"scantron.$ansnum.answer"}='';
 6751:             }
 6752:             $ansnum++;
 6753:         }
 6754:     } elsif (!defined($currquest)
 6755:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6756:             || (&occurence_count($currquest,$matchon) == 0)) {
 6757:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6758:             $record->{"scantron.$ansnum.answer"}='';
 6759:             $ansnum++;
 6760:         }
 6761:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6762:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6763:         }
 6764:     } else {
 6765:         if ($$scantron_config{'Qon'} eq 'number') {
 6766:             $currquest = &digits_to_letters($currquest);            
 6767:         }
 6768:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6769:             my $bubble = substr($currquest,$ans,1);
 6770:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6771:             $ansnum++;
 6772:         }
 6773:     }
 6774:     return $ansnum;
 6775: }
 6776: 
 6777: sub scantron_validator_positional {
 6778:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6779:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6780:         $randomorder,$randompick,$respnumlookup) = @_;
 6781: 
 6782:     # Otherwise there's a positional notation;
 6783:     # each bubble line requires Qlength items, and there are filled in
 6784:     # bubbles for each case where there 'Qon' characters.
 6785:     #
 6786: 
 6787:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6788: 
 6789:     # If the split only gives us one element.. the full length of the
 6790:     # answer string, no bubbles are filled in:
 6791: 
 6792:     if ($answers_needed eq '') {
 6793:         return;
 6794:     }
 6795: 
 6796:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6797:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6798:             $record->{"scantron.$ansnum.answer"}='';
 6799:             $ansnum++;
 6800:         }
 6801:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6802:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6803:         }
 6804:     } elsif (scalar(@array) == 2) {
 6805:         my $location = length($array[0]);
 6806:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6807:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6808:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6809:             if ($ans eq $line_num) {
 6810:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6811:             } else {
 6812:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6813:             }
 6814:             $ansnum++;
 6815:          }
 6816:     } else {
 6817:         #  If there's more than one instance of a bubble character
 6818:         #  That's a double bubble; with positional notation we can
 6819:         #  record all the bubbles filled in as well as the
 6820:         #  fact this response consists of multiple bubbles.
 6821:         #
 6822:         my $responsenum = $questnum-1;
 6823:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6824:             $responsenum = $respnumlookup->{$questnum-1}
 6825:         }
 6826:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6827:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6828:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6829:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6830:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6831:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6832:             my $doubleerror = 0;
 6833:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6834:                    (!$doubleerror)) {
 6835:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6836:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6837:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6838:                if (length(@currarray) > 2) {
 6839:                    $doubleerror = 1;
 6840:                } 
 6841:             }
 6842:             if ($doubleerror) {
 6843:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6844:             }
 6845:         } else {
 6846:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6847:         }
 6848:         my $item = $ansnum;
 6849:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6850:             $record->{"scantron.$item.answer"} = '';
 6851:             $item ++;
 6852:         }
 6853: 
 6854:         my @ans=@array;
 6855:         my $i=0;
 6856:         my $increment = 0;
 6857:         while ($#ans) {
 6858:             $i+=length($ans[0]) + $increment;
 6859:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6860:             my $bubble = $i%$$scantron_config{'Qlength'};
 6861:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6862:             shift(@ans);
 6863:             $increment = 1;
 6864:         }
 6865:         $ansnum += $answers_needed;
 6866:     }
 6867:     return $ansnum;
 6868: }
 6869: 
 6870: =pod
 6871: 
 6872: =item scantron_add_delay
 6873: 
 6874:    Adds an error message that occurred during the grading phase to a
 6875:    queue of messages to be shown after grading pass is complete
 6876: 
 6877:  Arguments:
 6878:    $delayqueue  - arrary ref of hash ref of error messages
 6879:    $scanline    - the scanline that caused the error
 6880:    $errormesage - the error message
 6881:    $errorcode   - a numeric code for the error
 6882: 
 6883:  Side Effects:
 6884:    updates the $delayqueue to have a new hash ref of the error
 6885: 
 6886: =cut
 6887: 
 6888: sub scantron_add_delay {
 6889:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6890:     push(@$delayqueue,
 6891: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6892: 	  'ecode' => $errorcode }
 6893: 	 );
 6894: }
 6895: 
 6896: =pod
 6897: 
 6898: =item scantron_find_student
 6899: 
 6900:    Finds the username for the current scanline
 6901: 
 6902:   Arguments:
 6903:    $scantron_record - hash result from scantron_parse_scanline
 6904:    $scan_data       - hash of correction information 
 6905:                       (see &scantron_getfile() form more information)
 6906:    $idmap           - hash from &username_to_idmap()
 6907:    $line            - number of current scanline
 6908:  
 6909:   Returns:
 6910:    Either 'username:domain' or undef if unknown
 6911: 
 6912: =cut
 6913: 
 6914: sub scantron_find_student {
 6915:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6916:     my $scanID=$$scantron_record{'scantron.ID'};
 6917:     if ($scanID =~ /^\s*$/) {
 6918:  	return &scan_data($scan_data,"$line.user");
 6919:     }
 6920:     foreach my $id (keys(%$idmap)) {
 6921:  	if (lc($id) eq lc($scanID)) {
 6922:  	    return $$idmap{$id};
 6923:  	}
 6924:     }
 6925:     return undef;
 6926: }
 6927: 
 6928: =pod
 6929: 
 6930: =item scantron_filter
 6931: 
 6932:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6933:    hidden resources was selected
 6934: 
 6935: =cut
 6936: 
 6937: sub scantron_filter {
 6938:     my ($curres)=@_;
 6939: 
 6940:     if (ref($curres) && $curres->is_problem()) {
 6941: 	# if the user has asked to not have either hidden
 6942: 	# or 'randomout' controlled resources to be graded
 6943: 	# don't include them
 6944: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6945: 	    && $curres->randomout) {
 6946: 	    return 0;
 6947: 	}
 6948: 	return 1;
 6949:     }
 6950:     return 0;
 6951: }
 6952: 
 6953: =pod
 6954: 
 6955: =item scantron_process_corrections
 6956: 
 6957:    Gets correction information out of submitted form data and corrects
 6958:    the scanline
 6959: 
 6960: =cut
 6961: 
 6962: sub scantron_process_corrections {
 6963:     my ($r) = @_;
 6964:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6965:     my ($scanlines,$scan_data)=&scantron_getfile();
 6966:     my $classlist=&Apache::loncoursedata::get_classlist();
 6967:     my $which=$env{'form.scantron_line'};
 6968:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6969:     my ($skip,$err,$errmsg);
 6970:     if ($env{'form.scantron_skip_record'}) {
 6971: 	$skip=1;
 6972:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6973: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6974: 	    $env{'form.scantron_domain'};
 6975: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6976: 	($line,$err,$errmsg)=
 6977: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6978: 				     'ID',{'newid'=>$newid,
 6979: 				    'username'=>$env{'form.scantron_username'},
 6980: 				    'domain'=>$env{'form.scantron_domain'}});
 6981:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6982: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6983: 	my $newCODE;
 6984: 	my %args;
 6985: 	if      ($resolution eq 'use_unfound') {
 6986: 	    $newCODE='use_unfound';
 6987: 	} elsif ($resolution eq 'use_found') {
 6988: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6989: 	} elsif ($resolution eq 'use_typed') {
 6990: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6991: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6992: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6993: 	}
 6994: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6995: 	    $args{'CODE_ignore_dup'}=1;
 6996: 	}
 6997: 	$args{'CODE'}=$newCODE;
 6998: 	($line,$err,$errmsg)=
 6999: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7000: 				     'CODE',\%args);
 7001:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7002: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7003: 	    ($line,$err,$errmsg)=
 7004: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7005: 					 $which,'answer',
 7006: 					 { 'question'=>$question,
 7007: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7008:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7009: 	    if ($err) { last; }
 7010: 	}
 7011:     }
 7012:     if ($err) {
 7013:         $r->print(
 7014:             '<p class="LC_error">'
 7015:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7016:                 $errmsg)
 7017:            .'</p>');
 7018:     } else {
 7019: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7020: 	&scantron_putfile($scanlines,$scan_data);
 7021:     }
 7022: }
 7023: 
 7024: =pod
 7025: 
 7026: =item reset_skipping_status
 7027: 
 7028:    Forgets the current set of remember skipped scanlines (and thus
 7029:    reverts back to considering all lines in the
 7030:    scantron_skipped_<filename> file)
 7031: 
 7032: =cut
 7033: 
 7034: sub reset_skipping_status {
 7035:     my ($scanlines,$scan_data)=&scantron_getfile();
 7036:     &scan_data($scan_data,'remember_skipping',undef,1);
 7037:     &scantron_putfile(undef,$scan_data);
 7038: }
 7039: 
 7040: =pod
 7041: 
 7042: =item start_skipping
 7043: 
 7044:    Marks a scanline to be skipped. 
 7045: 
 7046: =cut
 7047: 
 7048: sub start_skipping {
 7049:     my ($scan_data,$i)=@_;
 7050:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7051:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7052: 	$remembered{$i}=2;
 7053:     } else {
 7054: 	$remembered{$i}=1;
 7055:     }
 7056:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7057: }
 7058: 
 7059: =pod
 7060: 
 7061: =item should_be_skipped
 7062: 
 7063:    Checks whether a scanline should be skipped.
 7064: 
 7065: =cut
 7066: 
 7067: sub should_be_skipped {
 7068:     my ($scanlines,$scan_data,$i)=@_;
 7069:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7070: 	# not redoing old skips
 7071: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7072: 	return 0;
 7073:     }
 7074:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7075: 
 7076:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7077: 	return 0;
 7078:     }
 7079:     return 1;
 7080: }
 7081: 
 7082: =pod
 7083: 
 7084: =item remember_current_skipped
 7085: 
 7086:    Discovers what scanlines are in the scantron_skipped_<filename>
 7087:    file and remembers them into scan_data for later use.
 7088: 
 7089: =cut
 7090: 
 7091: sub remember_current_skipped {
 7092:     my ($scanlines,$scan_data)=&scantron_getfile();
 7093:     my %to_remember;
 7094:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7095: 	if ($scanlines->{'skipped'}[$i]) {
 7096: 	    $to_remember{$i}=1;
 7097: 	}
 7098:     }
 7099: 
 7100:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7101:     &scantron_putfile(undef,$scan_data);
 7102: }
 7103: 
 7104: =pod
 7105: 
 7106: =item check_for_error
 7107: 
 7108:     Checks if there was an error when attempting to remove a specific
 7109:     scantron_.. bubblesheet data file. Prints out an error if
 7110:     something went wrong.
 7111: 
 7112: =cut
 7113: 
 7114: sub check_for_error {
 7115:     my ($r,$result)=@_;
 7116:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7117: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7118:     }
 7119: }
 7120: 
 7121: =pod
 7122: 
 7123: =item scantron_warning_screen
 7124: 
 7125:    Interstitial screen to make sure the operator has selected the
 7126:    correct options before we start the validation phase.
 7127: 
 7128: =cut
 7129: 
 7130: sub scantron_warning_screen {
 7131:     my ($button_text,$symb)=@_;
 7132:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7133:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7134:     my $CODElist;
 7135:     if ($scantron_config{'CODElocation'} &&
 7136: 	$scantron_config{'CODEstart'} &&
 7137: 	$scantron_config{'CODElength'}) {
 7138: 	$CODElist=$env{'form.scantron_CODElist'};
 7139: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7140: 	$CODElist=
 7141: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7142: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7143:     }
 7144:     my $lastbubblepoints;
 7145:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7146:         $lastbubblepoints =
 7147:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7148:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7149:     }
 7150:     return '
 7151: <p>
 7152: <span class="LC_warning">
 7153: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7154: </p>
 7155: <table>
 7156: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7157: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7158: '.$CODElist.$lastbubblepoints.'
 7159: </table>
 7160: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7161: '.&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>
 7162: ';
 7163: }
 7164: 
 7165: =pod
 7166: 
 7167: =item scantron_do_warning
 7168: 
 7169:    Check if the operator has picked something for all required
 7170:    fields. Error out if something is missing.
 7171: 
 7172: =cut
 7173: 
 7174: sub scantron_do_warning {
 7175:     my ($r,$symb)=@_;
 7176:     if (!$symb) {return '';}
 7177:     my $default_form_data=&defaultFormData($symb);
 7178:     $r->print(&scantron_form_start().$default_form_data);
 7179:     if ( $env{'form.selectpage'} eq '' ||
 7180: 	 $env{'form.scantron_selectfile'} eq '' ||
 7181: 	 $env{'form.scantron_format'} eq '' ) {
 7182: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7183: 	if ( $env{'form.selectpage'} eq '') {
 7184: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7185: 	} 
 7186: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7187: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7188: 	}
 7189: 	if ( $env{'form.scantron_format'} eq '') {
 7190: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7191: 	}
 7192:     } else {
 7193: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7194:         my ($checksec,@possibles) = &gradable_sections();
 7195:         my $gradesections;
 7196:         if ($checksec) {
 7197:             my $file=$env{'form.scantron_selectfile'};
 7198:             if (&valid_file($file)) {
 7199:                 my %bysec = &scantron_get_sections();
 7200:                 my $table;
 7201:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7202:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7203:                     $table = &Apache::loncommon::start_data_table()."\n".
 7204:                              &Apache::loncommon::start_data_table_header_row().
 7205:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7206:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7207:                     if ($bysec{'none'}) {
 7208:                         $table .= &Apache::loncommon::start_data_table_row().
 7209:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7210:                                   &Apache::loncommon::end_data_table_row()."\n";
 7211:                     }
 7212:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7213:                         next if ($sec eq 'none');
 7214:                         $table .= &Apache::loncommon::start_data_table_row().
 7215:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7216:                                   &Apache::loncommon::end_data_table_row()."\n";
 7217:                     }
 7218:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7219:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7220:                                       '<p>'.$table.'</p>';
 7221:                     if (@possibles) {
 7222:                         $gradesections .= '<p>'.
 7223:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7224:                                               scalar(@possibles)).'<br />'.
 7225:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7226:                                               '<i>'.$checksec.'</i>').' ';
 7227:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7228:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7229:                         }
 7230:                         $gradesections .= '</p>';
 7231:                     }
 7232:                 }
 7233:             } else {
 7234:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7235:             }
 7236:         }
 7237:         my $bubbledbyhand=&hand_bubble_option();
 7238: 	$r->print('
 7239: '.$warning.$gradesections.$bubbledbyhand.'
 7240: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7241: <input type="hidden" name="command" value="scantron_validate" />
 7242: ');
 7243:     }
 7244:     $r->print("</form><br />");
 7245:     return '';
 7246: }
 7247: 
 7248: =pod
 7249: 
 7250: =item scantron_form_start
 7251: 
 7252:     html hidden input for remembering all selected grading options
 7253: 
 7254: =cut
 7255: 
 7256: sub scantron_form_start {
 7257:     my ($max_bubble)=@_;
 7258:     my $result= <<SCANTRONFORM;
 7259: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7260:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7261:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7262:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7263:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7264:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7265:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7266:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7267:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7268:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7269: SCANTRONFORM
 7270: 
 7271:   my $line = 0;
 7272:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7273:        my $chunk =
 7274: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7275:        $chunk .=
 7276: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7277:        $chunk .= 
 7278:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7279:        $chunk .=
 7280:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7281:        $chunk .=
 7282:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7283:        $result .= $chunk;
 7284:        $line++;
 7285:     }
 7286:     return $result;
 7287: }
 7288: 
 7289: =pod
 7290: 
 7291: =item scantron_validate_file
 7292: 
 7293:     Dispatch routine for doing validation of a bubblesheet data file.
 7294: 
 7295:     Also processes any necessary information resets that need to
 7296:     occur before validation begins (ignore previous corrections,
 7297:     restarting the skipped records processing)
 7298: 
 7299: =cut
 7300: 
 7301: sub scantron_validate_file {
 7302:     my ($r,$symb) = @_;
 7303:     if (!$symb) {return '';}
 7304:     my $default_form_data=&defaultFormData($symb);
 7305:     
 7306:     # do the detection of only doing skipped records first before we delete
 7307:     # them when doing the corrections reset
 7308:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7309: 	&reset_skipping_status();
 7310:     }
 7311:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7312: 	&remember_current_skipped();
 7313: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7314:     }
 7315: 
 7316:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7317: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7318: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7319: 	&check_for_error($r,&scantron_remove_scan_data());
 7320: 	$env{'form.scantron_options_ignore'}='done';
 7321:     }
 7322: 
 7323:     if ($env{'form.scantron_corrections'}) {
 7324: 	&scantron_process_corrections($r);
 7325:     }
 7326: 
 7327:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7328:     my ($checksec,@gradable);
 7329:     if ($env{'request.course.sec'}) {
 7330:         ($checksec,my @possibles) = &gradable_sections();
 7331:         if ($checksec) {
 7332:             if (@possibles) {
 7333:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7334:                 if (@chosensecs) {
 7335:                     foreach my $sec (@chosensecs) {
 7336:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7337:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7338:                                 push(@gradable,$sec);
 7339:                             }
 7340:                         }
 7341:                     }
 7342:                 }
 7343:             }
 7344:             $r->print('<p><table>');
 7345:             if (@gradable) {
 7346:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7347:                 $r->print(
 7348:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7349:             } else {
 7350:                 $r->print(
 7351:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7352:             }
 7353:             $r->print('</table></p>');
 7354:         }
 7355:     }
 7356:     $r->rflush();
 7357: 
 7358:     #get the student pick code ready
 7359:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7360:     my $nav_error;
 7361:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7362:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7363:     if ($nav_error) {
 7364:         $r->print(&navmap_errormsg());
 7365:         return '';
 7366:     }
 7367:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7368:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7369:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7370:     }
 7371:     $r->print($result);
 7372:     
 7373:     my @validate_phases=( 'sequence',
 7374: 			  'ID',
 7375: 			  'CODE',
 7376: 			  'doublebubble',
 7377: 			  'missingbubbles');
 7378:     if (!$env{'form.validatepass'}) {
 7379: 	$env{'form.validatepass'} = 0;
 7380:     }
 7381:     my $currentphase=$env{'form.validatepass'};
 7382:     my %skipbysec=();
 7383: 
 7384:     my $stop=0;
 7385:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7386: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7387: 	$r->rflush();
 7388:      
 7389: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7390: 	{
 7391: 	    no strict 'refs';
 7392:             my @extras=();
 7393:             if ($validate_phases[$currentphase] eq 'ID') {
 7394:                 @extras = (\%skipbysec,$checksec,@gradable);
 7395:             }
 7396: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7397: 	}
 7398:     }
 7399:     if (!$stop) {
 7400: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7401:         my $secinfo;
 7402:         if (keys(%skipbysec) > 0) {
 7403:             my $seclist = '<ul>';
 7404:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7405:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7406:             }
 7407:             $seclist .= '</ul>';
 7408:             $secinfo = '<p class="LC_info">'.
 7409:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7410:                            $seclist).
 7411:                        '</p>';
 7412:         }
 7413: 	$r->print(&mt('Validation process complete.').'<br />'.
 7414:                   $secinfo.$warning.
 7415:                   &mt('Perform verification for each student after storage of submissions?').
 7416:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7417:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7418:                   ('&nbsp;'x3).'<label>'.
 7419:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7420:                   '</label></span><br />'.
 7421:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7422:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7423:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7424:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7425:     } else {
 7426: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7427: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7428:     }
 7429:     if ($stop) {
 7430: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7431: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7432: 	    $r->print(' '.&mt('this error').' <br />');
 7433: 
 7434: 	    $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>');
 7435: 	} else {
 7436:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7437: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7438:             } else {
 7439:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7440:             }
 7441: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7442: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7443: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7444: 	}
 7445:     }
 7446:     $r->print(" </form><br />");
 7447:     return '';
 7448: }
 7449: 
 7450: 
 7451: =pod
 7452: 
 7453: =item scantron_remove_file
 7454: 
 7455:    Removes the requested bubblesheet data file, makes sure that
 7456:    scantron_original_<filename> is never removed
 7457: 
 7458: 
 7459: =cut
 7460: 
 7461: sub scantron_remove_file {
 7462:     my ($which)=@_;
 7463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7465:     my $file='scantron_';
 7466:     if ($which eq 'corrected' || $which eq 'skipped') {
 7467: 	$file.=$which.'_';
 7468:     } else {
 7469: 	return 'refused';
 7470:     }
 7471:     $file.=$env{'form.scantron_selectfile'};
 7472:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7473: }
 7474: 
 7475: 
 7476: =pod
 7477: 
 7478: =item scantron_remove_scan_data
 7479: 
 7480:    Removes all scan_data correction for the requested bubblesheet
 7481:    data file.  (In the case that both the are doing skipped records we need
 7482:    to remember the old skipped lines for the time being so that element
 7483:    persists for a while.)
 7484: 
 7485: =cut
 7486: 
 7487: sub scantron_remove_scan_data {
 7488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7490:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7491:     my @todelete;
 7492:     my $filename=$env{'form.scantron_selectfile'};
 7493:     foreach my $key (@keys) {
 7494: 	if ($key=~/^\Q$filename\E_/) {
 7495: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7496: 		$key=~/remember_skipping/) {
 7497: 		next;
 7498: 	    }
 7499: 	    push(@todelete,$key);
 7500: 	}
 7501:     }
 7502:     my $result;
 7503:     if (@todelete) {
 7504: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7505: 				       \@todelete,$cdom,$cname);
 7506:     } else {
 7507: 	$result = 'ok';
 7508:     }
 7509:     return $result;
 7510: }
 7511: 
 7512: 
 7513: =pod
 7514: 
 7515: =item scantron_getfile
 7516: 
 7517:     Fetches the requested bubblesheet data file (all 3 versions), and
 7518:     the scan_data hash
 7519:   
 7520:   Arguments:
 7521:     None
 7522: 
 7523:   Returns:
 7524:     2 hash references
 7525: 
 7526:      - first one has 
 7527:          orig      -
 7528:          corrected -
 7529:          skipped   -  each of which points to an array ref of the specified
 7530:                       file broken up into individual lines
 7531:          count     - number of scanlines
 7532:  
 7533:      - second is the scan_data hash possible keys are
 7534:        ($number refers to scanline numbered $number and thus the key affects
 7535:         only that scanline
 7536:         $bubline refers to the specific bubble line element and the aspects
 7537:         refers to that specific bubble line element)
 7538: 
 7539:        $number.user - username:domain to use
 7540:        $number.CODE_ignore_dup 
 7541:                     - ignore the duplicate CODE error 
 7542:        $number.useCODE
 7543:                     - use the CODE in the scanline as is
 7544:        $number.no_bubble.$bubline
 7545:                     - it is valid that there is no bubbled in bubble
 7546:                       at $number $bubline
 7547:        remember_skipping
 7548:                     - a frozen hash containing keys of $number and values
 7549:                       of either 
 7550:                         1 - we are on a 'do skipped records pass' and plan
 7551:                             on processing this line
 7552:                         2 - we are on a 'do skipped records pass' and this
 7553:                             scanline has been marked to skip yet again
 7554: 
 7555: =cut
 7556: 
 7557: sub scantron_getfile {
 7558:     #FIXME really would prefer a scantron directory
 7559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7561:     my $lines;
 7562:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7563: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7564:     my %scanlines;
 7565:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7566:     my $temp=$scanlines{'orig'};
 7567:     $scanlines{'count'}=$#$temp;
 7568: 
 7569:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7570: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7571:     if ($lines eq '-1') {
 7572: 	$scanlines{'corrected'}=[];
 7573:     } else {
 7574: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7575:     }
 7576:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7577: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7578:     if ($lines eq '-1') {
 7579: 	$scanlines{'skipped'}=[];
 7580:     } else {
 7581: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7582:     }
 7583:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7584:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7585:     my %scan_data = @tmp;
 7586:     return (\%scanlines,\%scan_data);
 7587: }
 7588: 
 7589: =pod
 7590: 
 7591: =item lonnet_putfile
 7592: 
 7593:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7594: 
 7595:  Arguments:
 7596:    $contents - data to store
 7597:    $filename - filename to store $contents into
 7598: 
 7599:  Returns:
 7600:    result value from &Apache::lonnet::finishuserfileupload
 7601: 
 7602: =cut
 7603: 
 7604: sub lonnet_putfile {
 7605:     my ($contents,$filename)=@_;
 7606:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7607:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7608:     $env{'form.sillywaytopassafilearound'}=$contents;
 7609:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7610: 
 7611: }
 7612: 
 7613: =pod
 7614: 
 7615: =item scantron_putfile
 7616: 
 7617:     Stores the current version of the bubblesheet data files, and the
 7618:     scan_data hash. (Does not modify the original version only the
 7619:     corrected and skipped versions.
 7620: 
 7621:  Arguments:
 7622:     $scanlines - hash ref that looks like the first return value from
 7623:                  &scantron_getfile()
 7624:     $scan_data - hash ref that looks like the second return value from
 7625:                  &scantron_getfile()
 7626: 
 7627: =cut
 7628: 
 7629: sub scantron_putfile {
 7630:     my ($scanlines,$scan_data) = @_;
 7631:     #FIXME really would prefer a scantron directory
 7632:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7633:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7634:     if ($scanlines) {
 7635: 	my $prefix='scantron_';
 7636: # no need to update orig, shouldn't change
 7637: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7638: #		    $env{'form.scantron_selectfile'});
 7639: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7640: 			$prefix.'corrected_'.
 7641: 			$env{'form.scantron_selectfile'});
 7642: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7643: 			$prefix.'skipped_'.
 7644: 			$env{'form.scantron_selectfile'});
 7645:     }
 7646:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7647: }
 7648: 
 7649: =pod
 7650: 
 7651: =item scantron_get_line
 7652: 
 7653:    Returns the correct version of the scanline
 7654: 
 7655:  Arguments:
 7656:     $scanlines - hash ref that looks like the first return value from
 7657:                  &scantron_getfile()
 7658:     $scan_data - hash ref that looks like the second return value from
 7659:                  &scantron_getfile()
 7660:     $i         - number of the requested line (starts at 0)
 7661: 
 7662:  Returns:
 7663:    A scanline, (either the original or the corrected one if it
 7664:    exists), or undef if the requested scanline should be
 7665:    skipped. (Either because it's an skipped scanline, or it's an
 7666:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7667:    pass.
 7668: 
 7669: =cut
 7670: 
 7671: sub scantron_get_line {
 7672:     my ($scanlines,$scan_data,$i)=@_;
 7673:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7674:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7675:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7676:     return $scanlines->{'orig'}[$i]; 
 7677: }
 7678: 
 7679: =pod
 7680: 
 7681: =item scantron_todo_count
 7682: 
 7683:     Counts the number of scanlines that need processing.
 7684: 
 7685:  Arguments:
 7686:     $scanlines - hash ref that looks like the first return value from
 7687:                  &scantron_getfile()
 7688:     $scan_data - hash ref that looks like the second return value from
 7689:                  &scantron_getfile()
 7690: 
 7691:  Returns:
 7692:     $count - number of scanlines to process
 7693: 
 7694: =cut
 7695: 
 7696: sub get_todo_count {
 7697:     my ($scanlines,$scan_data)=@_;
 7698:     my $count=0;
 7699:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7700: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7701: 	if ($line=~/^[\s\cz]*$/) { next; }
 7702: 	$count++;
 7703:     }
 7704:     return $count;
 7705: }
 7706: 
 7707: =pod
 7708: 
 7709: =item scantron_put_line
 7710: 
 7711:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7712:     data file.
 7713: 
 7714:  Arguments:
 7715:     $scanlines - hash ref that looks like the first return value from
 7716:                  &scantron_getfile()
 7717:     $scan_data - hash ref that looks like the second return value from
 7718:                  &scantron_getfile()
 7719:     $i         - line number to update
 7720:     $newline   - contents of the updated scanline
 7721:     $skip      - if true make the line for skipping and update the
 7722:                  'skipped' file
 7723: 
 7724: =cut
 7725: 
 7726: sub scantron_put_line {
 7727:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7728:     if ($skip) {
 7729: 	$scanlines->{'skipped'}[$i]=$newline;
 7730: 	&start_skipping($scan_data,$i);
 7731: 	return;
 7732:     }
 7733:     $scanlines->{'corrected'}[$i]=$newline;
 7734: }
 7735: 
 7736: =pod
 7737: 
 7738: =item scantron_clear_skip
 7739: 
 7740:    Remove a line from the 'skipped' file
 7741: 
 7742:  Arguments:
 7743:     $scanlines - hash ref that looks like the first return value from
 7744:                  &scantron_getfile()
 7745:     $scan_data - hash ref that looks like the second return value from
 7746:                  &scantron_getfile()
 7747:     $i         - line number to update
 7748: 
 7749: =cut
 7750: 
 7751: sub scantron_clear_skip {
 7752:     my ($scanlines,$scan_data,$i)=@_;
 7753:     if (exists($scanlines->{'skipped'}[$i])) {
 7754: 	undef($scanlines->{'skipped'}[$i]);
 7755: 	return 1;
 7756:     }
 7757:     return 0;
 7758: }
 7759: 
 7760: =pod
 7761: 
 7762: =item scantron_filter_not_exam
 7763: 
 7764:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7765:    filter out resources that are not marked as 'exam' mode
 7766: 
 7767: =cut
 7768: 
 7769: sub scantron_filter_not_exam {
 7770:     my ($curres)=@_;
 7771:     
 7772:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7773: 	# if the user has asked to not have either hidden
 7774: 	# or 'randomout' controlled resources to be graded
 7775: 	# don't include them
 7776: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7777: 	    && $curres->randomout) {
 7778: 	    return 0;
 7779: 	}
 7780: 	return 1;
 7781:     }
 7782:     return 0;
 7783: }
 7784: 
 7785: =pod
 7786: 
 7787: =item scantron_validate_sequence
 7788: 
 7789:     Validates the selected sequence, checking for resource that are
 7790:     not set to exam mode.
 7791: 
 7792: =cut
 7793: 
 7794: sub scantron_validate_sequence {
 7795:     my ($r,$currentphase) = @_;
 7796: 
 7797:     my $navmap=Apache::lonnavmaps::navmap->new();
 7798:     unless (ref($navmap)) {
 7799:         $r->print(&navmap_errormsg());
 7800:         return (1,$currentphase);
 7801:     }
 7802:     my (undef,undef,$sequence)=
 7803: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7804: 
 7805:     my $map=$navmap->getResourceByUrl($sequence);
 7806: 
 7807:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7808:                                     value="ignore" />');
 7809:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7810: 	my @resources=
 7811: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7812: 	if (@resources) {
 7813: 	    $r->print(
 7814:                 '<p class="LC_warning">'
 7815:                .&mt('Some resources in the sequence currently are not set to'
 7816:                    .' bubblesheet 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,$skipbysec,$checksec,@gradable) = @_;
 7831:     
 7832:     #get student info
 7833:     my $classlist=&Apache::loncoursedata::get_classlist();
 7834:     my %idmap=&username_to_idmap($classlist);
 7835:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7836: 
 7837:     #get scantron line setup
 7838:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7839:     my ($scanlines,$scan_data)=&scantron_getfile();
 7840: 
 7841:     my $nav_error;
 7842:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7843:     if ($nav_error) {
 7844:         $r->print(&navmap_errormsg());
 7845:         return(1,$currentphase);
 7846:     }
 7847: 
 7848:     my %found=('ids'=>{},'usernames'=>{});
 7849:     my $unsavedskips = 0;
 7850:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7851: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7852: 	if ($line=~/^[\s\cz]*$/) { next; }
 7853: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7854: 						 $scan_data);
 7855: 	my $id=$$scan_record{'scantron.ID'};
 7856: 	my $found;
 7857: 	foreach my $checkid (keys(%idmap)) {
 7858: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7859: 	}
 7860: 	if ($found) {
 7861: 	    my $username=$idmap{$found};
 7862:             if ($checksec) {
 7863:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7864:                     my $stusec = $classlist->{$username}->[$secidx];
 7865:                     if ($stusec ne $checksec) {
 7866:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7867:                             my $skip=1;
 7868:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7869:                             if (ref($skipbysec) eq 'HASH') {
 7870:                                 if ($stusec eq '') {
 7871:                                     $skipbysec->{'none'} ++;
 7872:                                 } else {
 7873:                                     $skipbysec->{$stusec} ++;
 7874:                                 }
 7875:                             }
 7876:                             $unsavedskips ++;
 7877:                             next;
 7878:                         }
 7879:                     }
 7880:                 }
 7881:             }
 7882: 	    if ($found{'ids'}{$found}) {
 7883: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7884: 					 $line,'duplicateID',$found);
 7885:                 if ($unsavedskips) {
 7886:                     &scantron_putfile($scanlines,$scan_data);
 7887:                     $unsavedskips = 0;
 7888:                 }
 7889: 		return(1,$currentphase);
 7890: 	    } elsif ($found{'usernames'}{$username}) {
 7891: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7892: 					 $line,'duplicateID',$username);
 7893:                 if ($unsavedskips) {
 7894:                     &scantron_putfile($scanlines,$scan_data);
 7895:                     $unsavedskips = 0;
 7896:                 }
 7897: 		return(1,$currentphase);
 7898: 	    }
 7899: 	    #FIXME store away line we previously saw the ID on to use above
 7900: 	    $found{'ids'}{$found}++;
 7901: 	    $found{'usernames'}{$username}++;
 7902: 	} else {
 7903: 	    if ($id =~ /^\s*$/) {
 7904: 		my $username=&scan_data($scan_data,"$i.user");
 7905:                 if (($checksec && $username ne '')) {
 7906:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 7907:                         my $stusec = $classlist->{$username}->[$secidx];
 7908:                         if ($stusec ne $checksec) {
 7909:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7910:                                 my $skip=1;
 7911:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7912:                                 if (ref($skipbysec) eq 'HASH') {
 7913:                                     if ($stusec eq '') {
 7914:                                         $skipbysec->{'none'} ++;
 7915:                                     } else {
 7916:                                         $skipbysec->{$stusec} ++;
 7917:                                     }
 7918:                                 }
 7919:                                 $unsavedskips ++;
 7920:                                 next;
 7921:                             }
 7922:                         }
 7923:                     }
 7924: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 7925: 		    &scantron_get_correction($r,$i,$scan_record,
 7926: 					     \%scantron_config,
 7927: 					     $line,'duplicateID',$username);
 7928:                     if ($unsavedskips) {
 7929:                         &scantron_putfile($scanlines,$scan_data);
 7930:                         $unsavedskips = 0;
 7931:                     }
 7932: 		    return(1,$currentphase);
 7933: 		} elsif (!defined($username)) {
 7934: 		    &scantron_get_correction($r,$i,$scan_record,
 7935: 					     \%scantron_config,
 7936: 					     $line,'incorrectID');
 7937:                     if ($unsavedskips) {
 7938:                         &scantron_putfile($scanlines,$scan_data);
 7939:                         $unsavedskips = 0;
 7940:                     }
 7941: 		    return(1,$currentphase);
 7942: 		}
 7943: 		$found{'usernames'}{$username}++;
 7944: 	    } else {
 7945: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7946: 					 $line,'incorrectID');
 7947:                 if ($unsavedskips) {
 7948:                     &scantron_putfile($scanlines,$scan_data);
 7949:                     $unsavedskips = 0;
 7950:                 }
 7951: 		return(1,$currentphase);
 7952: 	    }
 7953: 	}
 7954:     }
 7955:     if ($unsavedskips) {
 7956:         &scantron_putfile($scanlines,$scan_data);
 7957:         $unsavedskips = 0;
 7958:     }
 7959:     return (0,$currentphase+1);
 7960: }
 7961: 
 7962: sub scantron_get_sections {
 7963:     my %bysec;
 7964:     if ($env{'form.scantron_format'} ne '') {
 7965:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7966:         my ($scanlines,$scan_data)=&scantron_getfile();
 7967:         my $classlist=&Apache::loncoursedata::get_classlist();
 7968:         my %idmap=&username_to_idmap($classlist);
 7969:         foreach my $key (keys(%idmap)) {
 7970:             my $lckey = lc($key);
 7971:             $idmap{$lckey} = $idmap{$key};
 7972:         }
 7973:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 7974:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7975:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7976:             if ($line=~/^[\s\cz]*$/) { next; }
 7977:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7978:                                                      $scan_data);
 7979:             my $id=lc($$scan_record{'scantron.ID'});
 7980:             if (exists($idmap{$id})) {
 7981:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 7982:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 7983:                     if ($stusec eq '') {
 7984:                         $bysec{'none'} ++;
 7985:                     } else {
 7986:                         $bysec{$stusec} ++;
 7987:                     }
 7988:                 }
 7989:             }
 7990:         }
 7991:     }
 7992:     return %bysec;
 7993: }
 7994: 
 7995: sub scantron_get_correction {
 7996:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7997:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7998: #FIXME in the case of a duplicated ID the previous line, probably need
 7999: #to show both the current line and the previous one and allow skipping
 8000: #the previous one or the current one
 8001: 
 8002:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8003:         $r->print(
 8004:             '<p class="LC_warning">'
 8005:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8006:                 "<b>$error</b>",
 8007:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8008:            ."</p> \n");
 8009:     } else {
 8010:         $r->print(
 8011:             '<p class="LC_warning">'
 8012:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8013:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8014:            ."</p> \n");
 8015:     }
 8016:     my $message =
 8017:         '<p>'
 8018:        .&mt('The ID on the form is [_1]',
 8019:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8020:        .'<br />'
 8021:        .&mt('The name on the paper is [_1], [_2]',
 8022:             $$scan_record{'scantron.LastName'},
 8023:             $$scan_record{'scantron.FirstName'})
 8024:        .'</p>';
 8025: 
 8026:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8027:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8028:                            # Array populated for doublebubble or
 8029:     my @lines_to_correct;  # missingbubble errors to build javascript
 8030:                            # to validate radio button checking   
 8031: 
 8032:     if ($error =~ /ID$/) {
 8033: 	if ($error eq 'incorrectID') {
 8034:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8035: 		      "</p>\n");
 8036: 	} elsif ($error eq 'duplicateID') {
 8037:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8038: 	}
 8039: 	$r->print($message);
 8040: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8041: 	$r->print("\n<ul><li> ");
 8042: 	#FIXME it would be nice if this sent back the user ID and
 8043: 	#could do partial userID matches
 8044: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8045: 				       'scantron_username','scantron_domain'));
 8046: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8047: 	$r->print("\n:\n".
 8048: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8049: 
 8050: 	$r->print('</li>');
 8051:     } elsif ($error =~ /CODE$/) {
 8052: 	if ($error eq 'incorrectCODE') {
 8053: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8054: 	} elsif ($error eq 'duplicateCODE') {
 8055: 	    $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");
 8056: 	}
 8057: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8058: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8059:                  ."</p>\n");
 8060: 	$r->print($message);
 8061: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8062: 	$r->print("\n<br /> ");
 8063: 	my $i=0;
 8064: 	if ($error eq 'incorrectCODE' 
 8065: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8066: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8067: 	    if ($closest > 0) {
 8068: 		foreach my $testcode (@{$closest}) {
 8069: 		    my $checked='';
 8070: 		    if (!$i) { $checked=' checked="checked"'; }
 8071: 		    $r->print("
 8072:    <label>
 8073:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8074:        ".&mt("Use the similar CODE [_1] instead.",
 8075: 	    "<b><tt>".$testcode."</tt></b>")."
 8076:     </label>
 8077:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8078: 		    $r->print("\n<br />");
 8079: 		    $i++;
 8080: 		}
 8081: 	    }
 8082: 	}
 8083: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8084: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8085: 	    $r->print("
 8086:     <label>
 8087:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8088:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8089: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8090:     </label>");
 8091: 	    $r->print("\n<br />");
 8092: 	}
 8093: 
 8094: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8095: function change_radio(field) {
 8096:     var slct=document.scantronupload.scantron_CODE_resolution;
 8097:     var i;
 8098:     for (i=0;i<slct.length;i++) {
 8099:         if (slct[i].value==field) { slct[i].checked=true; }
 8100:     }
 8101: }
 8102: ENDSCRIPT
 8103: 	my $href="/adm/pickcode?".
 8104: 	   "form=".&escape("scantronupload").
 8105: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8106: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8107: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8108: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8109: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8110: 	    $r->print("
 8111:     <label>
 8112:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8113:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8114: 	     "<a target='_blank' href='$href'>","</a>")."
 8115:     </label> 
 8116:     ".&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\')" />'));
 8117: 	    $r->print("\n<br />");
 8118: 	}
 8119: 	$r->print("
 8120:     <label>
 8121:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8122:        ".&mt("Use [_1] as the CODE.",
 8123: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8124: 	$r->print("\n<br /><br />");
 8125:     } elsif ($error eq 'doublebubble') {
 8126: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8127: 
 8128: 	# The form field scantron_questions is acutally a list of line numbers.
 8129: 	# represented by this form so:
 8130: 
 8131: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8132:                                                 $respnumlookup,$startline);
 8133: 
 8134: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8135: 		  $line_list.'" />');
 8136: 	$r->print($message);
 8137: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8138: 	foreach my $question (@{$arg}) {
 8139: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8140:                                                    $scan_record, $error,
 8141:                                                    $randomorder,$randompick,
 8142:                                                    $respnumlookup,$startline);
 8143:             push(@lines_to_correct,@linenums);
 8144: 	}
 8145:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8146:     } elsif ($error eq 'missingbubble') {
 8147: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8148: 	$r->print($message);
 8149: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8150: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8151: 
 8152: 	# The form field scantron_questions is actually a list of line numbers not
 8153: 	# a list of question numbers. Therefore:
 8154: 	#
 8155: 
 8156: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8157:                                                 $respnumlookup,$startline);
 8158: 
 8159: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8160: 		  $line_list.'" />');
 8161: 	foreach my $question (@{$arg}) {
 8162: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8163:                                                    $scan_record, $error,
 8164:                                                    $randomorder,$randompick,
 8165:                                                    $respnumlookup,$startline);
 8166:             push(@lines_to_correct,@linenums);
 8167: 	}
 8168:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8169:     } else {
 8170: 	$r->print("\n<ul>");
 8171:     }
 8172:     $r->print("\n</li></ul>");
 8173: }
 8174: 
 8175: sub verify_bubbles_checked {
 8176:     my (@ansnums) = @_;
 8177:     my $ansnumstr = join('","',@ansnums);
 8178:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8179:     &js_escape(\$warning);
 8180:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8181: function verify_bubble_radio(form) {
 8182:     var ansnumArray = new Array ("$ansnumstr");
 8183:     var need_bubble_count = 0;
 8184:     for (var i=0; i<ansnumArray.length; i++) {
 8185:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8186:             var bubble_picked = 0; 
 8187:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8188:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8189:                     bubble_picked = 1;
 8190:                 }
 8191:             }
 8192:             if (bubble_picked == 0) {
 8193:                 need_bubble_count ++;
 8194:             }
 8195:         }
 8196:     }
 8197:     if (need_bubble_count) {
 8198:         alert("$warning");
 8199:         return;
 8200:     }
 8201:     form.submit(); 
 8202: }
 8203: ENDSCRIPT
 8204:     return $output;
 8205: }
 8206: 
 8207: =pod
 8208: 
 8209: =item  questions_to_line_list
 8210: 
 8211: Converts a list of questions into a string of comma separated
 8212: line numbers in the answer sheet used by the questions.  This is
 8213: used to fill in the scantron_questions form field.
 8214: 
 8215:   Arguments:
 8216:      questions    - Reference to an array of questions.
 8217:      randomorder  - True if randomorder in use.
 8218:      randompick   - True if randompick in use.
 8219:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8220:                      for current line to question number used for same question
 8221:                      in "Master Seqence" (as seen by Course Coordinator).
 8222:      startline    - Reference to hash where key is question number (0 is first)
 8223:                     and key is number of first bubble line for current student
 8224:                     or code-based randompick and/or randomorder.
 8225: 
 8226: =cut
 8227: 
 8228: 
 8229: sub questions_to_line_list {
 8230:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8231:     my @lines;
 8232: 
 8233:     foreach my $item (@{$questions}) {
 8234:         my $question = $item;
 8235:         my ($first,$count,$last);
 8236:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8237:             $question = $1;
 8238:             my $subquestion = $2;
 8239:             my $responsenum = $question-1;
 8240:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8241:                 $responsenum = $respnumlookup->{$question-1};
 8242:                 if (ref($startline) eq 'HASH') {
 8243:                     $first = $startline->{$question-1} + 1;
 8244:                 }
 8245:             } else {
 8246:                 $first = $first_bubble_line{$responsenum} + 1;
 8247:             }
 8248:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8249:             my $subcount = 1;
 8250:             while ($subcount<$subquestion) {
 8251:                 $first += $subans[$subcount-1];
 8252:                 $subcount ++;
 8253:             }
 8254:             $count = $subans[$subquestion-1];
 8255:         } else {
 8256:             my $responsenum = $question-1;
 8257:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8258:                 $responsenum = $respnumlookup->{$question-1};
 8259:                 if (ref($startline) eq 'HASH') {
 8260:                     $first = $startline->{$question-1} + 1;
 8261:                 }
 8262:             } else {
 8263:                 $first = $first_bubble_line{$responsenum} + 1;
 8264:             }
 8265: 	    $count   = $bubble_lines_per_response{$responsenum};
 8266:         }
 8267:         $last = $first+$count-1;
 8268:         push(@lines, ($first..$last));
 8269:     }
 8270:     return join(',', @lines);
 8271: }
 8272: 
 8273: =pod 
 8274: 
 8275: =item prompt_for_corrections
 8276: 
 8277: Prompts for a potentially multiline correction to the
 8278: user's bubbling (factors out common code from scantron_get_correction
 8279: for multi and missing bubble cases).
 8280: 
 8281:  Arguments:
 8282:    $r           - Apache request object.
 8283:    $question    - The question number to prompt for.
 8284:    $scan_config - The scantron file configuration hash.
 8285:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8286:    $error       - Type of error
 8287:    $randomorder - True if randomorder in use.
 8288:    $randompick  - True if randompick in use.
 8289:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8290:                     for current line to question number used for same question
 8291:                     in "Master Seqence" (as seen by Course Coordinator).
 8292:    $startline   - Reference to hash where key is question number (0 is first)
 8293:                   and value is number of first bubble line for current student
 8294:                   or code-based randompick and/or randomorder.
 8295: 
 8296: 
 8297:  Implicit inputs:
 8298:    %bubble_lines_per_response   - Starting line numbers for each question.
 8299:                                   Numbered from 0 (but question numbers are from
 8300:                                   1.
 8301:    %first_bubble_line           - Starting bubble line for each question.
 8302:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8303:                                   type problems render as separate sub-questions, 
 8304:                                   in exam mode. This hash contains a 
 8305:                                   comma-separated list of the lines per 
 8306:                                   sub-question.
 8307:    %responsetype_per_response   - essayresponse, formularesponse,
 8308:                                   stringresponse, imageresponse, reactionresponse,
 8309:                                   and organicresponse type problem parts can have
 8310:                                   multiple lines per response if the weight
 8311:                                   assigned exceeds 10.  In this case, only
 8312:                                   one bubble per line is permitted, but more 
 8313:                                   than one line might contain bubbles, e.g.
 8314:                                   bubbling of: line 1 - J, line 2 - J, 
 8315:                                   line 3 - B would assign 22 points.  
 8316: 
 8317: =cut
 8318: 
 8319: sub prompt_for_corrections {
 8320:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8321:         $randompick, $respnumlookup, $startline) = @_;
 8322:     my ($current_line,$lines);
 8323:     my @linenums;
 8324:     my $questionnum = $question;
 8325:     my ($first,$responsenum);
 8326:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8327:         $question = $1;
 8328:         my $subquestion = $2;
 8329:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8330:             $responsenum = $respnumlookup->{$question-1};
 8331:             if (ref($startline) eq 'HASH') {
 8332:                 $first = $startline->{$question-1};
 8333:             }
 8334:         } else {
 8335:             $responsenum = $question-1;
 8336:             $first = $first_bubble_line{$responsenum};
 8337:         }
 8338:         $current_line = $first + 1 ;
 8339:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8340:         my $subcount = 1;
 8341:         while ($subcount<$subquestion) {
 8342:             $current_line += $subans[$subcount-1];
 8343:             $subcount ++;
 8344:         }
 8345:         $lines = $subans[$subquestion-1];
 8346:     } else {
 8347:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8348:             $responsenum = $respnumlookup->{$question-1};
 8349:             if (ref($startline) eq 'HASH') { 
 8350:                 $first = $startline->{$question-1};
 8351:             }
 8352:         } else {
 8353:             $responsenum = $question-1;
 8354:             $first = $first_bubble_line{$responsenum};
 8355:         }
 8356:         $current_line = $first + 1;
 8357:         $lines        = $bubble_lines_per_response{$responsenum};
 8358:     }
 8359:     if ($lines > 1) {
 8360:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8361:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8362:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8363:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8364:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8365:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8366:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8367:             $r->print(
 8368:                 &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)
 8369:                .'<br /><br />'
 8370:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8371:                .'<br />'
 8372:                .&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.')
 8373:                .'<br />'
 8374:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8375:                .'<br /><br />'
 8376:             );
 8377:         } else {
 8378:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8379:         }
 8380:     }
 8381:     for (my $i =0; $i < $lines; $i++) {
 8382:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8383: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8384: 	        		  $questionnum,$error,split('', $selected));
 8385:         push(@linenums,$current_line);
 8386: 	$current_line++;
 8387:     }
 8388:     if ($lines > 1) {
 8389: 	$r->print("<hr /><br />");
 8390:     }
 8391:     return @linenums;
 8392: }
 8393: 
 8394: =pod
 8395: 
 8396: =item scantron_bubble_selector
 8397:   
 8398:    Generates the html radiobuttons to correct a single bubble line
 8399:    possibly showing the existing the selected bubbles if known
 8400: 
 8401:  Arguments:
 8402:     $r           - Apache request object
 8403:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8404:     $line        - Number of the line being displayed.
 8405:     $questionnum - Question number (may include subquestion)
 8406:     $error       - Type of error.
 8407:     @selected    - Array of bubbles picked on this line.
 8408: 
 8409: =cut
 8410: 
 8411: sub scantron_bubble_selector {
 8412:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8413:     my $max=$$scan_config{'Qlength'};
 8414: 
 8415:     my $scmode=$$scan_config{'Qon'};
 8416:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8417:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8418:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8419:             $max=$$scan_config{'BubblesPerRow'};
 8420:             if (($scmode eq 'number') && ($max > 10)) {
 8421:                 $max = 10;
 8422:             } elsif (($scmode eq 'letter') && $max > 26) {
 8423:                 $max = 26;
 8424:             }
 8425:         } else {
 8426:             $max = 10;
 8427:         }
 8428:     }
 8429: 
 8430:     my @alphabet=('A'..'Z');
 8431:     $r->print(&Apache::loncommon::start_data_table().
 8432:               &Apache::loncommon::start_data_table_row());
 8433:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8434:     for (my $i=0;$i<$max+1;$i++) {
 8435: 	$r->print("\n".'<td align="center">');
 8436: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8437: 	else { $r->print('&nbsp;'); }
 8438: 	$r->print('</td>');
 8439:     }
 8440:     $r->print(&Apache::loncommon::end_data_table_row().
 8441:               &Apache::loncommon::start_data_table_row());
 8442:     for (my $i=0;$i<$max;$i++) {
 8443: 	$r->print("\n".
 8444: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8445: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8446:     }
 8447:     my $nobub_checked = ' ';
 8448:     if ($error eq 'missingbubble') {
 8449:         $nobub_checked = ' checked = "checked" ';
 8450:     }
 8451:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8452: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8453:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8454:               $line.'" value="'.$questionnum.'" /></td>');
 8455:     $r->print(&Apache::loncommon::end_data_table_row().
 8456:               &Apache::loncommon::end_data_table());
 8457: }
 8458: 
 8459: =pod
 8460: 
 8461: =item num_matches
 8462: 
 8463:    Counts the number of characters that are the same between the two arguments.
 8464: 
 8465:  Arguments:
 8466:    $orig - CODE from the scanline
 8467:    $code - CODE to match against
 8468: 
 8469:  Returns:
 8470:    $count - integer count of the number of same characters between the
 8471:             two arguments
 8472: 
 8473: =cut
 8474: 
 8475: sub num_matches {
 8476:     my ($orig,$code) = @_;
 8477:     my @code=split(//,$code);
 8478:     my @orig=split(//,$orig);
 8479:     my $same=0;
 8480:     for (my $i=0;$i<scalar(@code);$i++) {
 8481: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8482:     }
 8483:     return $same;
 8484: }
 8485: 
 8486: =pod
 8487: 
 8488: =item scantron_get_closely_matching_CODEs
 8489: 
 8490:    Cycles through all CODEs and finds the set that has the greatest
 8491:    number of same characters as the provided CODE
 8492: 
 8493:  Arguments:
 8494:    $allcodes - hash ref returned by &get_codes()
 8495:    $CODE     - CODE from the current scanline
 8496: 
 8497:  Returns:
 8498:    2 element list
 8499:     - first elements is number of how closely matching the best fit is 
 8500:       (5 means best set has 5 matching characters)
 8501:     - second element is an arrary ref containing the set of valid CODEs
 8502:       that best fit the passed in CODE
 8503: 
 8504: =cut
 8505: 
 8506: sub scantron_get_closely_matching_CODEs {
 8507:     my ($allcodes,$CODE)=@_;
 8508:     my @CODEs;
 8509:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8510: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8511:     }
 8512: 
 8513:     return ($#CODEs,$CODEs[-1]);
 8514: }
 8515: 
 8516: =pod
 8517: 
 8518: =item get_codes
 8519: 
 8520:    Builds a hash which has keys of all of the valid CODEs from the selected
 8521:    set of remembered CODEs.
 8522: 
 8523:  Arguments:
 8524:   $old_name - name of the set of remembered CODEs
 8525:   $cdom     - domain of the course
 8526:   $cnum     - internal course name
 8527: 
 8528:  Returns:
 8529:   %allcodes - keys are the valid CODEs, values are all 1
 8530: 
 8531: =cut
 8532: 
 8533: sub get_codes {
 8534:     my ($old_name, $cdom, $cnum) = @_;
 8535:     if (!$old_name) {
 8536: 	$old_name=$env{'form.scantron_CODElist'};
 8537:     }
 8538:     if (!$cdom) {
 8539: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8540:     }
 8541:     if (!$cnum) {
 8542: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8543:     }
 8544:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8545: 				    $cdom,$cnum);
 8546:     my %allcodes;
 8547:     if ($result{"type\0$old_name"} eq 'number') {
 8548: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8549:     } else {
 8550: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8551:     }
 8552:     return %allcodes;
 8553: }
 8554: 
 8555: =pod
 8556: 
 8557: =item scantron_validate_CODE
 8558: 
 8559:    Validates all scanlines in the selected file to not have any
 8560:    invalid or underspecified CODEs and that none of the codes are
 8561:    duplicated if this was requested.
 8562: 
 8563: =cut
 8564: 
 8565: sub scantron_validate_CODE {
 8566:     my ($r,$currentphase) = @_;
 8567:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8568:     if ($scantron_config{'CODElocation'} &&
 8569: 	$scantron_config{'CODEstart'} &&
 8570: 	$scantron_config{'CODElength'}) {
 8571: 	if (!defined($env{'form.scantron_CODElist'})) {
 8572: 	    &FIXME_blow_up()
 8573: 	}
 8574:     } else {
 8575: 	return (0,$currentphase+1);
 8576:     }
 8577:     
 8578:     my %usedCODEs;
 8579: 
 8580:     my %allcodes=&get_codes();
 8581: 
 8582:     my $nav_error;
 8583:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8584:     if ($nav_error) {
 8585:         $r->print(&navmap_errormsg());
 8586:         return(1,$currentphase);
 8587:     }
 8588: 
 8589:     my ($scanlines,$scan_data)=&scantron_getfile();
 8590:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8591: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8592: 	if ($line=~/^[\s\cz]*$/) { next; }
 8593: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8594: 						 $scan_data);
 8595: 	my $CODE=$$scan_record{'scantron.CODE'};
 8596: 	my $error=0;
 8597: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8598: 	    &scantron_get_correction($r,$i,$scan_record,
 8599: 				     \%scantron_config,
 8600: 				     $line,'incorrectCODE',\%allcodes);
 8601: 	    return(1,$currentphase);
 8602: 	}
 8603: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8604: 	    && !$$scan_record{'scantron.useCODE'}) {
 8605: 	    &scantron_get_correction($r,$i,$scan_record,
 8606: 				     \%scantron_config,
 8607: 				     $line,'incorrectCODE',\%allcodes);
 8608: 	    return(1,$currentphase);
 8609: 	}
 8610: 	if (exists($usedCODEs{$CODE}) 
 8611: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8612: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8613: 	    &scantron_get_correction($r,$i,$scan_record,
 8614: 				     \%scantron_config,
 8615: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8616: 	    return(1,$currentphase);
 8617: 	}
 8618: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8619:     }
 8620:     return (0,$currentphase+1);
 8621: }
 8622: 
 8623: =pod
 8624: 
 8625: =item scantron_validate_doublebubble
 8626: 
 8627:    Validates all scanlines in the selected file to not have any
 8628:    bubble lines with multiple bubbles marked.
 8629: 
 8630: =cut
 8631: 
 8632: sub scantron_validate_doublebubble {
 8633:     my ($r,$currentphase) = @_;
 8634:     #get student info
 8635:     my $classlist=&Apache::loncoursedata::get_classlist();
 8636:     my %idmap=&username_to_idmap($classlist);
 8637:     my (undef,undef,$sequence)=
 8638:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8639: 
 8640:     #get scantron line setup
 8641:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8642:     my ($scanlines,$scan_data)=&scantron_getfile();
 8643: 
 8644:     my $navmap = Apache::lonnavmaps::navmap->new();
 8645:     unless (ref($navmap)) {
 8646:         $r->print(&navmap_errormsg());
 8647:         return(1,$currentphase);
 8648:     }
 8649:     my $map=$navmap->getResourceByUrl($sequence);
 8650:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8651:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8652:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8653:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8654: 
 8655:     my $nav_error;
 8656:     if (ref($map)) {
 8657:         $randomorder = $map->randomorder();
 8658:         $randompick = $map->randompick();
 8659:         if ($randomorder || $randompick) {
 8660:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8661:             if ($nav_error) {
 8662:                 $r->print(&navmap_errormsg());
 8663:                 return(1,$currentphase);
 8664:             }
 8665:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8666:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8667:         }
 8668:     } else {
 8669:         $r->print(&navmap_errormsg());
 8670:         return(1,$currentphase);
 8671:     }
 8672: 
 8673:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8674:     if ($nav_error) {
 8675:         $r->print(&navmap_errormsg());
 8676:         return(1,$currentphase);
 8677:     }
 8678: 
 8679:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8680: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8681: 	if ($line=~/^[\s\cz]*$/) { next; }
 8682: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8683: 						 $scan_data,undef,\%idmap,$randomorder,
 8684:                                                  $randompick,$sequence,\@master_seq,
 8685:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8686:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8687: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8688: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8689: 				 'doublebubble',
 8690: 				 $$scan_record{'scantron.doubleerror'},
 8691:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8692:     	return (1,$currentphase);
 8693:     }
 8694:     return (0,$currentphase+1);
 8695: }
 8696: 
 8697: 
 8698: sub scantron_get_maxbubble {
 8699:     my ($nav_error,$scantron_config) = @_;
 8700:     if (defined($env{'form.scantron_maxbubble'}) &&
 8701: 	$env{'form.scantron_maxbubble'}) {
 8702: 	&restore_bubble_lines();
 8703: 	return $env{'form.scantron_maxbubble'};
 8704:     }
 8705: 
 8706:     my (undef, undef, $sequence) =
 8707: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8708: 
 8709:     my $navmap=Apache::lonnavmaps::navmap->new();
 8710:     unless (ref($navmap)) {
 8711:         if (ref($nav_error)) {
 8712:             $$nav_error = 1;
 8713:         }
 8714:         return;
 8715:     }
 8716:     my $map=$navmap->getResourceByUrl($sequence);
 8717:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8718:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8719: 
 8720:     &Apache::lonxml::clear_problem_counter();
 8721: 
 8722:     my $uname       = $env{'user.name'};
 8723:     my $udom        = $env{'user.domain'};
 8724:     my $cid         = $env{'request.course.id'};
 8725:     my $total_lines = 0;
 8726:     %bubble_lines_per_response = ();
 8727:     %first_bubble_line         = ();
 8728:     %subdivided_bubble_lines   = ();
 8729:     %responsetype_per_response = ();
 8730:     %masterseq_id_responsenum  = ();
 8731: 
 8732:     my $response_number = 0;
 8733:     my $bubble_line     = 0;
 8734:     foreach my $resource (@resources) {
 8735:         my $resid = $resource->id(); 
 8736:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8737:                                                           $udom,undef,$bubbles_per_row);
 8738:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8739: 	    foreach my $part_id (@{$parts}) {
 8740:                 my $lines;
 8741: 
 8742: 	        # TODO - make this a persistent hash not an array.
 8743: 
 8744:                 # optionresponse, matchresponse and rankresponse type items 
 8745:                 # render as separate sub-questions in exam mode.
 8746:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8747:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8748:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8749:                     my ($numbub,$numshown);
 8750:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8751:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8752:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8753:                         }
 8754:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8755:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8756:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8757:                         }
 8758:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8759:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8760:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8761:                         }
 8762:                     }
 8763:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8764:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8765:                     }
 8766:                     my $bubbles_per_row =
 8767:                         &bubblesheet_bubbles_per_row($scantron_config);
 8768:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8769:                     if (($numbub % $bubbles_per_row) != 0) {
 8770:                         $inner_bubble_lines++;
 8771:                     }
 8772:                     for (my $i=0; $i<$numshown; $i++) {
 8773:                         $subdivided_bubble_lines{$response_number} .= 
 8774:                             $inner_bubble_lines.',';
 8775:                     }
 8776:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8777:                     $lines = $numshown * $inner_bubble_lines;
 8778:                 } else {
 8779:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8780:                 }
 8781: 
 8782:                 $first_bubble_line{$response_number} = $bubble_line;
 8783: 	        $bubble_lines_per_response{$response_number} = $lines;
 8784:                 $responsetype_per_response{$response_number} = 
 8785:                     $analysis->{$part_id.'.type'};
 8786:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8787: 	        $response_number++;
 8788: 
 8789: 	        $bubble_line +=  $lines;
 8790: 	        $total_lines +=  $lines;
 8791: 	    }
 8792:         }
 8793:     }
 8794:     &Apache::lonnet::delenv('scantron.');
 8795: 
 8796:     &save_bubble_lines();
 8797:     $env{'form.scantron_maxbubble'} =
 8798: 	$total_lines;
 8799:     return $env{'form.scantron_maxbubble'};
 8800: }
 8801: 
 8802: sub bubblesheet_bubbles_per_row {
 8803:     my ($scantron_config) = @_;
 8804:     my $bubbles_per_row;
 8805:     if (ref($scantron_config) eq 'HASH') {
 8806:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8807:     }
 8808:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8809:         $bubbles_per_row = 10;
 8810:     }
 8811:     return $bubbles_per_row;
 8812: }
 8813: 
 8814: sub scantron_validate_missingbubbles {
 8815:     my ($r,$currentphase) = @_;
 8816:     #get student info
 8817:     my $classlist=&Apache::loncoursedata::get_classlist();
 8818:     my %idmap=&username_to_idmap($classlist);
 8819:     my (undef,undef,$sequence)=
 8820:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8821: 
 8822:     #get scantron line setup
 8823:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8824:     my ($scanlines,$scan_data)=&scantron_getfile();
 8825: 
 8826:     my $navmap = Apache::lonnavmaps::navmap->new();
 8827:     unless (ref($navmap)) {
 8828:         $r->print(&navmap_errormsg());
 8829:         return(1,$currentphase);
 8830:     }
 8831: 
 8832:     my $map=$navmap->getResourceByUrl($sequence);
 8833:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8834:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8835:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8836:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8837: 
 8838:     my $nav_error;
 8839:     if (ref($map)) {
 8840:         $randomorder = $map->randomorder();
 8841:         $randompick = $map->randompick();
 8842:         if ($randomorder || $randompick) {
 8843:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8844:             if ($nav_error) {
 8845:                 $r->print(&navmap_errormsg());
 8846:                 return(1,$currentphase);
 8847:             }
 8848:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8849:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8850:         }
 8851:     } else {
 8852:         $r->print(&navmap_errormsg());
 8853:         return(1,$currentphase);
 8854:     }
 8855: 
 8856: 
 8857:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8858:     if ($nav_error) {
 8859:         $r->print(&navmap_errormsg());
 8860:         return(1,$currentphase);
 8861:     }
 8862: 
 8863:     if (!$max_bubble) { $max_bubble=2**31; }
 8864:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8865: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8866: 	if ($line=~/^[\s\cz]*$/) { next; }
 8867: 	my $scan_record =
 8868:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8869: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8870:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8871:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8872: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8873: 	my @to_correct;
 8874: 	
 8875: 	# Probably here's where the error is...
 8876: 
 8877: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8878:             my $lastbubble;
 8879:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8880:                my $question = $1;
 8881:                my $subquestion = $2;
 8882:                my ($first,$responsenum);
 8883:                if ($randomorder || $randompick) {
 8884:                    $responsenum = $respnumlookup{$question-1};
 8885:                    $first = $startline{$question-1};
 8886:                } else {
 8887:                    $responsenum = $question-1; 
 8888:                    $first = $first_bubble_line{$responsenum};
 8889:                }
 8890:                if (!defined($first)) { next; }
 8891:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8892:                my $subcount = 1;
 8893:                while ($subcount<$subquestion) {
 8894:                    $first += $subans[$subcount-1];
 8895:                    $subcount ++;
 8896:                }
 8897:                my $count = $subans[$subquestion-1];
 8898:                $lastbubble = $first + $count;
 8899:             } else {
 8900:                my ($first,$responsenum);
 8901:                if ($randomorder || $randompick) {
 8902:                    $responsenum = $respnumlookup{$missing-1};
 8903:                    $first = $startline{$missing-1};
 8904:                } else {
 8905:                    $responsenum = $missing-1;
 8906:                    $first = $first_bubble_line{$responsenum};
 8907:                }
 8908:                if (!defined($first)) { next; }
 8909:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8910:             }
 8911:             if ($lastbubble > $max_bubble) { next; }
 8912: 	    push(@to_correct,$missing);
 8913: 	}
 8914: 	if (@to_correct) {
 8915: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8916: 				     $line,'missingbubble',\@to_correct,
 8917:                                      $randomorder,$randompick,\%respnumlookup,
 8918:                                      \%startline);
 8919: 	    return (1,$currentphase);
 8920: 	}
 8921: 
 8922:     }
 8923:     return (0,$currentphase+1);
 8924: }
 8925: 
 8926: sub hand_bubble_option {
 8927:     my (undef, undef, $sequence) =
 8928:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8929:     return if ($sequence eq '');
 8930:     my $navmap = Apache::lonnavmaps::navmap->new();
 8931:     unless (ref($navmap)) {
 8932:         return;
 8933:     }
 8934:     my $needs_hand_bubbles;
 8935:     my $map=$navmap->getResourceByUrl($sequence);
 8936:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8937:     foreach my $res (@resources) {
 8938:         if (ref($res)) {
 8939:             if ($res->is_problem()) {
 8940:                 my $partlist = $res->parts();
 8941:                 foreach my $part (@{ $partlist }) {
 8942:                     my @types = $res->responseType($part);
 8943:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8944:                         $needs_hand_bubbles = 1;
 8945:                         last;
 8946:                     }
 8947:                 }
 8948:             }
 8949:         }
 8950:     }
 8951:     if ($needs_hand_bubbles) {
 8952:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8953:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8954:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8955:                &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 />').
 8956:                '<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;'.
 8957:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8958:     }
 8959:     return;
 8960: }
 8961: 
 8962: sub scantron_process_students {
 8963:     my ($r,$symb) = @_;
 8964: 
 8965:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8966:     if (!$symb) {
 8967: 	return '';
 8968:     }
 8969:     my $default_form_data=&defaultFormData($symb);
 8970: 
 8971:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8972:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8973:     my ($scanlines,$scan_data)=&scantron_getfile();
 8974:     my $classlist=&Apache::loncoursedata::get_classlist();
 8975:     my %idmap=&username_to_idmap($classlist);
 8976:     my $navmap=Apache::lonnavmaps::navmap->new();
 8977:     unless (ref($navmap)) {
 8978:         $r->print(&navmap_errormsg());
 8979:         return '';
 8980:     }
 8981:     my $map=$navmap->getResourceByUrl($sequence);
 8982:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8983:         %grader_randomlists_by_symb);
 8984:     if (ref($map)) {
 8985:         $randomorder = $map->randomorder();
 8986:         $randompick = $map->randompick();
 8987:     } else {
 8988:         $r->print(&navmap_errormsg());
 8989:         return '';
 8990:     }
 8991:     my $nav_error;
 8992:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8993:     if ($randomorder || $randompick) {
 8994:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8995:         if ($nav_error) {
 8996:             $r->print(&navmap_errormsg());
 8997:             return '';
 8998:         }
 8999:     }
 9000:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9001:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9002: 
 9003:     my ($uname,$udom);
 9004:     my $result= <<SCANTRONFORM;
 9005: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9006:   <input type="hidden" name="command" value="scantron_configphase" />
 9007:   $default_form_data
 9008: SCANTRONFORM
 9009:     $r->print($result);
 9010: 
 9011:     my ($checksec,@possibles)=&gradable_sections();
 9012:     my @delayqueue;
 9013:     my (%completedstudents,%scandata);
 9014: 
 9015:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9016:     my $count=&get_todo_count($scanlines,$scan_data);
 9017:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9018:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9019:     $r->print('<br />');
 9020:     my $start=&Time::HiRes::time();
 9021:     my $i=-1;
 9022:     my $started;
 9023: 
 9024:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9025:     if ($nav_error) {
 9026:         $r->print(&navmap_errormsg());
 9027:         return '';
 9028:     }
 9029: 
 9030:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9031:     # the user and return.
 9032: 
 9033:     if ($ssi_error) {
 9034: 	$r->print("</form>");
 9035: 	&ssi_print_error($r);
 9036:         &Apache::lonnet::remove_lock($lock);
 9037: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9038:     }
 9039: 
 9040:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9041:     my $numletts = scalar(keys(%lettdig));
 9042:     my %orderedforcode;
 9043: 
 9044:     while ($i<$scanlines->{'count'}) {
 9045:  	($uname,$udom)=('','');
 9046:  	$i++;
 9047:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9048:  	if ($line=~/^[\s\cz]*$/) { next; }
 9049: 	if ($started) {
 9050: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9051: 	}
 9052: 	$started=1;
 9053:         my %respnumlookup = ();
 9054:         my %startline = ();
 9055:         my $total;
 9056:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9057:                                                  $scan_data,undef,\%idmap,$randomorder,
 9058:                                                  $randompick,$sequence,\@master_seq,
 9059:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9060:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9061:                                                  \$total);
 9062:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9063:  					      \%idmap,$i)) {
 9064:   	    &scantron_add_delay(\@delayqueue,$line,
 9065:  				'Unable to find a student that matches',1);
 9066:  	    next;
 9067:   	}
 9068:  	if (exists $completedstudents{$uname}) {
 9069:  	    &scantron_add_delay(\@delayqueue,$line,
 9070:  				'Student '.$uname.' has multiple sheets',2);
 9071:  	    next;
 9072:  	}
 9073:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9074:         if (($checksec ne '') && ($checksec ne $usec)) {
 9075:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9076:                 &scantron_add_delay(\@delayqueue,$line,
 9077:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9078:                 next;
 9079:             }
 9080:         }
 9081:         my $user = $uname.':'.$usec;
 9082:   	($uname,$udom)=split(/:/,$uname);
 9083: 
 9084:         my $scancode;
 9085:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9086:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9087:             $scancode = $scan_record->{'scantron.CODE'};
 9088:         } else {
 9089:             $scancode = '';
 9090:         }
 9091: 
 9092:         my @mapresources = @resources;
 9093:         if ($randomorder || $randompick) {
 9094:             @mapresources = 
 9095:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9096:                              \%orderedforcode);
 9097:         }
 9098:         my (%partids_by_symb,$res_error);
 9099:         foreach my $resource (@mapresources) {
 9100:             my $ressymb;
 9101:             if (ref($resource)) {
 9102:                 $ressymb = $resource->symb();
 9103:             } else {
 9104:                 $res_error = 1;
 9105:                 last;
 9106:             }
 9107:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9108:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9109:                 my $currcode;
 9110:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9111:                     $currcode = $scancode;
 9112:                 }
 9113:                 my ($analysis,$parts) =
 9114:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9115:                                               $uname,$udom,undef,$bubbles_per_row,
 9116:                                               $currcode);
 9117:                 $partids_by_symb{$ressymb} = $parts;
 9118:             } else {
 9119:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9120:             }
 9121:         }
 9122: 
 9123:         if ($res_error) {
 9124:             &scantron_add_delay(\@delayqueue,$line,
 9125:                                 'An error occurred while grading student '.$uname,2);
 9126:             next;
 9127:         }
 9128: 
 9129: 	&Apache::lonxml::clear_problem_counter();
 9130:   	&Apache::lonnet::appenv($scan_record);
 9131: 
 9132: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9133: 	    &scantron_putfile($scanlines,$scan_data);
 9134: 	}
 9135: 	
 9136:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9137:                                    \@mapresources,\%partids_by_symb,
 9138:                                    $bubbles_per_row,$randomorder,$randompick,
 9139:                                    \%respnumlookup,\%startline) 
 9140:             eq 'ssi_error') {
 9141:             $ssi_error = 0; # So end of handler error message does not trigger.
 9142:             $r->print("</form>");
 9143:             &ssi_print_error($r);
 9144:             &Apache::lonnet::remove_lock($lock);
 9145:             return '';      # Why return ''?  Beats me.
 9146:         }
 9147: 
 9148:         if (($scancode) && ($randomorder || $randompick)) {
 9149:             my $parmresult =
 9150:                 &Apache::lonparmset::storeparm_by_symb($symb,
 9151:                                                        '0_examcode',2,$scancode,
 9152:                                                        'string_examcode',$uname,
 9153:                                                        $udom);
 9154:         }
 9155: 	$completedstudents{$uname}={'line'=>$line};
 9156:         if ($env{'form.verifyrecord'}) {
 9157:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9158:             if ($randompick) {
 9159:                 if ($total) {
 9160:                     $lastpos = $total*$scantron_config{'Qlength'};
 9161:                 }
 9162:             }
 9163: 
 9164:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9165:             chomp($studentdata);
 9166:             $studentdata =~ s/\r$//;
 9167:             my $studentrecord = '';
 9168:             my $counter = -1;
 9169:             foreach my $resource (@mapresources) {
 9170:                 my $ressymb = $resource->symb();
 9171:                 ($counter,my $recording) =
 9172:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9173:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9174:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9175:                                              $randompick,\%respnumlookup,\%startline);
 9176:                 $studentrecord .= $recording;
 9177:             }
 9178:             if ($studentrecord ne $studentdata) {
 9179:                 &Apache::lonxml::clear_problem_counter();
 9180:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9181:                                            \@mapresources,\%partids_by_symb,
 9182:                                            $bubbles_per_row,$randomorder,$randompick,
 9183:                                            \%respnumlookup,\%startline) 
 9184:                     eq 'ssi_error') {
 9185:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9186:                     $r->print("</form>");
 9187:                     &ssi_print_error($r);
 9188:                     &Apache::lonnet::remove_lock($lock);
 9189:                     delete($completedstudents{$uname});
 9190:                     return '';
 9191:                 }
 9192:                 $counter = -1;
 9193:                 $studentrecord = '';
 9194:                 foreach my $resource (@mapresources) {
 9195:                     my $ressymb = $resource->symb();
 9196:                     ($counter,my $recording) =
 9197:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9198:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9199:                                                  \%scantron_config,\%lettdig,$numletts,
 9200:                                                  $randomorder,$randompick,\%respnumlookup,
 9201:                                                  \%startline);
 9202:                     $studentrecord .= $recording;
 9203:                 }
 9204:                 if ($studentrecord ne $studentdata) {
 9205:                     $r->print('<p><span class="LC_warning">');
 9206:                     if ($scancode eq '') {
 9207:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9208:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9209:                     } else {
 9210:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9211:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9212:                     }
 9213:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9214:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9215:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9216:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9217:                               &Apache::loncommon::start_data_table_row().
 9218:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9219:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9220:                               &Apache::loncommon::end_data_table_row().
 9221:                               &Apache::loncommon::start_data_table_row().
 9222:                               '<td>'.&mt('Stored submissions').'</td>'.
 9223:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9224:                               &Apache::loncommon::end_data_table_row().
 9225:                               &Apache::loncommon::end_data_table().'</p>');
 9226:                 } else {
 9227:                     $r->print('<br /><span class="LC_warning">'.
 9228:                              &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 />'.
 9229:                              &mt("As a consequence, this user's submission history records two tries.").
 9230:                                  '</span><br />');
 9231:                 }
 9232:             }
 9233:         }
 9234:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9235:     } continue {
 9236: 	&Apache::lonxml::clear_problem_counter();
 9237: 	&Apache::lonnet::delenv('scantron.');
 9238:     }
 9239:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9240:     &Apache::lonnet::remove_lock($lock);
 9241: #    my $lasttime = &Time::HiRes::time()-$start;
 9242: #    $r->print("<p>took $lasttime</p>");
 9243: 
 9244:     $r->print("</form>");
 9245:     return '';
 9246: }
 9247: 
 9248: sub graders_resources_pass {
 9249:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9250:         $bubbles_per_row) = @_;
 9251:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9252:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9253:         foreach my $resource (@{$resources}) {
 9254:             my $ressymb = $resource->symb();
 9255:             my ($analysis,$parts) =
 9256:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9257:                                           $env{'user.name'},$env{'user.domain'},
 9258:                                           1,$bubbles_per_row);
 9259:             $grader_partids_by_symb->{$ressymb} = $parts;
 9260:             if (ref($analysis) eq 'HASH') {
 9261:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9262:                     $grader_randomlists_by_symb->{$ressymb} =
 9263:                         $analysis->{'parts_withrandomlist'};
 9264:                 }
 9265:             }
 9266:         }
 9267:     }
 9268:     return;
 9269: }
 9270: 
 9271: =pod
 9272: 
 9273: =item users_order
 9274: 
 9275:   Returns array of resources in current map, ordered based on either CODE,
 9276:   if this is a CODEd exam, or based on student's identity if this is a 
 9277:   "NAMEd" exam.
 9278: 
 9279:   Should be used when randomorder and/or randompick applied when the 
 9280:   corresponding exam was printed, prior to students completing bubblesheets 
 9281:   for the version of the exam the student received.
 9282: 
 9283: =cut
 9284: 
 9285: sub users_order  {
 9286:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9287:     my @mapresources;
 9288:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9289:         return @mapresources;
 9290:     }
 9291:     if ($scancode) {
 9292:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9293:             @mapresources = @{$orderedforcode->{$scancode}};
 9294:         } else {
 9295:             $env{'form.CODE'} = $scancode;
 9296:             my $actual_seq =
 9297:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9298:                                                                $master_seq,
 9299:                                                                $user,$scancode,1);
 9300:             if (ref($actual_seq) eq 'ARRAY') {
 9301:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9302:                 if (ref($orderedforcode) eq 'HASH') {
 9303:                     if (@mapresources > 0) { 
 9304:                         $orderedforcode->{$scancode} = \@mapresources;
 9305:                     }
 9306:                 }
 9307:             }
 9308:             delete($env{'form.CODE'});
 9309:         }
 9310:     } else {
 9311:         my $actual_seq =
 9312:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9313:                                                            $master_seq,
 9314:                                                            $user,undef,1);
 9315:         if (ref($actual_seq) eq 'ARRAY') {
 9316:             @mapresources = 
 9317:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9318:         }
 9319:     }
 9320:     return @mapresources;
 9321: }
 9322: 
 9323: sub grade_student_bubbles {
 9324:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9325:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9326:     my $uselookup = 0;
 9327:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9328:         (ref($startline) eq 'HASH')) {
 9329:         $uselookup = 1;
 9330:     }
 9331: 
 9332:     if (ref($resources) eq 'ARRAY') {
 9333:         my $count = 0;
 9334:         foreach my $resource (@{$resources}) {
 9335:             my $ressymb = $resource->symb();
 9336:             my %form = ('submitted'      => 'scantron',
 9337:                         'grade_target'   => 'grade',
 9338:                         'grade_username' => $uname,
 9339:                         'grade_domain'   => $udom,
 9340:                         'grade_courseid' => $env{'request.course.id'},
 9341:                         'grade_symb'     => $ressymb,
 9342:                         'CODE'           => $scancode
 9343:                        );
 9344:             if ($bubbles_per_row ne '') {
 9345:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9346:             }
 9347:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9348:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9349:             }
 9350:             if (ref($parts) eq 'HASH') {
 9351:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9352:                     foreach my $part (@{$parts->{$ressymb}}) {
 9353:                         if ($uselookup) {
 9354:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9355:                         } else {
 9356:                             $form{'scantron_questnum_start.'.$part} =
 9357:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9358:                         }
 9359:                         $count++;
 9360:                     }
 9361:                 }
 9362:             }
 9363:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9364:             return 'ssi_error' if ($ssi_error);
 9365:             last if (&Apache::loncommon::connection_aborted($r));
 9366:         }
 9367:     }
 9368:     return;
 9369: }
 9370: 
 9371: sub scantron_upload_scantron_data {
 9372:     my ($r,$symb) = @_;
 9373:     my $dom = $env{'request.role.domain'};
 9374:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9375:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9376:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9377:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9378: 							  'domainid',
 9379: 							  'coursename',$dom);
 9380:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9381:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9382:     my $default_form_data=&defaultFormData($symb);
 9383:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9384:     &js_escape(\$nofile_alert);
 9385:     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.");
 9386:     &js_escape(\$nocourseid_alert);
 9387:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9388:     function checkUpload(formname) {
 9389: 	if (formname.upfile.value == "") {
 9390: 	    alert("'.$nofile_alert.'");
 9391: 	    return false;
 9392: 	}
 9393:         if (formname.courseid.value == "") {
 9394:             alert("'.$nocourseid_alert.'");
 9395:             return false;
 9396:         }
 9397: 	formname.submit();
 9398:     }
 9399: 
 9400:     function ToSyllabus() {
 9401:         var cdom = '."'$dom'".';
 9402:         var cnum = document.rules.courseid.value;
 9403:         if (cdom == "" || cdom == null) {
 9404:             return;
 9405:         }
 9406:         if (cnum == "" || cnum == null) {
 9407:            return;
 9408:         }
 9409:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9410:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9411:         return;
 9412:     }
 9413: 
 9414:     '.$formatjs.'
 9415: '));
 9416:     $r->print('
 9417: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9418: 
 9419: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9420: '.$default_form_data.
 9421:   &Apache::lonhtmlcommon::start_pick_box().
 9422:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9423:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9424:   &Apache::lonhtmlcommon::row_closure().
 9425:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9426:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9427:   &Apache::lonhtmlcommon::row_closure().
 9428:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9429:   '<input name="domainid" type="hidden" />'.$domdesc.
 9430:   &Apache::lonhtmlcommon::row_closure());
 9431:     if ($formatoptions) {
 9432:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9433:                   &Apache::lonhtmlcommon::row_closure());
 9434:     }
 9435:     $r->print(
 9436:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9437:   '<input type="file" name="upfile" size="50" />'.
 9438:   &Apache::lonhtmlcommon::row_closure(1).
 9439:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9440: 
 9441: <input name="command" value="scantronupload_save" type="hidden" />
 9442: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9443: </form>
 9444: ');
 9445:     return '';
 9446: }
 9447: 
 9448: sub scantron_upload_dataformat {
 9449:     my ($dom) = @_;
 9450:     my ($formatoptions,$formattitle,$formatjs);
 9451:     $formatjs = <<'END';
 9452: function toggleScantab(form) {
 9453:    return;
 9454: }
 9455: END
 9456:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9457:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9458:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9459:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9460:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9461:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9462:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9463:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9464:                             my ($onclick,$formatextra,$singleline);
 9465:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9466:                             my $count = 0;
 9467:                             foreach my $line (@lines) {
 9468:                                 next if ($line =~ /^#/);
 9469:                                 $singleline = $line;
 9470:                                 $count ++;
 9471:                             }
 9472:                             if ($count > 1) {
 9473:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9474:                                                '<span class="LC_nobreak">'.
 9475:                                                &mt('Bubblesheet type').':&nbsp;'.
 9476:                                                &scantron_scantab().'</span></div>';
 9477:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9478:                                 $formatjs = <<"END";
 9479: function toggleScantab(form) {
 9480:     var divid = 'bubbletype';
 9481:     if (document.getElementById(divid)) {
 9482:         var radioname = 'fileformat';
 9483:         var num = form.elements[radioname].length;
 9484:         if (num) {
 9485:             for (var i=0; i<num; i++) {
 9486:                 if (form.elements[radioname][i].checked) {
 9487:                     var chosen = form.elements[radioname][i].value;
 9488:                     if (chosen == 'dat') {
 9489:                         document.getElementById(divid).style.display = 'none';
 9490:                     } else if (chosen == 'csv') {
 9491:                         document.getElementById(divid).style.display = 'block';
 9492:                     }
 9493:                 }
 9494:             }
 9495:         }
 9496:     }
 9497:     return;
 9498: }
 9499: 
 9500: END
 9501:                             } elsif ($count == 1) {
 9502:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9503:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9504:                             }
 9505:                             $formattitle = &mt('File format');
 9506:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9507:                                              &mt('Plain Text (no delimiters)').
 9508:                                              '</label>'.('&nbsp;'x2).
 9509:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9510:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9511:                         }
 9512:                     }
 9513:                 }
 9514:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9515:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9516:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9517:                         $formattitle = &mt('Bubblesheet type');
 9518:                         $formatoptions = &scantron_scantab();
 9519:                     }
 9520:                 }
 9521:             }
 9522:         }
 9523:     }
 9524:     return ($formatoptions,$formattitle,$formatjs);
 9525: }
 9526: 
 9527: sub scantron_upload_scantron_data_save {
 9528:     my ($r,$symb) = @_;
 9529:     my $doanotherupload=
 9530: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9531: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9532: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9533: 	'</form>'."\n";
 9534:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9535: 	!&Apache::lonnet::allowed('usc',
 9536: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9537:         !&Apache::lonnet::allowed('usc',
 9538:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9539: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9540: 	unless ($symb) {
 9541: 	    $r->print($doanotherupload);
 9542: 	}
 9543: 	return '';
 9544:     }
 9545:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9546:     my $uploadedfile;
 9547:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9548:     if (length($env{'form.upfile'}) < 2) {
 9549:         $r->print(
 9550:             &Apache::lonhtmlcommon::confirm_success(
 9551:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9552:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9553:     } else {
 9554:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9555:         my $parser;
 9556:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9557:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9558:                 my $is_csv;
 9559:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9560:                 if (@possibles > 1) {
 9561:                     if ($env{'form.fileformat'} eq 'csv') {
 9562:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9563:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9564:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9565:                                     $is_csv = 1;
 9566:                                 }
 9567:                             }
 9568:                         }
 9569:                     }
 9570:                 } elsif (@possibles == 1) {
 9571:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9572:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9573:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9574:                                 $is_csv = 1;
 9575:                             }
 9576:                         }
 9577:                     }
 9578:                 }
 9579:                 if ($is_csv) {
 9580:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9581:                 }
 9582:             }
 9583:         }
 9584:         my $result =
 9585:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9586:                                             $env{'form.courseid'},$env{'form.domainid'});
 9587:         if ($result =~ m{^/uploaded/}) {
 9588:             $r->print(
 9589:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9590:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9591:                         (length($env{'form.upfile'})-1),
 9592:                         '<span class="LC_filename">'.$result.'</span>'));
 9593:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9594:             if ($uploadedfile =~ /^scantron_orig_/) {
 9595:                 my $logname = $uploadedfile;
 9596:                 $logname =~ s/^scantron_orig_//;
 9597:                 if ($logname ne '') {
 9598:                     my $now = time;
 9599:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9600:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9601:                 }
 9602:             }
 9603:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9604:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9605:         } else {
 9606:             $r->print(
 9607:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9608:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9609:                           $result,
 9610: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9611: 	}
 9612:     }
 9613:     if ($symb) {
 9614: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9615:     } else {
 9616: 	$r->print($doanotherupload);
 9617:     }
 9618:     return '';
 9619: }
 9620: 
 9621: sub validate_uploaded_scantron_file {
 9622:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9623: 
 9624:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9625:     my @lines;
 9626:     if ($scanlines ne '-1') {
 9627:         @lines=split("\n",$scanlines,-1);
 9628:     }
 9629:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9630:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9631:     if ($context eq 'download') {
 9632:         $priv = 'mgr';
 9633:     } else {
 9634:         $priv = 'usc';
 9635:     }
 9636:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9637:             (($env{'request.course.id'}) &&
 9638:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9639:         if ($env{'request.course.sec'} ne '') {
 9640:             unless (&Apache::lonnet::allowed($priv,
 9641:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9642:                 unless ($context eq 'download') {
 9643:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9644:                 }
 9645:                 return $output;
 9646:             }
 9647:             ($checksec,@possibles)=&gradable_sections();
 9648:         }
 9649:     }
 9650:     if (@lines) {
 9651:         my (%counts,$max_match_format);
 9652:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9653:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9654:         my %idmap = &username_to_idmap($classlist);
 9655:         foreach my $key (keys(%idmap)) {
 9656:             my $lckey = lc($key);
 9657:             $idmap{$lckey} = $idmap{$key};
 9658:         }
 9659:         my %unique_formats;
 9660:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9661:         foreach my $line (@formatlines) {
 9662:             chomp($line);
 9663:             my @config = split(/:/,$line);
 9664:             my $idstart = $config[5];
 9665:             my $idlength = $config[6];
 9666:             if (($idstart ne '') && ($idlength > 0)) {
 9667:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9668:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9669:                 } else {
 9670:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9671:                 }
 9672:             }
 9673:         }
 9674:         foreach my $key (keys(%unique_formats)) {
 9675:             my ($idstart,$idlength) = split(':',$key);
 9676:             %{$counts{$key}} = (
 9677:                                'found'   => 0,
 9678:                                'total'   => 0,
 9679:                                'totalanysec' => 0,
 9680:                                'othersec' => 0,
 9681:                               );
 9682:             foreach my $line (@lines) {
 9683:                 next if ($line =~ /^#/);
 9684:                 next if ($line =~ /^[\s\cz]*$/);
 9685:                 my $id = substr($line,$idstart-1,$idlength);
 9686:                 $id = lc($id);
 9687:                 if (exists($idmap{$id})) {
 9688:                     if ($checksec ne '') {
 9689:                         $counts{$key}{'totalanysec'} ++;
 9690:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9691:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9692:                             if ($stusec ne $checksec) {
 9693:                                 if (@possibles) {
 9694:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9695:                                         $counts{$key}{'othersec'} ++;
 9696:                                         next;
 9697:                                     }
 9698:                                 } else {
 9699:                                     $counts{$key}{'othersec'} ++;
 9700:                                     next;
 9701:                                 }
 9702:                             }
 9703:                         }
 9704:                     }
 9705:                     $counts{$key}{'found'} ++;
 9706:                 }
 9707:                 $counts{$key}{'total'} ++;
 9708:             }
 9709:             if ($counts{$key}{'total'}) {
 9710:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9711:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9712:                     $max_match_pct = $percent_match;
 9713:                     $max_match_format = $key;
 9714:                     $found_match_count = $counts{$key}{'found'};
 9715:                     $max_match_count = $counts{$key}{'total'};
 9716:                 }
 9717:             }
 9718:         }
 9719:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9720:             my $format_descs;
 9721:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9722:             for (my $i=0; $i<$numwithformat; $i++) {
 9723:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9724:                 if ($i<$numwithformat-2) {
 9725:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9726:                 } elsif ($i==$numwithformat-2) {
 9727:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9728:                 } elsif ($i==$numwithformat-1) {
 9729:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9730:                 }
 9731:             }
 9732:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9733:             $output .= '<br />';
 9734:             if ($found_match_count == $max_match_count) {
 9735:                 # 100% matching entries
 9736:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9737:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9738:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9739:                 &mt('Comparison of student IDs in the uploaded file with'.
 9740:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9741:                     ' in the file (for the format defined for [_3]).',
 9742:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9743:             } else {
 9744:                 # Not all entries matching? -> Show warning and additional info
 9745:                 $output .=
 9746:                     &Apache::lonhtmlcommon::confirm_success(
 9747:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9748:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9749:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9750:                     &mt('Comparison of student IDs in the uploaded file with'.
 9751:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9752:                         ' in the file (for the format defined for [_3]).',
 9753:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9754:                     '<p class="LC_info">'.
 9755:                     &mt('A low percentage of matches results from one of the following:').
 9756:                     '</p><ul>'.
 9757:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9758:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9759:                                '<i>'.$cdom.'</i>').'</li>'.
 9760:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9761:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9762:                     '</ul>';
 9763:             }
 9764:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9765:                 if ($counts{$max_match_format}{'othersec'}) {
 9766:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9767:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9768:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9769:                     &js_escape(\$confirmdel);
 9770:                     $output .= '<p class="LC_warning">'.
 9771:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
 9772:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9773:                                '<br />'.
 9774:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
 9775:                                '</p><p>'.
 9776:                                &mt('If you prefer to delete the file now, use: [_1]').
 9777:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9778:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9779:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9780:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9781:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9782:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9783:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9784:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9785:                                '</form></p>';
 9786:                 }
 9787:             }
 9788:         }
 9789:         if (($context eq 'download') && ($checksec ne '')) {
 9790:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9791:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9792:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9793:             }
 9794:         } 
 9795:     } elsif ($context ne 'download') {
 9796:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9797:     }
 9798:     return $output;
 9799: }
 9800: 
 9801: sub gradable_sections {
 9802:     my $checksec = $env{'request.course.sec'};
 9803:     my @oksecs;
 9804:     if ($checksec) {
 9805:         my %availablesecs = &sections_grade_privs();
 9806:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9807:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9808:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9809:                     push(@oksecs,$sec);
 9810:                 }
 9811:             }
 9812:             if (grep(/^all$/,@oksecs)) {
 9813:                 undef($checksec);
 9814:             }
 9815:         }
 9816:     }
 9817:     return($checksec,@oksecs);
 9818: }
 9819: 
 9820: sub sections_grade_privs {
 9821:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9822:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9823:     my %availablesecs = (
 9824:                           mgr => [],
 9825:                           vgr => [],
 9826:                           usc => [],
 9827:                         );
 9828:     my $ccrole = 'cc';
 9829:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9830:         $ccrole = 'co';
 9831:     }
 9832:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9833:                                                      'userroles',['active'],
 9834:                                                      [$ccrole,'in','cr'],$cdom,1);
 9835:     my $crsid = $cnum.':'.$cdom;
 9836:     foreach my $item (keys(%crsroleshash)) {
 9837:         next unless ($item =~ /^$crsid\:/);
 9838:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9839:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9840:         if ($sec ne '') {
 9841:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9842:         }
 9843:         if (($role eq $ccrole) || ($role eq 'in')) {
 9844:             foreach my $priv ('mgr','vgr','usc') { 
 9845:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9846:                     if ($sec eq '') {
 9847:                         $availablesecs{$priv} = ['all'];
 9848:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9849:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9850:                             push(@{$availablesecs{$priv}},$sec);
 9851:                         }
 9852:                     }
 9853:                 }
 9854:             }
 9855:         } elsif ($role =~ m{^cr/}) {
 9856:             foreach my $priv ('mgr','vgr','usc') {
 9857:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9858:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9859:                         if ($sec eq '') {
 9860:                             $availablesecs{$priv} = ['all'];
 9861:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9862:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9863:                                 push(@{$availablesecs{$priv}},$sec);
 9864:                             }
 9865:                         }
 9866:                     }
 9867:                 }
 9868:             }
 9869:         }
 9870:     }
 9871:     return %availablesecs;
 9872: }
 9873: 
 9874: sub scantron_upload_delete {
 9875:     my ($r,$symb) = @_;
 9876:     my $filename = $env{'form.uploadedfile'};
 9877:     if ($filename =~ /^scantron_orig_/) {
 9878:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9879:             &Apache::lonnet::allowed('usc',
 9880:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9881:             &Apache::lonnet::allowed('usc',
 9882:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9883:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9884:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9885:             if ($retrieval eq '-1') {
 9886:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9887:                           &mt('File requested for deletion not found.'));
 9888:             } else {
 9889:                 $filename =~ s/^scantron_orig_//;
 9890:                 if ($filename ne '') {
 9891:                     my ($is_valid,$numleft);
 9892:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9893:                     if (keys(%info)) {
 9894:                         if (ref($info{$filename}) eq 'HASH') {
 9895:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9896:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9897:                                     $is_valid = 1;
 9898:                                     delete($info{$filename}{$timestamp}); 
 9899:                                 }
 9900:                             }
 9901:                             $numleft = scalar(keys(%{$info{$filename}}));
 9902:                         }
 9903:                     }
 9904:                     if ($is_valid) {
 9905:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
 9906:                         if ($result eq 'ok') {
 9907:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
 9908:                             if ($numleft) {
 9909:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9910:                             } else {
 9911:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9912:                             }
 9913:                         } else {
 9914:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9915:                                       &mt('Result was [_1]',$result));
 9916:                         }
 9917:                     } else {
 9918:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9919:                                   &mt('File requested for deletion was uploaded by a different user.'));
 9920:                     }
 9921:                 } else {
 9922:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9923:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9924:                 }
 9925:             }
 9926:         } else {
 9927:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
 9928:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
 9929:         }
 9930:     } else {
 9931:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9932:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9933:     }
 9934:     return;
 9935: }
 9936: 
 9937: sub valid_file {
 9938:     my ($requested_file)=@_;
 9939:     foreach my $filename (sort(&scantron_filenames())) {
 9940: 	if ($requested_file eq $filename) { return 1; }
 9941:     }
 9942:     return 0;
 9943: }
 9944: 
 9945: sub scantron_download_scantron_data {
 9946:     my ($r,$symb) = @_;
 9947:     my $default_form_data=&defaultFormData($symb);
 9948:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9949:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9950:     my $file=$env{'form.scantron_selectfile'};
 9951:     if (! &valid_file($file)) {
 9952: 	$r->print('
 9953: 	<p>
 9954: 	    '.&mt('The requested filename was invalid.').'
 9955:         </p>
 9956: ');
 9957: 	return;
 9958:     }
 9959:     my (%uploader,$is_owner,%counts,$percent);
 9960:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
 9961:     if (ref($uploader{$file}) eq 'HASH') {
 9962:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
 9963:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9964:                 $is_owner = 1;
 9965:                 last;
 9966:             }
 9967:         }
 9968:     }
 9969:     unless ($is_owner) {
 9970:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
 9971:         if ($counts{'totalanysec'}) {
 9972:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
 9973:             if ($percent_othersec >= 10) {
 9974:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
 9975:                 $r->print('<p class="LC_warning">'.
 9976:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
 9977:                           '</p>');
 9978:                 return;
 9979:             }
 9980:         }
 9981:     }
 9982:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9983:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9984:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9985:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9986:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9987:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9988:     $r->print('
 9989:     <p>
 9990: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9991: 	      '<a href="'.$orig.'">','</a>').'
 9992:     </p>
 9993:     <p>
 9994: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9995: 	      '<a href="'.$corrected.'">','</a>').'
 9996:     </p>
 9997:     <p>
 9998: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9999: 	      '<a href="'.$skipped.'">','</a>').'
10000:     </p>
10001: ');
10002:     return '';
10003: }
10004: 
10005: sub checkscantron_results {
10006:     my ($r,$symb) = @_;
10007:     if (!$symb) {return '';}
10008:     my $cid = $env{'request.course.id'};
10009:     my %lettdig = &Apache::lonnet::letter_to_digits();
10010:     my $numletts = scalar(keys(%lettdig));
10011:     my $cnum = $env{'course.'.$cid.'.num'};
10012:     my $cdom = $env{'course.'.$cid.'.domain'};
10013:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10014:     my %record;
10015:     my %scantron_config =
10016:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10017:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10018:     my ($scanlines,$scan_data)=&scantron_getfile();
10019:     my $classlist=&Apache::loncoursedata::get_classlist();
10020:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10021:     my $navmap=Apache::lonnavmaps::navmap->new();
10022:     unless (ref($navmap)) {
10023:         $r->print(&navmap_errormsg());
10024:         return '';
10025:     }
10026:     my $map=$navmap->getResourceByUrl($sequence);
10027:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10028:         %grader_randomlists_by_symb,%orderedforcode);
10029:     if (ref($map)) { 
10030:         $randomorder=$map->randomorder();
10031:         $randompick=$map->randompick();
10032:     }
10033:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10034:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10035:     if ($nav_error) {
10036:         $r->print(&navmap_errormsg());
10037:         return '';
10038:     }
10039:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10040:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10041:     my ($uname,$udom);
10042:     my (%scandata,%lastname,%bylast);
10043:     $r->print('
10044: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10045: 
10046:     my @delayqueue;
10047:     my %completedstudents;
10048: 
10049:     my $count=&get_todo_count($scanlines,$scan_data);
10050:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10051:     my ($username,$domain,$started);
10052:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10053:     if ($nav_error) {
10054:         $r->print(&navmap_errormsg());
10055:         return '';
10056:     }
10057: 
10058:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10059:     my $start=&Time::HiRes::time();
10060:     my $i=-1;
10061: 
10062:     while ($i<$scanlines->{'count'}) {
10063:         ($username,$domain,$uname)=('','','');
10064:         $i++;
10065:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10066:         if ($line=~/^[\s\cz]*$/) { next; }
10067:         if ($started) {
10068:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10069:         }
10070:         $started=1;
10071:         my $scan_record=
10072:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10073:                                                      $scan_data);
10074:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10075:                                               \%idmap,$i)) {
10076:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10077:                                 'Unable to find a student that matches',1);
10078:             next;
10079:         }
10080:         if (exists $completedstudents{$uname}) {
10081:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10082:                                 'Student '.$uname.' has multiple sheets',2);
10083:             next;
10084:         }
10085:         my $pid = $scan_record->{'scantron.ID'};
10086:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10087:         push(@{$bylast{$lastname{$pid}}},$pid);
10088:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10089:         my $user = $uname.':'.$usec;
10090:         ($username,$domain)=split(/:/,$uname);
10091: 
10092:         my $scancode;
10093:         if ((exists($scan_record->{'scantron.CODE'})) &&
10094:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10095:             $scancode = $scan_record->{'scantron.CODE'};
10096:         } else {
10097:             $scancode = '';
10098:         }
10099: 
10100:         my @mapresources = @resources;
10101:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10102:         my %respnumlookup=();
10103:         my %startline=();
10104:         if ($randomorder || $randompick) {
10105:             @mapresources =
10106:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10107:                              \%orderedforcode);
10108:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10109:                                              $scan_record,\@master_seq,\%symb_to_resource,
10110:                                              \%grader_partids_by_symb,\%orderedforcode,
10111:                                              \%respnumlookup,\%startline);
10112:             if ($randompick && $total) {
10113:                 $lastpos = $total*$scantron_config{'Qlength'};
10114:             }
10115:         }
10116:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10117:         chomp($scandata{$pid});
10118:         $scandata{$pid} =~ s/\r$//;
10119: 
10120:         my $counter = -1;
10121:         foreach my $resource (@mapresources) {
10122:             my $parts;
10123:             my $ressymb = $resource->symb();
10124:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10125:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10126:                 my $currcode;
10127:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10128:                     $currcode = $scancode;
10129:                 }
10130:                 (my $analysis,$parts) =
10131:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10132:                                               $username,$domain,undef,
10133:                                               $bubbles_per_row,$currcode);
10134:             } else {
10135:                 $parts = $grader_partids_by_symb{$ressymb};
10136:             }
10137:             ($counter,my $recording) =
10138:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10139:                                          $scandata{$pid},$parts,
10140:                                          \%scantron_config,\%lettdig,$numletts,
10141:                                          $randomorder,$randompick,
10142:                                          \%respnumlookup,\%startline);
10143:             $record{$pid} .= $recording;
10144:         }
10145:     }
10146:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10147:     $r->print('<br />');
10148:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10149:     $passed = 0;
10150:     $failed = 0;
10151:     $numstudents = 0;
10152:     foreach my $last (sort(keys(%bylast))) {
10153:         if (ref($bylast{$last}) eq 'ARRAY') {
10154:             foreach my $pid (sort(@{$bylast{$last}})) {
10155:                 my $showscandata = $scandata{$pid};
10156:                 my $showrecord = $record{$pid};
10157:                 $showscandata =~ s/\s/&nbsp;/g;
10158:                 $showrecord =~ s/\s/&nbsp;/g;
10159:                 if ($scandata{$pid} eq $record{$pid}) {
10160:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10161:                     $okstudents .= '<tr class="'.$css_class.'">'.
10162: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10163: '</tr>'."\n".
10164: '<tr class="'.$css_class.'">'."\n".
10165: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10166:                     $passed ++;
10167:                 } else {
10168:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10169:                     $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".
10170: '</tr>'."\n".
10171: '<tr class="'.$css_class.'">'."\n".
10172: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10173: '</tr>'."\n";
10174:                     $failed ++;
10175:                 }
10176:                 $numstudents ++;
10177:             }
10178:         }
10179:     }
10180:     $r->print(
10181:         '<p>'
10182:        .&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).',
10183:             '<b>',
10184:             $numstudents,
10185:             '</b>',
10186:             $env{'form.scantron_maxbubble'})
10187:        .'</p>'
10188:     );
10189:     $r->print('<p>'
10190:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10191:              .'<br />'
10192:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10193:              .'</p>'
10194:     );
10195:     if ($passed) {
10196:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10197:         $r->print(&Apache::loncommon::start_data_table()."\n".
10198:                  &Apache::loncommon::start_data_table_header_row()."\n".
10199:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10200:                  &Apache::loncommon::end_data_table_header_row()."\n".
10201:                  $okstudents."\n".
10202:                  &Apache::loncommon::end_data_table().'<br />');
10203:     }
10204:     if ($failed) {
10205:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10206:         $r->print(&Apache::loncommon::start_data_table()."\n".
10207:                  &Apache::loncommon::start_data_table_header_row()."\n".
10208:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10209:                  &Apache::loncommon::end_data_table_header_row()."\n".
10210:                  $badstudents."\n".
10211:                  &Apache::loncommon::end_data_table()).'<br />'.
10212:                  &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.');  
10213:     }
10214:     $r->print('</form><br />');
10215:     return;
10216: }
10217: 
10218: sub verify_scantron_grading {
10219:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10220:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10221:         $respnumlookup,$startline) = @_;
10222:     my ($record,%expected,%startpos);
10223:     return ($counter,$record) if (!ref($resource));
10224:     return ($counter,$record) if (!$resource->is_problem());
10225:     my $symb = $resource->symb();
10226:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10227:     foreach my $part_id (@{$partids}) {
10228:         $counter ++;
10229:         $expected{$part_id} = 0;
10230:         my $respnum = $counter;
10231:         if ($randomorder || $randompick) {
10232:             $respnum = $respnumlookup->{$counter};
10233:             $startpos{$part_id} = $startline->{$counter} + 1;
10234:         } else {
10235:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10236:         }
10237:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10238:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10239:             foreach my $item (@sub_lines) {
10240:                 $expected{$part_id} += $item;
10241:             }
10242:         } else {
10243:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10244:         }
10245:     }
10246:     if ($symb) {
10247:         my %recorded;
10248:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10249:         if ($returnhash{'version'}) {
10250:             my %lasthash=();
10251:             my $version;
10252:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10253:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10254:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10255:                 }
10256:             }
10257:             foreach my $key (keys(%lasthash)) {
10258:                 if ($key =~ /\.scantron$/) {
10259:                     my $value = &unescape($lasthash{$key});
10260:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10261:                     if ($value eq '') {
10262:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10263:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10264:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10265:                             }
10266:                         }
10267:                     } else {
10268:                         my @tocheck;
10269:                         my @items = split(//,$value);
10270:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10271:                             ($scantron_config->{'Qon'} eq 'number')) {
10272:                             if (@items < $expected{$part_id}) {
10273:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10274:                                 my @singles = split(//,$fragment);
10275:                                 foreach my $pos (@singles) {
10276:                                     if ($pos eq ' ') {
10277:                                         push(@tocheck,$pos);
10278:                                     } else {
10279:                                         my $next = shift(@items);
10280:                                         push(@tocheck,$next);
10281:                                     }
10282:                                 }
10283:                             } else {
10284:                                 @tocheck = @items;
10285:                             }
10286:                             foreach my $letter (@tocheck) {
10287:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10288:                                     if ($letter !~ /^[A-J]$/) {
10289:                                         $letter = $scantron_config->{'Qoff'};
10290:                                     }
10291:                                     $recorded{$part_id} .= $letter;
10292:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10293:                                     my $digit;
10294:                                     if ($letter !~ /^[A-J]$/) {
10295:                                         $digit = $scantron_config->{'Qoff'};
10296:                                     } else {
10297:                                         $digit = $lettdig->{$letter};
10298:                                     }
10299:                                     $recorded{$part_id} .= $digit;
10300:                                 }
10301:                             }
10302:                         } else {
10303:                             @tocheck = @items;
10304:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10305:                                 my $curr_sub = shift(@tocheck);
10306:                                 my $digit;
10307:                                 if ($curr_sub =~ /^[A-J]$/) {
10308:                                     $digit = $lettdig->{$curr_sub}-1;
10309:                                 }
10310:                                 if ($curr_sub eq 'J') {
10311:                                     $digit += scalar($numletts);
10312:                                 }
10313:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10314:                                     if ($j == $digit) {
10315:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10316:                                     } else {
10317:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10318:                                     }
10319:                                 }
10320:                             }
10321:                         }
10322:                     }
10323:                 }
10324:             }
10325:         }
10326:         foreach my $part_id (@{$partids}) {
10327:             if ($recorded{$part_id} eq '') {
10328:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10329:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10330:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10331:                     }
10332:                 }
10333:             }
10334:             $record .= $recorded{$part_id};
10335:         }
10336:     }
10337:     return ($counter,$record);
10338: }
10339: 
10340: #-------- end of section for handling grading scantron forms -------
10341: #
10342: #-------------------------------------------------------------------
10343: 
10344: #-------------------------- Menu interface -------------------------
10345: #
10346: #--- Href with symb and command ---
10347: 
10348: sub href_symb_cmd {
10349:     my ($symb,$cmd)=@_;
10350:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10351: }
10352: 
10353: sub grading_menu {
10354:     my ($request,$symb) = @_;
10355:     if (!$symb) {return '';}
10356: 
10357:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10358:                   'command'=>'individual');
10359:     
10360:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10361: 
10362:     $fields{'command'}='ungraded';
10363:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10364: 
10365:     $fields{'command'}='table';
10366:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10367: 
10368:     $fields{'command'}='all_for_one';
10369:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10370: 
10371:     $fields{'command'}='downloadfilesselect';
10372:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10373: 
10374:     $fields{'command'} = 'csvform';
10375:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10376:     
10377:     $fields{'command'} = 'processclicker';
10378:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10379:     
10380:     $fields{'command'} = 'scantron_selectphase';
10381:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10382: 
10383:     $fields{'command'} = 'initialverifyreceipt';
10384:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10385:     
10386:     my @menu = ({	categorytitle=>'Hand Grading',
10387:             items =>[
10388:                         {	linktext => 'Select individual students to grade',
10389:                     		url => $url1a,
10390:                     		permission => 'F',
10391:                     		icon => 'grade_students.png',
10392:                     		linktitle => 'Grade current resource for a selection of students.'
10393:                         }, 
10394:                         {       linktext => 'Grade ungraded submissions',
10395:                                 url => $url1b,
10396:                                 permission => 'F',
10397:                                 icon => 'ungrade_sub.png',
10398:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10399:                         },
10400: 
10401:                         {       linktext => 'Grading table',
10402:                                 url => $url1c,
10403:                                 permission => 'F',
10404:                                 icon => 'grading_table.png',
10405:                                 linktitle => 'Grade current resource for all students.'
10406:                         },
10407:                         {       linktext => 'Grade page/folder for one student',
10408:                                 url => $url1d,
10409:                                 permission => 'F',
10410:                                 icon => 'grade_PageFolder.png',
10411:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10412:                         },
10413:                         {       linktext => 'Download submissions',
10414:                                 url => $url1e,
10415:                                 permission => 'F',
10416:                                 icon => 'download_sub.png',
10417:                                 linktitle => 'Download all students submissions.'
10418:                         }]},
10419:                          { categorytitle=>'Automated Grading',
10420:                items =>[
10421: 
10422:                 	    {	linktext => 'Upload Scores',
10423:                     		url => $url2,
10424:                     		permission => 'F',
10425:                     		icon => 'uploadscores.png',
10426:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10427:                 	    },
10428:                 	    {	linktext => 'Process Clicker',
10429:                     		url => $url3,
10430:                     		permission => 'F',
10431:                     		icon => 'addClickerInfoFile.png',
10432:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10433:                 	    },
10434:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10435:                     		url => $url4,
10436:                     		permission => 'F',
10437:                     		icon => 'bubblesheet.png',
10438:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10439:                 	    },
10440:                             {   linktext => 'Verify Receipt Number',
10441:                                 url => $url5,
10442:                                 permission => 'F',
10443:                                 icon => 'receipt_number.png',
10444:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10445:                             }
10446: 
10447:                     ]
10448:             });
10449: 
10450:     # Create the menu
10451:     my $Str;
10452:     $Str .= '<form method="post" action="" name="gradingMenu">';
10453:     $Str .= '<input type="hidden" name="command" value="" />'.
10454:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10455: 
10456:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10457:     return $Str;    
10458: }
10459: 
10460: sub ungraded {
10461:     my ($request)=@_;
10462:     &submit_options($request);
10463: }
10464: 
10465: sub submit_options_sequence {
10466:     my ($request,$symb) = @_;
10467:     if (!$symb) {return '';}
10468:     &commonJSfunctions($request);
10469:     my $result;
10470: 
10471:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10472:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10473:     $result.=&selectfield(0).
10474:             '<input type="hidden" name="command" value="pickStudentPage" />
10475:             <div>
10476:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10477:             </div>
10478:         </div>
10479:   </form>';
10480:     return $result;
10481: }
10482: 
10483: sub submit_options_table {
10484:     my ($request,$symb) = @_;
10485:     if (!$symb) {return '';}
10486:     &commonJSfunctions($request);
10487:     my $is_tool = ($symb =~ /ext\.tool$/);
10488:     my $result;
10489: 
10490:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10491:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10492: 
10493:     $result.=&selectfield(1,$is_tool).
10494:             '<input type="hidden" name="command" value="viewgrades" />
10495:             <div>
10496:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10497:             </div>
10498:         </div>
10499:   </form>';
10500:     return $result;
10501: }
10502: 
10503: sub submit_options_download {
10504:     my ($request,$symb) = @_;
10505:     if (!$symb) {return '';}
10506: 
10507:     my $res_error;
10508:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10509:         &response_type($symb,\$res_error);
10510:     if ($res_error) {
10511:         $request->print(&mt('An error occurred retrieving response types'));
10512:         return;
10513:     }
10514:     unless ($numessay) {
10515:         $request->print(&mt('No essayresponse items found'));
10516:         return;
10517:     }
10518:     my $table;
10519:     if (ref($partlist) eq 'ARRAY') {
10520:         if (scalar(@$partlist) > 1 ) {
10521:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10522:         }
10523:     }
10524: 
10525:     my $is_tool = ($symb =~ /ext\.tool$/);
10526:     &commonJSfunctions($request);
10527: 
10528:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10529:                $table."\n".
10530:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10531:     $result.='
10532: <h2>
10533:   '.&mt('Select Students for whom to Download Submissions').'
10534: </h2>'.&selectfield(1,$is_tool).'
10535:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10536:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10537:             </div>
10538:           </div>
10539: 
10540: 
10541:   </form>';
10542:     return $result;
10543: }
10544: 
10545: #--- Displays the submissions first page -------
10546: sub submit_options {
10547:     my ($request,$symb) = @_;
10548:     if (!$symb) {return '';}
10549: 
10550:     my $is_tool = ($symb =~ /ext\.tool$/);
10551:     &commonJSfunctions($request);
10552:     my $result;
10553: 
10554:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10555: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10556:     $result.=&selectfield(1,$is_tool).'
10557:                 <input type="hidden" name="command" value="submission" /> 
10558: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10559:             </div>
10560:           </div>
10561:   </form>';
10562:     return $result;
10563: }
10564: 
10565: sub selectfield {
10566:    my ($full,$is_tool)=@_;
10567:    my %options;
10568:    if ($is_tool) {
10569:        %options =
10570:            (&transtatus_options,
10571:             'select_form_order' => ['yes','incorrect','all']);
10572:    } else {
10573:        %options = 
10574:            (&substatus_options,
10575:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10576:    }
10577:    my $result='<div class="LC_columnSection">
10578:   
10579:     <fieldset>
10580:       <legend>
10581:        '.&mt('Sections').'
10582:       </legend>
10583:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10584:     </fieldset>
10585:   
10586:     <fieldset>
10587:       <legend>
10588:         '.&mt('Groups').'
10589:       </legend>
10590:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10591:     </fieldset>
10592:   
10593:     <fieldset>
10594:       <legend>
10595:         '.&mt('Access Status').'
10596:       </legend>
10597:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10598:     </fieldset>';
10599:     if ($full) {
10600:         my $heading = &mt('Submission Status');
10601:         if ($is_tool) {
10602:             $heading = &mt('Transaction Status');
10603:         }
10604:         $result.='
10605:     <fieldset>
10606:       <legend>
10607:         '.$heading.'
10608:       </legend>'.
10609:        &Apache::loncommon::select_form('all','submitonly',\%options).
10610:    '</fieldset>';
10611:     }
10612:     $result.='</div><br />';
10613:     return $result;
10614: }
10615: 
10616: sub substatus_options {
10617:     return &Apache::lonlocal::texthash(
10618:                                       'yes'       => 'with submissions',
10619:                                       'queued'    => 'in grading queue',
10620:                                       'graded'    => 'with ungraded submissions',
10621:                                       'incorrect' => 'with incorrect submissions',
10622:                                       'all'       => 'with any status',
10623:                                       );
10624: }
10625: 
10626: sub transtatus_options {
10627:     return &Apache::lonlocal::texthash(
10628:                                        'yes'       => 'with score transactions',
10629:                                        'incorrect' => 'with less than full credit',
10630:                                        'all'       => 'with any status',
10631:                                       );
10632: }
10633: 
10634: sub reset_perm {
10635:     undef(%perm);
10636: }
10637: 
10638: sub init_perm {
10639:     &reset_perm();
10640:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10641: 
10642: 	my $scope = $env{'request.course.id'};
10643: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10644: 
10645: 	    $scope .= '/'.$env{'request.course.sec'};
10646: 	    if ( $perm{$test_perm}=
10647: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10648: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10649: 	    } else {
10650: 		delete($perm{$test_perm});
10651: 	    }
10652: 	}
10653:     }
10654: }
10655: 
10656: sub init_old_essays {
10657:     my ($symb,$apath,$adom,$aname) = @_;
10658:     if ($symb ne '') {
10659:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10660:         if (keys(%essays) > 0) {
10661:             $old_essays{$symb} = \%essays;
10662:         }
10663:     }
10664:     return;
10665: }
10666: 
10667: sub reset_old_essays {
10668:     undef(%old_essays);
10669: }
10670: 
10671: sub gather_clicker_ids {
10672:     my %clicker_ids;
10673: 
10674:     my $classlist = &Apache::loncoursedata::get_classlist();
10675: 
10676:     # Set up a couple variables.
10677:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10678:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10679:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10680: 
10681:     foreach my $student (keys(%$classlist)) {
10682:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10683:         my $username = $classlist->{$student}->[$username_idx];
10684:         my $domain   = $classlist->{$student}->[$domain_idx];
10685:         my $clickers =
10686: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10687:         foreach my $id (split(/\,/,$clickers)) {
10688:             $id=~s/^[\#0]+//;
10689:             $id=~s/[\-\:]//g;
10690:             if (exists($clicker_ids{$id})) {
10691: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10692:             } else {
10693: 		$clicker_ids{$id}=$username.':'.$domain;
10694:             }
10695:         }
10696:     }
10697:     return %clicker_ids;
10698: }
10699: 
10700: sub gather_adv_clicker_ids {
10701:     my %clicker_ids;
10702:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10703:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10704:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10705:     foreach my $element (sort(keys(%coursepersonnel))) {
10706:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10707:             my ($puname,$pudom)=split(/\:/,$person);
10708:             my $clickers =
10709: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10710:             foreach my $id (split(/\,/,$clickers)) {
10711: 		$id=~s/^[\#0]+//;
10712:                 $id=~s/[\-\:]//g;
10713: 		if (exists($clicker_ids{$id})) {
10714: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10715: 		} else {
10716: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10717: 		}
10718:             }
10719:         }
10720:     }
10721:     return %clicker_ids;
10722: }
10723: 
10724: sub clicker_grading_parameters {
10725:     return ('gradingmechanism' => 'scalar',
10726:             'upfiletype' => 'scalar',
10727:             'specificid' => 'scalar',
10728:             'pcorrect' => 'scalar',
10729:             'pincorrect' => 'scalar');
10730: }
10731: 
10732: sub process_clicker {
10733:     my ($r,$symb)=@_;
10734:     if (!$symb) {return '';}
10735:     my $result=&checkforfile_js();
10736:     $result.=&Apache::loncommon::start_data_table().
10737:              &Apache::loncommon::start_data_table_header_row().
10738:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10739:              &Apache::loncommon::end_data_table_header_row().
10740:              &Apache::loncommon::start_data_table_row()."<td>\n";
10741: # Attempt to restore parameters from last session, set defaults if not present
10742:     my %Saveable_Parameters=&clicker_grading_parameters();
10743:     &Apache::loncommon::restore_course_settings('grades_clicker',
10744:                                                  \%Saveable_Parameters);
10745:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10746:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10747:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10748:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10749: 
10750:     my %checked;
10751:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10752:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10753:           $checked{$gradingmechanism}=' checked="checked"';
10754:        }
10755:     }
10756: 
10757:     my $upload=&mt("Evaluate File");
10758:     my $type=&mt("Type");
10759:     my $attendance=&mt("Award points just for participation");
10760:     my $personnel=&mt("Correctness determined from response by course personnel");
10761:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10762:     my $given=&mt("Correctness determined from given list of answers").' '.
10763:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10764:     my $pcorrect=&mt("Percentage points for correct solution");
10765:     my $pincorrect=&mt("Percentage points for incorrect solution");
10766:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10767: 						   {'iclicker' => 'i>clicker',
10768:                                                     'interwrite' => 'interwrite PRS',
10769:                                                     'turning' => 'Turning Technologies'});
10770:     $symb = &Apache::lonenc::check_encrypt($symb);
10771:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10772: function sanitycheck() {
10773: // Accept only integer percentages
10774:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10775:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10776: // Find out grading choice
10777:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10778:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10779:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10780:       }
10781:    }
10782: // By default, new choice equals user selection
10783:    newgradingchoice=gradingchoice;
10784: // Not good to give more points for false answers than correct ones
10785:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10786:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10787:    }
10788: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10789:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10790:       document.forms.gradesupload.pcorrect.value=100;
10791:       document.forms.gradesupload.pincorrect.value=100;
10792:    }
10793: // If the values are different, cannot be attendance only
10794:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10795:        (gradingchoice=='attendance')) {
10796:        newgradingchoice='personnel';
10797:    }
10798: // Change grading choice to new one
10799:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10800:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10801:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10802:       } else {
10803:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10804:       }
10805:    }
10806: // Remember the old state
10807:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10808: }
10809: ENDUPFORM
10810:     $result.= <<ENDUPFORM;
10811: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10812: <input type="hidden" name="symb" value="$symb" />
10813: <input type="hidden" name="command" value="processclickerfile" />
10814: <input type="file" name="upfile" size="50" />
10815: <br /><label>$type: $selectform</label>
10816: ENDUPFORM
10817:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10818:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10819:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10820: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10821: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10822: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10823: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10824: <br />&nbsp;&nbsp;&nbsp;
10825: <input type="text" name="givenanswer" size="50" />
10826: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10827: ENDGRADINGFORM
10828:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10829:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10830:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10831: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10832: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10833: </form>
10834: ENDPERCFORM
10835:     $result.='</td>'.
10836:              &Apache::loncommon::end_data_table_row().
10837:              &Apache::loncommon::end_data_table();
10838:     return $result;
10839: }
10840: 
10841: sub process_clicker_file {
10842:     my ($r,$symb) = @_;
10843:     if (!$symb) {return '';}
10844: 
10845:     my %Saveable_Parameters=&clicker_grading_parameters();
10846:     &Apache::loncommon::store_course_settings('grades_clicker',
10847:                                               \%Saveable_Parameters);
10848:     my $result='';
10849:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10850: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10851: 	return $result;
10852:     }
10853:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10854:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10855:         return $result;
10856:     }
10857:     my $foundgiven=0;
10858:     if ($env{'form.gradingmechanism'} eq 'given') {
10859:         $env{'form.givenanswer'}=~s/^\s*//gs;
10860:         $env{'form.givenanswer'}=~s/\s*$//gs;
10861:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10862:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10863:         my @answers=split(/\,/,$env{'form.givenanswer'});
10864:         $foundgiven=$#answers+1;
10865:     }
10866:     my %clicker_ids=&gather_clicker_ids();
10867:     my %correct_ids;
10868:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10869: 	%correct_ids=&gather_adv_clicker_ids();
10870:     }
10871:     if ($env{'form.gradingmechanism'} eq 'specific') {
10872: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10873: 	   $correct_id=~tr/a-z/A-Z/;
10874: 	   $correct_id=~s/\s//gs;
10875: 	   $correct_id=~s/^[\#0]+//;
10876:            $correct_id=~s/[\-\:]//g;
10877:            if ($correct_id) {
10878: 	      $correct_ids{$correct_id}='specified';
10879:            }
10880:         }
10881:     }
10882:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10883: 	$result.=&mt('Score based on attendance only');
10884:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10885:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10886:     } else {
10887: 	my $number=0;
10888: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10889: 	foreach my $id (sort(keys(%correct_ids))) {
10890: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10891: 	    if ($correct_ids{$id} eq 'specified') {
10892: 		$result.=&mt('specified');
10893: 	    } else {
10894: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10895: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10896: 	    }
10897: 	    $number++;
10898: 	}
10899:         $result.="</p>\n";
10900:         if ($number==0) {
10901:             $result .=
10902:                  &Apache::lonhtmlcommon::confirm_success(
10903:                      &mt('No IDs found to determine correct answer'),1);
10904:             return $result;
10905:         }
10906:     }
10907:     if (length($env{'form.upfile'}) < 2) {
10908:         $result .=
10909:             &Apache::lonhtmlcommon::confirm_success(
10910:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10911:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10912:         return $result;
10913:     }
10914:     my $mimetype;
10915:     if ($env{'form.upfiletype'} eq 'iclicker') {
10916:         my $mm = new File::MMagic;
10917:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10918:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10919:             $result.= '<p>'.
10920:                 &Apache::lonhtmlcommon::confirm_success(
10921:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10922:             return $result;
10923:         }
10924:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10925:         $result .= '<p>'.
10926:             &Apache::lonhtmlcommon::confirm_success(
10927:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10928:         return $result;
10929:     }
10930: 
10931: # Were able to get all the info needed, now analyze the file
10932: 
10933:     $result.=&Apache::loncommon::studentbrowser_javascript();
10934:     $symb = &Apache::lonenc::check_encrypt($symb);
10935:     $result.=&Apache::loncommon::start_data_table().
10936:              &Apache::loncommon::start_data_table_header_row().
10937:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10938:              &Apache::loncommon::end_data_table_header_row().
10939:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10940: <td>
10941: <form method="post" action="/adm/grades" name="clickeranalysis">
10942: <input type="hidden" name="symb" value="$symb" />
10943: <input type="hidden" name="command" value="assignclickergrades" />
10944: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10945: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10946: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10947: ENDHEADER
10948:     if ($env{'form.gradingmechanism'} eq 'given') {
10949:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10950:     } 
10951:     my %responses;
10952:     my @questiontitles;
10953:     my $errormsg='';
10954:     my $number=0;
10955:     if ($env{'form.upfiletype'} eq 'iclicker') {
10956:         if ($mimetype eq 'text/plain') {
10957:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10958:         } elsif ($mimetype eq 'text/html') {
10959:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10960:         }
10961:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10962:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10963:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10964:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10965:     }
10966:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10967:              '<input type="hidden" name="number" value="'.$number.'" />'.
10968:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10969:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10970:              '<br />';
10971:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10972:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10973:        return $result;
10974:     } 
10975: # Remember Question Titles
10976: # FIXME: Possibly need delimiter other than ":"
10977:     for (my $i=0;$i<$number;$i++) {
10978:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10979:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10980:     }
10981:     my $correct_count=0;
10982:     my $student_count=0;
10983:     my $unknown_count=0;
10984: # Match answers with usernames
10985: # FIXME: Possibly need delimiter other than ":"
10986:     foreach my $id (keys(%responses)) {
10987:        if ($correct_ids{$id}) {
10988:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10989:           $correct_count++;
10990:        } elsif ($clicker_ids{$id}) {
10991:           if ($clicker_ids{$id}=~/\,/) {
10992: # More than one user with the same clicker!
10993:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10994:                            &Apache::loncommon::start_data_table_row()."<td>".
10995:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10996:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10997:                            "<select name='multi".$id."'>";
10998:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10999:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
11000:              }
11001:              $result.='</select>';
11002:              $unknown_count++;
11003:           } else {
11004: # Good: found one and only one user with the right clicker
11005:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
11006:              $student_count++;
11007:           }
11008:        } else {
11009:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11010:                            &Apache::loncommon::start_data_table_row()."<td>".
11011:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11012:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11013:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11014:                    "\n".&mt("Domain").": ".
11015:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11016:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11017:           $unknown_count++;
11018:        }
11019:     }
11020:     $result.='<hr />'.
11021:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11022:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11023:        if ($correct_count==0) {
11024:           $errormsg.="Found no correct answers for grading!";
11025:        } elsif ($correct_count>1) {
11026:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11027:        }
11028:     }
11029:     if ($number<1) {
11030:        $errormsg.="Found no questions.";
11031:     }
11032:     if ($errormsg) {
11033:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11034:     } else {
11035:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11036:     }
11037:     $result.='</form></td>'.
11038:              &Apache::loncommon::end_data_table_row().
11039:              &Apache::loncommon::end_data_table();
11040:     return $result;
11041: }
11042: 
11043: sub iclicker_eval {
11044:     my ($questiontitles,$responses)=@_;
11045:     my $number=0;
11046:     my $errormsg='';
11047:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11048:         my %components=&Apache::loncommon::record_sep($line);
11049:         my @entries=map {$components{$_}} (sort(keys(%components)));
11050: 	if ($entries[0] eq 'Question') {
11051: 	    for (my $i=3;$i<$#entries;$i+=6) {
11052: 		$$questiontitles[$number]=$entries[$i];
11053: 		$number++;
11054: 	    }
11055: 	}
11056: 	if ($entries[0]=~/^\#/) {
11057: 	    my $id=$entries[0];
11058: 	    my @idresponses;
11059: 	    $id=~s/^[\#0]+//;
11060: 	    for (my $i=0;$i<$number;$i++) {
11061: 		my $idx=3+$i*6;
11062:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11063: 		push(@idresponses,$entries[$idx]);
11064: 	    }
11065: 	    $$responses{$id}=join(',',@idresponses);
11066: 	}
11067:     }
11068:     return ($errormsg,$number);
11069: }
11070: 
11071: sub iclickerxml_eval {
11072:     my ($questiontitles,$responses)=@_;
11073:     my $number=0;
11074:     my $errormsg='';
11075:     my @state;
11076:     my %respbyid;
11077:     my $p = HTML::Parser->new
11078:     (
11079:         xml_mode => 1,
11080:         start_h =>
11081:             [sub {
11082:                  my ($tagname,$attr) = @_;
11083:                  push(@state,$tagname);
11084:                  if ("@state" eq "ssn p") {
11085:                      my $title = $attr->{qn};
11086:                      $title =~ s/(^\s+|\s+$)//g;
11087:                      $questiontitles->[$number]=$title;
11088:                  } elsif ("@state" eq "ssn p v") {
11089:                      my $id = $attr->{id};
11090:                      my $entry = $attr->{ans};
11091:                      $id=~s/^[\#0]+//;
11092:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11093:                      $respbyid{$id}[$number] = $entry;
11094:                  }
11095:             }, "tagname, attr"],
11096:          end_h =>
11097:                [sub {
11098:                    my ($tagname) = @_;
11099:                    if ("@state" eq "ssn p") {
11100:                        $number++;
11101:                    }
11102:                    pop(@state);
11103:                 }, "tagname"],
11104:     );
11105: 
11106:     $p->parse($env{'form.upfile'});
11107:     $p->eof;
11108:     foreach my $id (keys(%respbyid)) {
11109:         $responses->{$id}=join(',',@{$respbyid{$id}});
11110:     }
11111:     return ($errormsg,$number);
11112: }
11113: 
11114: sub interwrite_eval {
11115:     my ($questiontitles,$responses)=@_;
11116:     my $number=0;
11117:     my $errormsg='';
11118:     my $skipline=1;
11119:     my $questionnumber=0;
11120:     my %idresponses=();
11121:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11122:         my %components=&Apache::loncommon::record_sep($line);
11123:         my @entries=map {$components{$_}} (sort(keys(%components)));
11124:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11125:         if ($entries[1] eq 'Response') { $skipline=1; }
11126:         next if $skipline;
11127:         if ($entries[0]!=$questionnumber) {
11128:            $questionnumber=$entries[0];
11129:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11130:            $number++;
11131:         }
11132:         my $id=$entries[4];
11133:         $id=~s/^[\#0]+//;
11134:         $id=~s/^v\d*\://i;
11135:         $id=~s/[\-\:]//g;
11136:         $idresponses{$id}[$number]=$entries[6];
11137:     }
11138:     foreach my $id (keys(%idresponses)) {
11139:        $$responses{$id}=join(',',@{$idresponses{$id}});
11140:        $$responses{$id}=~s/^\s*\,//;
11141:     }
11142:     return ($errormsg,$number);
11143: }
11144: 
11145: sub turning_eval {
11146:     my ($questiontitles,$responses)=@_;
11147:     my $number=0;
11148:     my $errormsg='';
11149:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11150:         my %components=&Apache::loncommon::record_sep($line);
11151:         my @entries=map {$components{$_}} (sort(keys(%components)));
11152:         if ($#entries>$number) { $number=$#entries; }
11153:         my $id=$entries[0];
11154:         my @idresponses;
11155:         $id=~s/^[\#0]+//;
11156:         unless ($id) { next; }
11157:         for (my $idx=1;$idx<=$#entries;$idx++) {
11158:             $entries[$idx]=~s/\,/\;/g;
11159:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11160:             push(@idresponses,$entries[$idx]);
11161:         }
11162:         $$responses{$id}=join(',',@idresponses);
11163:     }
11164:     for (my $i=1; $i<=$number; $i++) {
11165:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11166:     }
11167:     return ($errormsg,$number);
11168: }
11169: 
11170: 
11171: sub assign_clicker_grades {
11172:     my ($r,$symb) = @_;
11173:     if (!$symb) {return '';}
11174: # See which part we are saving to
11175:     my $res_error;
11176:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11177:     if ($res_error) {
11178:         return &navmap_errormsg();
11179:     }
11180: # FIXME: This should probably look for the first handgradeable part
11181:     my $part=$$partlist[0];
11182: # Start screen output
11183:     my $result = &Apache::loncommon::start_data_table().
11184:                  &Apache::loncommon::start_data_table_header_row().
11185:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11186:                  &Apache::loncommon::end_data_table_header_row().
11187:                  &Apache::loncommon::start_data_table_row().'<td>';
11188: # Get correct result
11189: # FIXME: Possibly need delimiter other than ":"
11190:     my @correct=();
11191:     my $gradingmechanism=$env{'form.gradingmechanism'};
11192:     my $number=$env{'form.number'};
11193:     if ($gradingmechanism ne 'attendance') {
11194:        foreach my $key (keys(%env)) {
11195:           if ($key=~/^form\.correct\:/) {
11196:              my @input=split(/\,/,$env{$key});
11197:              for (my $i=0;$i<=$#input;$i++) {
11198:                  if (($correct[$i]) && ($input[$i]) &&
11199:                      ($correct[$i] ne $input[$i])) {
11200:                     $result.='<br /><span class="LC_warning">'.
11201:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11202:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11203:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11204:                     $correct[$i]=$input[$i];
11205:                  }
11206:              }
11207:           }
11208:        }
11209:        for (my $i=0;$i<$number;$i++) {
11210:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11211:              $result.='<br /><span class="LC_error">'.
11212:                       &mt('No correct result given for question "[_1]"!',
11213:                           $env{'form.question:'.$i}).'</span>';
11214:           }
11215:        }
11216:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11217:     }
11218: # Start grading
11219:     my $pcorrect=$env{'form.pcorrect'};
11220:     my $pincorrect=$env{'form.pincorrect'};
11221:     my $storecount=0;
11222:     my %users=();
11223:     foreach my $key (keys(%env)) {
11224:        my $user='';
11225:        if ($key=~/^form\.student\:(.*)$/) {
11226:           $user=$1;
11227:        }
11228:        if ($key=~/^form\.unknown\:(.*)$/) {
11229:           my $id=$1;
11230:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11231:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11232:           } elsif ($env{'form.multi'.$id}) {
11233:              $user=$env{'form.multi'.$id};
11234:           }
11235:        }
11236:        if ($user) {
11237:           if ($users{$user}) {
11238:              $result.='<br /><span class="LC_warning">'.
11239:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11240:                       '</span><br />';
11241:           }
11242:           $users{$user}=1; 
11243:           my @answer=split(/\,/,$env{$key});
11244:           my $sum=0;
11245:           my $realnumber=$number;
11246:           for (my $i=0;$i<$number;$i++) {
11247:              if  ($correct[$i] eq '-') {
11248:                 $realnumber--;
11249:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11250:                 if ($gradingmechanism eq 'attendance') {
11251:                    $sum+=$pcorrect;
11252:                 } elsif ($correct[$i] eq '*') {
11253:                    $sum+=$pcorrect;
11254:                 } else {
11255: # We actually grade if correct or not
11256:                    my $increment=$pincorrect;
11257: # Special case: numerical answer "0"
11258:                    if ($correct[$i] eq '0') {
11259:                       if ($answer[$i]=~/^[0\.]+$/) {
11260:                          $increment=$pcorrect;
11261:                       }
11262: # General numerical answer, both evaluate to something non-zero
11263:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11264:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11265:                          $increment=$pcorrect;
11266:                       }
11267: # Must be just alphanumeric
11268:                    } elsif ($answer[$i] eq $correct[$i]) {
11269:                       $increment=$pcorrect;
11270:                    }
11271:                    $sum+=$increment;
11272:                 }
11273:              }
11274:           }
11275:           my $ave=$sum/(100*$realnumber);
11276: # Store
11277:           my ($username,$domain)=split(/\:/,$user);
11278:           my %grades=();
11279:           $grades{"resource.$part.solved"}='correct_by_override';
11280:           $grades{"resource.$part.awarded"}=$ave;
11281:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11282:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11283:                                                  $env{'request.course.id'},
11284:                                                  $domain,$username);
11285:           if ($returncode ne 'ok') {
11286:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11287:           } else {
11288:              $storecount++;
11289:           }
11290:        }
11291:     }
11292: # We are done
11293:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11294:              '</td>'.
11295:              &Apache::loncommon::end_data_table_row().
11296:              &Apache::loncommon::end_data_table();
11297:     return $result;
11298: }
11299: 
11300: sub navmap_errormsg {
11301:     return '<div class="LC_error">'.
11302:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11303:            &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>').
11304:            '</div>';
11305: }
11306: 
11307: sub startpage {
11308:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11309:     my %args;
11310:     if ($onload) {
11311:          my %loaditems = (
11312:                         'onload' => $onload,
11313:                       );
11314:          $args{'add_entries'} = \%loaditems;
11315:     }
11316:     if ($nomenu) {
11317:         $args{'only_body'} = 1; 
11318:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11319:     } else {
11320:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11321:         $args{'bread_crumbs'} = $crumbs;
11322:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11323:         if ($env{'request.course.id'}) {
11324:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11325:         }
11326:     }
11327:     unless ($nodisplayflag) {
11328:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11329:     }
11330: }
11331: 
11332: sub select_problem {
11333:     my ($r)=@_;
11334:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11335:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11336:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11337:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11338: }
11339: 
11340: sub css_links {
11341:     my ($currsymb,$level) = @_;
11342:     my ($links,@symbs,%cssrefs,%httpref);
11343:     if ($level eq 'map') {
11344:         my $navmap = Apache::lonnavmaps::navmap->new();
11345:         if (ref($navmap)) {
11346:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
11347:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
11348:             foreach my $res (@resources) {
11349:                 if (ref($res)) {
11350:                     if ($res->symb()) {
11351:                         push(@symbs,$res->symb());
11352:                     }
11353:                 }
11354:             }
11355:         }
11356:     } else {
11357:         @symbs = ($currsymb);
11358:     }
11359:     foreach my $symb (@symbs) {
11360:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
11361:         if ($css_href =~ /\S/) {
11362:             unless ($css_href =~ m{https?://}) {
11363:                 my ($map,undef,$url)=&Apache::lonnet::decode_symb($symb);
11364:                 my $proburl =  &Apache::lonnet::clutter($url);
11365:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
11366:                 unless ($css_href =~ m{^/}) {
11367:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
11368:                 }
11369:                 if ($css_href =~ m{^/(res|uploaded)/}) {
11370:                     unless (($httpref{'httpref.'.$css_href}) |
11371:                             (&Apache::lonnet::is_on_map($css_href))) {
11372:                         my $thisurl = $proburl;
11373:                         if ($env{'httpref.'.$proburl}) {
11374:                             $thisurl = $env{'httpref.'.$proburl};
11375:                         }
11376:                         $httpref{'httpref.'.$css_href} = $thisurl;
11377:                     }
11378:                 }
11379:             }
11380:             $cssrefs{$css_href} = 1;
11381:         }
11382:     }
11383:     if (keys(%httpref)) {
11384:         &Apache::lonnet::appenv(\%httpref);
11385:     }
11386:     if (keys(%cssrefs)) {
11387:         foreach my $css_href (keys(%cssrefs)) {
11388:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
11389:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
11390:         }
11391:     }
11392:     return $links;
11393: }
11394: 
11395: sub handler {
11396:     my $request=$_[0];
11397:     &reset_caches();
11398:     if ($request->header_only) {
11399:         &Apache::loncommon::content_type($request,'text/html');
11400:         $request->send_http_header;
11401:         return OK;
11402:     }
11403:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11404: 
11405: # see what command we need to execute
11406: 
11407:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11408:     my $command=$commands[0];
11409: 
11410:     &init_perm();
11411:     if (!$env{'request.course.id'}) {
11412:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11413:                 ($command =~ /^scantronupload/)) {
11414:             # Not in a course.
11415:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11416:             return HTTP_NOT_ACCEPTABLE;
11417:         }
11418:     } elsif (!%perm) {
11419:         $request->internal_redirect('/adm/quickgrades');
11420:         return OK;
11421:     }
11422:     &Apache::loncommon::content_type($request,'text/html');
11423:     $request->send_http_header;
11424: 
11425:     if ($#commands > 0) {
11426: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11427:     }
11428: 
11429: # see what the symb is
11430: 
11431:     my $symb=$env{'form.symb'};
11432:     unless ($symb) {
11433:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11434:        $symb=&Apache::lonnet::symbread($url);
11435:     }
11436:     &Apache::lonenc::check_decrypt(\$symb);
11437: 
11438:     $ssi_error = 0;
11439:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11440: #
11441: # Not called from a resource, but inside a course
11442: #    
11443:         &startpage($request,undef,[],1,1);
11444:         &select_problem($request);
11445:     } else {
11446: 	if ($command eq 'submission' && $perm{'vgr'}) {
11447:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11448:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11449:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11450:                     &choose_task_version_form($symb,$env{'form.student'},
11451:                                               $env{'form.userdom'});
11452:             }
11453:             my $divforres;
11454:             if ($env{'form.student'} eq '') {
11455:                 $js .= &part_selector_js();
11456:                 $onload = "toggleParts('gradesub');";
11457:             } else {
11458:                 $divforres = 1;
11459:             }
11460:             my $head_extra = $js;
11461:             unless ($env{'form.vProb'} eq 'no') {
11462:                 my $csslinks = &css_links($symb);
11463:                 if ($csslinks) {
11464:                     $head_extra .= "\n$csslinks";
11465:                 }
11466:             }
11467:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11468:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11469:             if ($versionform) {
11470:                 if ($divforres) {
11471:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11472:                 }
11473:                 $request->print($versionform);
11474:             }
11475: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11476:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11477:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11478:                 &choose_task_version_form($symb,$env{'form.student'},
11479:                                           $env{'form.userdom'},
11480:                                           $env{'form.inhibitmenu'});
11481:             my $head_extra = $js;
11482:             unless ($env{'form.vProb'} eq 'no') {
11483:                 my $csslinks = &css_links($symb);
11484:                 if ($csslinks) {
11485:                     $head_extra .= "\n$csslinks";
11486:                 }
11487:             }
11488:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11489:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11490:             if ($versionform) {
11491:                 $request->print($versionform);
11492:             }
11493:             $request->print('<br clear="all" />');
11494:             $request->print(&show_previous_task_version($request,$symb));
11495: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11496:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11497:                                        {href=>'',text=>'Select student'}],1,1);
11498: 	    &pickStudentPage($request,$symb);
11499: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11500:             my $csslinks;
11501:             unless ($env{'form.vProb'} eq 'no') {
11502:                 $csslinks = &css_links($symb,'map');
11503:             }
11504:             &startpage($request,$symb,
11505:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11506:                                        {href=>'',text=>'Select student'},
11507:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11508: 	    &displayPage($request,$symb);
11509: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11510:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11511:                                        {href=>'',text=>'Select student'},
11512:                                        {href=>'',text=>'Grade student'},
11513:                                        {href=>'',text=>'Store grades'}],1,1);
11514: 	    &updateGradeByPage($request,$symb);
11515: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11516:             my $csslinks;
11517:             unless ($env{'form.vProb'} eq 'no') {
11518:                 $csslinks = &css_links($symb);
11519:             }
11520:             &startpage($request,$symb,[{href=>'',text=>'...'},
11521:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11522: 	    &processGroup($request,$symb);
11523: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11524:             &startpage($request,$symb);
11525: 	    $request->print(&grading_menu($request,$symb));
11526: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11527:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11528: 	    $request->print(&submit_options($request,$symb));
11529:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11530:             my $js = &part_selector_js();
11531:             my $onload = "toggleParts('gradesub');";
11532:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11533:                        undef,undef,undef,undef,undef,$js,$onload);
11534:             $request->print(&listStudents($request,$symb,'graded'));
11535:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11536:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11537:             $request->print(&submit_options_table($request,$symb));
11538:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11539:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11540:             $request->print(&submit_options_sequence($request,$symb));
11541: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11542:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11543: 	    $request->print(&viewgrades($request,$symb));
11544: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11545:             &startpage($request,$symb,[{href=>'',text=>'...'},
11546:                                        {href=>'',text=>'Store grades'}]);
11547: 	    $request->print(&processHandGrade($request,$symb));
11548: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11549:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11550:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11551:                                                                              text=>"Modify grades"},
11552:                                        {href=>'', text=>"Store grades"}]);
11553: 	    $request->print(&editgrades($request,$symb));
11554:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11555:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11556:             $request->print(&initialverifyreceipt($request,$symb));
11557: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11558:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11559:                                        {href=>'',text=>'Verification Result'}]);
11560: 	    $request->print(&verifyreceipt($request,$symb));
11561:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11562:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11563:             $request->print(&process_clicker($request,$symb));
11564:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11565:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11566:                                        {href=>'', text=>'Process clicker file'}]);
11567:             $request->print(&process_clicker_file($request,$symb));
11568:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11569:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11570:                                        {href=>'', text=>'Process clicker file'},
11571:                                        {href=>'', text=>'Store grades'}]);
11572:             $request->print(&assign_clicker_grades($request,$symb));
11573: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11574:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11575: 	    $request->print(&upcsvScores_form($request,$symb));
11576: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11577:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11578: 	    $request->print(&csvupload($request,$symb));
11579: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11580:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11581: 	    $request->print(&csvuploadmap($request,$symb));
11582: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11583: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11584:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11585: 		$request->print(&csvuploadoptions($request,$symb));
11586: 	    } else {
11587: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11588: 		    $env{'form.upfile_associate'} = 'reverse';
11589: 		} else {
11590: 		    $env{'form.upfile_associate'} = 'forward';
11591: 		}
11592:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11593: 		$request->print(&csvuploadmap($request,$symb));
11594: 	    }
11595: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11596:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11597: 	    $request->print(&csvuploadassign($request,$symb));
11598: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11599:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11600:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11601: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11602:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11603:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11604:  	    $request->print(&scantron_do_warning($request,$symb));
11605: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11606:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11607: 	    $request->print(&scantron_validate_file($request,$symb));
11608: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11609:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11610: 	    $request->print(&scantron_process_students($request,$symb));
11611:  	} elsif ($command eq 'scantronupload' && 
11612:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11613:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11614:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11615:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11616:  	} elsif ($command eq 'scantronupload_save' &&
11617:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11618:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11619:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11620:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11621:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11622:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11623:         } elsif ($command eq 'scantronupload_delete' &&
11624:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11625:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11626:             &scantron_upload_delete($request,$symb);
11627:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11628:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11629:             $request->print(&checkscantron_results($request,$symb));
11630:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11631:             my $js = &part_selector_js();
11632:             my $onload = "toggleParts('gradingMenu');";
11633:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11634:                        undef,undef,undef,undef,undef,$js,$onload);
11635:             $request->print(&submit_options_download($request,$symb));
11636:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11637:             &startpage($request,$symb,
11638:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11639:     {href=>'', text=>'Download submitted files'}],
11640:                undef,undef,undef,undef,undef,undef,undef,1);
11641:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11642:             &submit_download_link($request,$symb);
11643: 	} elsif ($command) {
11644:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11645: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11646: 	}
11647:     }
11648:     if ($ssi_error) {
11649: 	&ssi_print_error($request);
11650:     }
11651:     if ($env{'form.inhibitmenu'}) {
11652:         $request->print(&Apache::loncommon::end_page());
11653:     } elsif ($env{'request.course.id'}) {
11654:         &Apache::lonquickgrades::endGradeScreen($request);
11655:     }
11656:     &reset_caches();
11657:     return OK;
11658: }
11659: 
11660: 1;
11661: 
11662: __END__;
11663: 
11664: 
11665: =head1 NAME
11666: 
11667: Apache::grades
11668: 
11669: =head1 SYNOPSIS
11670: 
11671: Handles the viewing of grades.
11672: 
11673: This is part of the LearningOnline Network with CAPA project
11674: described at http://www.lon-capa.org.
11675: 
11676: =head1 OVERVIEW
11677: 
11678: Do an ssi with retries:
11679: While I'd love to factor out this with the version in lonprintout,
11680: 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
11681: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11682: 
11683: At least the logic that drives this has been pulled out into loncommon.
11684: 
11685: 
11686: 
11687: ssi_with_retries - Does the server side include of a resource.
11688:                      if the ssi call returns an error we'll retry it up to
11689:                      the number of times requested by the caller.
11690:                      If we still have a problem, no text is appended to the
11691:                      output and we set some global variables.
11692:                      to indicate to the caller an SSI error occurred.  
11693:                      All of this is supposed to deal with the issues described
11694:                      in LON-CAPA BZ 5631 see:
11695:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11696:                      by informing the user that this happened.
11697: 
11698: Parameters:
11699:   resource   - The resource to include.  This is passed directly, without
11700:                interpretation to lonnet::ssi.
11701:   form       - The form hash parameters that guide the interpretation of the resource
11702:                
11703:   retries    - Number of retries allowed before giving up completely.
11704: Returns:
11705:   On success, returns the rendered resource identified by the resource parameter.
11706: Side Effects:
11707:   The following global variables can be set:
11708:    ssi_error                - If an unrecoverable error occurred this becomes true.
11709:                               It is up to the caller to initialize this to false
11710:                               if desired.
11711:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11712:                               of the resource that could not be rendered by the ssi
11713:                               call.
11714:    ssi_error_message   - The error string fetched from the ssi response
11715:                               in the event of an error.
11716: 
11717: 
11718: =head1 HANDLER SUBROUTINE
11719: 
11720: ssi_with_retries()
11721: 
11722: =head1 SUBROUTINES
11723: 
11724: =over
11725: 
11726: =head1 Routines to display previous version of a Task for a specific student
11727: 
11728: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11729: can receive another opportunity. Access to tasks is slot-based. If a slot
11730: requires a proctor to check-in the student, a new version of the Task will
11731: be created when the student is checked in to the new opportunity.
11732: 
11733: If a particular student has tried two or more versions of a particular task,
11734: the submission screen provides a user with vgr privileges (e.g., a Course
11735: Coordinator) the ability to display a previous version worked on by the
11736: student.  By default, the current version is displayed. If a previous version
11737: has been selected for display, submission data are only shown that pertain
11738: to that particular version, and the interface to submit grades is not shown.
11739: 
11740: =over 4
11741: 
11742: =item show_previous_task_version()
11743: 
11744: Displays a specified version of a student's Task, as the student sees it.
11745: 
11746: Inputs: 2
11747:         request - request object
11748:         symb    - unique symb for current instance of resource
11749: 
11750: Output: None.
11751: 
11752: Side Effects: calls &show_problem() to print version of Task, with
11753:               version contained in form item: $env{'form.previousversion'}
11754: 
11755: =item choose_task_version_form()
11756: 
11757: Displays a web form used to select which version of a student's view of a
11758: Task should be displayed.  Either launches a pop-up window, or replaces
11759: content in existing pop-up, or replaces page in main window.
11760: 
11761: Inputs: 4
11762:         symb    - unique symb for current instance of resource
11763:         uname   - username of student
11764:         udom    - domain of student
11765:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11766:                   breadcrumbs etc., are displayed
11767: 
11768: Output: 4
11769:         current   - student's current version
11770:         displayed - student's version being displayed
11771:         result    - scalar containing HTML for web form used to switch to
11772:                     a different version (or a link to close window, if pop-up).
11773:         js        - javascript for processing selection in versions web form
11774: 
11775: Side Effects: None.
11776: 
11777: =item previous_display_javascript()
11778: 
11779: Inputs: 2
11780:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11781:                   breadcrumbs etc., are displayed.
11782:         current - student's current version number.
11783: 
11784: Output: 1
11785:         js      - javascript for processing selection in versions web form.
11786: 
11787: Side Effects: None.
11788: 
11789: =back
11790: 
11791: =head1 Routines to process bubblesheet data.
11792: 
11793: =over 4
11794: 
11795: =item scantron_get_correction() : 
11796: 
11797:    Builds the interface screen to interact with the operator to fix a
11798:    specific error condition in a specific scanline
11799: 
11800:  Arguments:
11801:     $r           - Apache request object
11802:     $i           - number of the current scanline
11803:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11804:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11805:     $line        - full contents of the current scanline
11806:     $error       - error condition, valid values are
11807:                    'incorrectCODE', 'duplicateCODE',
11808:                    'doublebubble', 'missingbubble',
11809:                    'duplicateID', 'incorrectID'
11810:     $arg         - extra information needed
11811:        For errors:
11812:          - duplicateID   - paper number that this studentID was seen before on
11813:          - duplicateCODE - array ref of the paper numbers this CODE was
11814:                            seen on before
11815:          - incorrectCODE - current incorrect CODE 
11816:          - doublebubble  - array ref of the bubble lines that have double
11817:                            bubble errors
11818:          - missingbubble - array ref of the bubble lines that have missing
11819:                            bubble errors
11820: 
11821:    $randomorder - True if exam folder has randomorder set
11822:    $randompick  - True if exam folder has randompick set
11823:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11824:                      for current line to question number used for same question
11825:                      in "Master Seqence" (as seen by Course Coordinator).
11826:    $startline   - Reference to hash where key is question number (0 is first)
11827:                   and value is number of first bubble line for current student
11828:                   or code-based randompick and/or randomorder.
11829: 
11830: 
11831: 
11832: =item  scantron_get_maxbubble() : 
11833: 
11834:    Arguments:
11835:        $nav_error  - Reference to scalar which is a flag to indicate a
11836:                       failure to retrieve a navmap object.
11837:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11838:        calling routine should trap the error condition and display the warning
11839:        found in &navmap_errormsg().
11840: 
11841:        $scantron_config - Reference to bubblesheet format configuration hash.
11842: 
11843:    Returns the maximum number of bubble lines that are expected to
11844:    occur. Does this by walking the selected sequence rendering the
11845:    resource and then checking &Apache::lonxml::get_problem_counter()
11846:    for what the current value of the problem counter is.
11847: 
11848:    Caches the results to $env{'form.scantron_maxbubble'},
11849:    $env{'form.scantron.bubble_lines.n'}, 
11850:    $env{'form.scantron.first_bubble_line.n'} and
11851:    $env{"form.scantron.sub_bubblelines.n"}
11852:    which are the total number of bubble lines, the number of bubble
11853:    lines for response n and number of the first bubble line for response n,
11854:    and a comma separated list of numbers of bubble lines for sub-questions
11855:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11856: 
11857: 
11858: =item  scantron_validate_missingbubbles() : 
11859: 
11860:    Validates all scanlines in the selected file to not have any
11861:     answers that don't have bubbles that have not been verified
11862:     to be bubble free.
11863: 
11864: =item  scantron_process_students() : 
11865: 
11866:    Routine that does the actual grading of the bubblesheet information.
11867: 
11868:    The parsed scanline hash is added to %env 
11869: 
11870:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11871:    foreach resource , with the form data of
11872: 
11873: 	'submitted'     =>'scantron' 
11874: 	'grade_target'  =>'grade',
11875: 	'grade_username'=> username of student
11876: 	'grade_domain'  => domain of student
11877: 	'grade_courseid'=> of course
11878: 	'grade_symb'    => symb of resource to grade
11879: 
11880:     This triggers a grading pass. The problem grading code takes care
11881:     of converting the bubbled letter information (now in %env) into a
11882:     valid submission.
11883: 
11884: =item  scantron_upload_scantron_data() :
11885: 
11886:     Creates the screen for adding a new bubblesheet data file to a course.
11887: 
11888: =item  scantron_upload_scantron_data_save() : 
11889: 
11890:    Adds a provided bubble information data file to the course if user
11891:    has the correct privileges to do so.
11892: 
11893: = item scantron_upload_delete() :
11894: 
11895:    Deletes a previously uploaded bubble information data file, if user
11896:    was the one who uploaded the file, and has the privileges to do so.
11897: 
11898: =item  valid_file() :
11899: 
11900:    Validates that the requested bubble data file exists in the course.
11901: 
11902: =item  scantron_download_scantron_data() : 
11903: 
11904:    Shows a list of the three internal files (original, corrected,
11905:    skipped) for a specific bubblesheet data file that exists in the
11906:    course.
11907: 
11908: =item  scantron_validate_ID() : 
11909: 
11910:    Validates all scanlines in the selected file to not have any
11911:    invalid or underspecified student/employee IDs
11912: 
11913: =item navmap_errormsg() :
11914: 
11915:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11916:    Should be called whenever the request to instantiate a navmap object fails.
11917: 
11918: =back
11919: 
11920: =back
11921: 
11922: =cut

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