File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.792: download - view: text, annotated - select for diffs
Sun Feb 12 21:01:30 2023 UTC (15 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6966

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.792 2023/02/12 21:01: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: # Check if any gradable
 1171:     my $showmore;
 1172:     if ($perm{'mgr'}) {
 1173:         my @sections;
 1174:         if ($env{'request.course.sec'} ne '') {
 1175:             @sections = ($env{'request.course.sec'});
 1176:         } elsif ($env{'form.section'} eq '') {
 1177:             @sections = ('all');
 1178:         } else {
 1179:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1180:         }
 1181:         if (grep(/^all$/,@sections)) {
 1182:             $showmore = 1;
 1183:         } else {
 1184:             foreach my $sec (@sections) {
 1185:                 if (&canmodify($sec)) {
 1186:                     $showmore = 1;
 1187:                     last;
 1188:                 }
 1189:             }
 1190:         }
 1191:     }
 1192: 
 1193:     if ($showmore) {
 1194:         $gradeTable .=
 1195:                    &Apache::lonhtmlcommon::row_closure()
 1196:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1197:                   .'<span class="LC_nobreak">'
 1198:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1199:                   .&mt('No').('&nbsp;'x2).'</label>'
 1200:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1201:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1202:                   .&Apache::lonhtmlcommon::row_closure();
 1203: 
 1204:         $gradeTable .= 
 1205:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1206:                   .'<select name="increment">'
 1207:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1208:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1209:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1210:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1211:                   .'</select>';
 1212:     }
 1213:     $gradeTable .= 
 1214:         &build_section_inputs().
 1215: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1216: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1217: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1218:     if (exists($env{'form.Status'})) {
 1219: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
 1220:     } else {
 1221:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1222:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1223:                       .&Apache::lonhtmlcommon::StatusOptions(
 1224:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1225:     }
 1226:     if ($numessay) {
 1227:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1228:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1229:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1230:     }
 1231:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1232:                   .&Apache::lonhtmlcommon::end_pick_box();
 1233:     my $regrademsg;
 1234:     if ($is_tool) {
 1235:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1236:     } else {
 1237:         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1238:     }
 1239:     $gradeTable .= '<p>'
 1240:                   .$regrademsg."\n"
 1241:                   .'<input type="hidden" name="command" value="processGroup" />'
 1242:                   .'</p>';
 1243: 
 1244: # checkall buttons
 1245:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1246:     $gradeTable.='<input type="button" '."\n".
 1247:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1248:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1249:     $gradeTable.=&check_buttons();
 1250:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1251:     $gradeTable.= &Apache::loncommon::start_data_table().
 1252: 	&Apache::loncommon::start_data_table_header_row();
 1253:     my $loop = 0;
 1254:     while ($loop < 2) {
 1255: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1256: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1257: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1258: 	    foreach my $part (sort(@$partlist)) {
 1259: 		my $display_part=
 1260: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1261: 		$gradeTable.=
 1262: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1263: 	    }
 1264: 	} elsif ($submitonly eq 'queued') {
 1265: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1266: 	}
 1267: 	$loop++;
 1268: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1269:     }
 1270:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1271: 
 1272:     my $ctr = 0;
 1273:     foreach my $student (sort 
 1274: 			 {
 1275: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1276: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1277: 			     }
 1278: 			     return $a cmp $b;
 1279: 			 }
 1280: 			 (keys(%$fullname))) {
 1281: 	my ($uname,$udom) = split(/:/,$student);
 1282: 
 1283: 	my %status = ();
 1284: 
 1285: 	if ($submitonly eq 'queued') {
 1286: 	    my %queue_status = 
 1287: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1288: 							$udom,$uname);
 1289: 	    next if (!defined($queue_status{'gradingqueue'}));
 1290: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1291: 	}
 1292: 
 1293: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1294: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1295: 	    my $submitted = 0;
 1296: 	    my $graded = 0;
 1297: 	    my $incorrect = 0;
 1298: 	    foreach (keys(%status)) {
 1299: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1300: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1301: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1302: 		
 1303: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1304: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1305: 		    $submitted = 0;
 1306: 		    my ($part)=split(/\./,$partid);
 1307: 		    $gradeTable.='<input type="hidden" name="'.
 1308: 			$student.':'.$part.':submitted_by" value="'.
 1309: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1310: 		}
 1311: 	    }
 1312: 	    
 1313: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1314: 				     $submitonly eq 'incorrect' ||
 1315: 				     $submitonly eq 'graded'));
 1316: 	    next if (!$graded && ($submitonly eq 'graded'));
 1317: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1318: 	}
 1319: 
 1320: 	$ctr++;
 1321: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1322:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1323: 	if ( $perm{'vgr'} eq 'F' ) {
 1324: 	    if ($ctr%2 ==1) {
 1325: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1326: 	    }
 1327: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1328:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1329:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1330: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1331: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1332: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1333: 
 1334: 	    if ($submitonly ne 'all') {
 1335: 		foreach (sort(keys(%status))) {
 1336: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1337: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1338: 		}
 1339: 	    }
 1340: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1341: 	    if ($ctr%2 ==0) {
 1342: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1343: 	    }
 1344: 	}
 1345:     }
 1346:     if ($ctr%2 ==1) {
 1347: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1348: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1349: 		foreach (@$partlist) {
 1350: 		    $gradeTable.='<td>&nbsp;</td>';
 1351: 		}
 1352: 	    } elsif ($submitonly eq 'queued') {
 1353: 		$gradeTable.='<td>&nbsp;</td>';
 1354: 	    }
 1355: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1356:     }
 1357: 
 1358:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1359:         '<input type="button" '.
 1360:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1361:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1362:     if ($ctr == 0) {
 1363: 	my $num_students=(scalar(keys(%$fullname)));
 1364: 	if ($num_students eq 0) {
 1365: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1366: 	} else {
 1367: 	    my $submissions='submissions';
 1368: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1369: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1370: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1371: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1372: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1373: 		    $num_students).
 1374: 		'</span><br />';
 1375: 	}
 1376:     } elsif ($ctr == 1) {
 1377: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1378:     }
 1379:     $request->print($gradeTable);
 1380:     return '';
 1381: }
 1382: 
 1383: #---- Called from the listStudents routine
 1384: 
 1385: sub check_script {
 1386:     my ($form,$type) = @_;
 1387:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1388:     function checkall() {
 1389:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1390:             ele = document.forms.'.$form.'.elements[i];
 1391:             if (ele.name == "'.$type.'") {
 1392:             document.forms.'.$form.'.elements[i].checked=true;
 1393:                                        }
 1394:         }
 1395:     }
 1396: 
 1397:     function checksec() {
 1398:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1399:             ele = document.forms.'.$form.'.elements[i];
 1400:            string = document.forms.'.$form.'.chksec.value;
 1401:            if
 1402:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1403:               document.forms.'.$form.'.elements[i].checked=true;
 1404:             }
 1405:         }
 1406:     }
 1407: 
 1408: 
 1409:     function uncheckall() {
 1410:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1411:             ele = document.forms.'.$form.'.elements[i];
 1412:             if (ele.name == "'.$type.'") {
 1413:             document.forms.'.$form.'.elements[i].checked=false;
 1414:                                        }
 1415:         }
 1416:     }
 1417: 
 1418: '."\n");
 1419:     return $chkallscript;
 1420: }
 1421: 
 1422: sub check_buttons {
 1423:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1424:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1425:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1426:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1427:     return $buttons;
 1428: }
 1429: 
 1430: #     Displays the submissions for one student or a group of students
 1431: sub processGroup {
 1432:     my ($request,$symb) = @_;
 1433:     my $ctr        = 0;
 1434:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1435:     my $total      = scalar(@stuchecked)-1;
 1436: 
 1437:     foreach my $student (@stuchecked) {
 1438: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1439: 	$env{'form.student'}        = $uname;
 1440: 	$env{'form.userdom'}        = $udom;
 1441: 	$env{'form.fullname'}       = $fullname;
 1442: 	&submission($request,$ctr,$total,$symb);
 1443: 	$ctr++;
 1444:     }
 1445:     return '';
 1446: }
 1447: 
 1448: #------------------------------------------------------------------------------------
 1449: #
 1450: #-------------------------- Next few routines handles grading by student, essentially
 1451: #                           handles essay response type problem/part
 1452: #
 1453: #--- Javascript to handle the submission page functionality ---
 1454: sub sub_page_js {
 1455:     my $request = shift;
 1456:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1457:     &js_escape(\$alertmsg);
 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1459:     function updateRadio(formname,id,weight) {
 1460: 	var gradeBox = formname["GD_BOX"+id];
 1461: 	var radioButton = formname["RADVAL"+id];
 1462: 	var oldpts = formname["oldpts"+id].value;
 1463: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1464: 	gradeBox.value = pts;
 1465: 	var resetbox = false;
 1466: 	if (isNaN(pts) || pts < 0) {
 1467: 	    alert("$alertmsg"+pts);
 1468: 	    for (var i=0; i<radioButton.length; i++) {
 1469: 		if (radioButton[i].checked) {
 1470: 		    gradeBox.value = i;
 1471: 		    resetbox = true;
 1472: 		}
 1473: 	    }
 1474: 	    if (!resetbox) {
 1475: 		formtextbox.value = "";
 1476: 	    }
 1477: 	    return;
 1478: 	}
 1479: 
 1480: 	if (pts > weight) {
 1481: 	    var resp = confirm("You entered a value ("+pts+
 1482: 			       ") greater than the weight for the part. Accept?");
 1483: 	    if (resp == false) {
 1484: 		gradeBox.value = oldpts;
 1485: 		return;
 1486: 	    }
 1487: 	}
 1488: 
 1489: 	for (var i=0; i<radioButton.length; i++) {
 1490: 	    radioButton[i].checked=false;
 1491: 	    if (pts == i && pts != "") {
 1492: 		radioButton[i].checked=true;
 1493: 	    }
 1494: 	}
 1495: 	updateSelect(formname,id);
 1496: 	formname["stores"+id].value = "0";
 1497:     }
 1498: 
 1499:     function writeBox(formname,id,pts) {
 1500: 	var gradeBox = formname["GD_BOX"+id];
 1501: 	if (checkSolved(formname,id) == 'update') {
 1502: 	    gradeBox.value = pts;
 1503: 	} else {
 1504: 	    var oldpts = formname["oldpts"+id].value;
 1505: 	    gradeBox.value = oldpts;
 1506: 	    var radioButton = formname["RADVAL"+id];
 1507: 	    for (var i=0; i<radioButton.length; i++) {
 1508: 		radioButton[i].checked=false;
 1509: 		if (i == oldpts) {
 1510: 		    radioButton[i].checked=true;
 1511: 		}
 1512: 	    }
 1513: 	}
 1514: 	formname["stores"+id].value = "0";
 1515: 	updateSelect(formname,id);
 1516: 	return;
 1517:     }
 1518: 
 1519:     function clearRadBox(formname,id) {
 1520: 	if (checkSolved(formname,id) == 'noupdate') {
 1521: 	    updateSelect(formname,id);
 1522: 	    return;
 1523: 	}
 1524: 	gradeSelect = formname["GD_SEL"+id];
 1525: 	for (var i=0; i<gradeSelect.length; i++) {
 1526: 	    if (gradeSelect[i].selected) {
 1527: 		var selectx=i;
 1528: 	    }
 1529: 	}
 1530: 	var stores = formname["stores"+id];
 1531: 	if (selectx == stores.value) { return };
 1532: 	var gradeBox = formname["GD_BOX"+id];
 1533: 	gradeBox.value = "";
 1534: 	var radioButton = formname["RADVAL"+id];
 1535: 	for (var i=0; i<radioButton.length; i++) {
 1536: 	    radioButton[i].checked=false;
 1537: 	}
 1538: 	stores.value = selectx;
 1539:     }
 1540: 
 1541:     function checkSolved(formname,id) {
 1542: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1543: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1544: 	    if (!reply) {return "noupdate";}
 1545: 	    formname.overRideScore.value = 'yes';
 1546: 	}
 1547: 	return "update";
 1548:     }
 1549: 
 1550:     function updateSelect(formname,id) {
 1551: 	formname["GD_SEL"+id][0].selected = true;
 1552: 	return;
 1553:     }
 1554: 
 1555: //=========== Check that a point is assigned for all the parts  ============
 1556:     function checksubmit(formname,val,total,parttot) {
 1557: 	formname.gradeOpt.value = val;
 1558: 	if (val == "Save & Next") {
 1559: 	    for (i=0;i<=total;i++) {
 1560: 		for (j=0;j<parttot;j++) {
 1561: 		    var partid = formname["partid"+i+"_"+j].value;
 1562: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1563: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1564: 			if (points == "") {
 1565: 			    var name = formname["name"+i].value;
 1566: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1567: 			    var resp = confirm("You did not assign a score for "+studentID+
 1568: 					       ", part "+partid+". Continue?");
 1569: 			    if (resp == false) {
 1570: 				formname["GD_BOX"+i+"_"+partid].focus();
 1571: 				return false;
 1572: 			    }
 1573: 			}
 1574: 		    }
 1575: 		}
 1576: 	    }
 1577: 	}
 1578: 	formname.submit();
 1579:     }
 1580: 
 1581: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1582:     function checkSubmitPage(formname,total) {
 1583: 	noscore = new Array(100);
 1584: 	var ptr = 0;
 1585: 	for (i=1;i<total;i++) {
 1586: 	    var partid = formname["q_"+i].value;
 1587: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1588: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1589: 		var status = formname["solved"+i+"_"+partid].value;
 1590: 		if (points == "" && status != "correct_by_student") {
 1591: 		    noscore[ptr] = i;
 1592: 		    ptr++;
 1593: 		}
 1594: 	    }
 1595: 	}
 1596: 	if (ptr != 0) {
 1597: 	    var sense = ptr == 1 ? ": " : "s: ";
 1598: 	    var prolist = "";
 1599: 	    if (ptr == 1) {
 1600: 		prolist = noscore[0];
 1601: 	    } else {
 1602: 		var i = 0;
 1603: 		while (i < ptr-1) {
 1604: 		    prolist += noscore[i]+", ";
 1605: 		    i++;
 1606: 		}
 1607: 		prolist += "and "+noscore[i];
 1608: 	    }
 1609: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1610: 	    if (resp == false) {
 1611: 		return false;
 1612: 	    }
 1613: 	}
 1614: 
 1615: 	formname.submit();
 1616:     }
 1617: SUBJAVASCRIPT
 1618: }
 1619: 
 1620: #--- javascript for grading message center
 1621: sub sub_grademessage_js {
 1622:     my $request = shift;
 1623:     my $iconpath = $request->dir_config('lonIconsURL');
 1624:     &commonJSfunctions($request);
 1625: 
 1626:     my $inner_js_msg_central= (<<INNERJS);
 1627: <script type="text/javascript">
 1628:     function checkInput() {
 1629:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1630:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1631:       var usrctr = document.msgcenter.usrctr.value;
 1632:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1633:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1634: 
 1635:       var msgchk = "";
 1636:       if (document.msgcenter.subchk.checked) {
 1637:          msgchk = "msgsub,";
 1638:       }
 1639:       var includemsg = 0;
 1640:       for (var i=1; i<=nmsg; i++) {
 1641:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1642:           var frmmsg = document.msgcenter["msg"+i];
 1643:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1644:           var showflg = opener.document.SCORE["shownOnce"+i];
 1645:           showflg.value = "1";
 1646:           var chkbox = document.msgcenter["msgn"+i];
 1647:           if (chkbox.checked) {
 1648:              msgchk += "savemsg"+i+",";
 1649:              includemsg = 1;
 1650:           }
 1651:       }
 1652:       if (document.msgcenter.newmsgchk.checked) {
 1653:          msgchk += "newmsg"+usrctr;
 1654:          includemsg = 1;
 1655:       }
 1656:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1657:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1658:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1659:       includemsg.value = msgchk;
 1660: 
 1661:       self.close()
 1662: 
 1663:     }
 1664: </script>
 1665: INNERJS
 1666: 
 1667:     my $start_page_msg_central =
 1668:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1669: 				       {'js_ready'  => 1,
 1670: 					'only_body' => 1,
 1671: 					'bgcolor'   =>'#FFFFFF',});
 1672:     my $end_page_msg_central =
 1673: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1674: 
 1675:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1676:     $docopen=~s/^document\.//;
 1677: 
 1678:     my %html_js_lt = &Apache::lonlocal::texthash(
 1679:                 comp => 'Compose Message for: ',
 1680:                 incl => 'Include',
 1681:                 type => 'Type',
 1682:                 subj => 'Subject',
 1683:                 mesa => 'Message',
 1684:                 new  => 'New',
 1685:                 save => 'Save',
 1686:                 canc => 'Cancel',
 1687:              );
 1688:     &html_escape(\%html_js_lt);
 1689:     &js_escape(\%html_js_lt);
 1690:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1691: 
 1692: //===================== Script to view submitted by ==================
 1693:   function viewSubmitter(submitter) {
 1694:     document.SCORE.refresh.value = "on";
 1695:     document.SCORE.NCT.value = "1";
 1696:     document.SCORE.unamedom0.value = submitter;
 1697:     document.SCORE.submit();
 1698:     return;
 1699:   }
 1700: 
 1701: //====================== Script for composing message ==============
 1702:    // preload images
 1703:    img1 = new Image();
 1704:    img1.src = "$iconpath/mailbkgrd.gif";
 1705:    img2 = new Image();
 1706:    img2.src = "$iconpath/mailto.gif";
 1707: 
 1708:   function msgCenter(msgform,usrctr,fullname) {
 1709:     var Nmsg  = msgform.savemsgN.value;
 1710:     savedMsgHeader(Nmsg,usrctr,fullname);
 1711:     var subject = msgform.msgsub.value;
 1712:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1713:     re = /msgsub/;
 1714:     var shwsel = "";
 1715:     if (re.test(msgchk)) { shwsel = "checked" }
 1716:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1717:     displaySubject(checkEntities(subject),shwsel);
 1718:     for (var i=1; i<=Nmsg; i++) {
 1719: 	var testmsg = "savemsg"+i+",";
 1720: 	re = new RegExp(testmsg,"g");
 1721: 	shwsel = "";
 1722: 	if (re.test(msgchk)) { shwsel = "checked" }
 1723: 	var message = document.SCORE["savemsg"+i].value;
 1724: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1725: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1726: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1727:     }
 1728:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1729:     shwsel = "";
 1730:     re = /newmsg/;
 1731:     if (re.test(msgchk)) { shwsel = "checked" }
 1732:     newMsg(newmsg,shwsel);
 1733:     msgTail(); 
 1734:     return;
 1735:   }
 1736: 
 1737:   function checkEntities(strx) {
 1738:     if (strx.length == 0) return strx;
 1739:     var orgStr = ["&", "<", ">", '"']; 
 1740:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1741:     var counter = 0;
 1742:     while (counter < 4) {
 1743: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1744: 	counter++;
 1745:     }
 1746:     return strx;
 1747:   }
 1748: 
 1749:   function strReplace(strx, orgStr, newStr) {
 1750:     return strx.split(orgStr).join(newStr);
 1751:   }
 1752: 
 1753:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1754:     var height = 70*Nmsg+250;
 1755:     if (height > 600) {
 1756: 	height = 600;
 1757:     }
 1758:     var xpos = (screen.width-600)/2;
 1759:     xpos = (xpos < 0) ? '0' : xpos;
 1760:     var ypos = (screen.height-height)/2-30;
 1761:     ypos = (ypos < 0) ? '0' : ypos;
 1762: 
 1763:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1764:     pWin.focus();
 1765:     pDoc = pWin.document;
 1766:     pDoc.$docopen;
 1767:     pDoc.write('$start_page_msg_central');
 1768: 
 1769:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1770:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1771:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1772: 
 1773:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1774:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1775: }
 1776:     function displaySubject(msg,shwsel) {
 1777:     pDoc = pWin.document;
 1778:     pDoc.write("<tr>");
 1779:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1780:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1781:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1782: }
 1783: 
 1784:   function displaySavedMsg(ctr,msg,shwsel) {
 1785:     pDoc = pWin.document;
 1786:     pDoc.write("<tr>");
 1787:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1788:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1789:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1790: }
 1791: 
 1792:   function newMsg(newmsg,shwsel) {
 1793:     pDoc = pWin.document;
 1794:     pDoc.write("<tr>");
 1795:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1796:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1797:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1798: }
 1799: 
 1800:   function msgTail() {
 1801:     pDoc = pWin.document;
 1802:     //pDoc.write("<\\/table>");
 1803:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1804:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1805:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1806:     pDoc.write("<\\/form>");
 1807:     pDoc.write('$end_page_msg_central');
 1808:     pDoc.close();
 1809: }
 1810: 
 1811: SUBJAVASCRIPT
 1812: }
 1813: 
 1814: #--- javascript for essay type problem --
 1815: sub sub_page_kw_js {
 1816:     my $request = shift;
 1817: 
 1818:     unless ($env{'form.compmsg'}) {
 1819:         &commonJSfunctions($request);
 1820:     }
 1821: 
 1822:     my $inner_js_highlight_central= (<<INNERJS);
 1823: <script type="text/javascript">
 1824:     function updateChoice(flag) {
 1825:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1826:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1827:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1828:       opener.document.SCORE.refresh.value = "on";
 1829:       if (opener.document.SCORE.keywords.value!=""){
 1830:          opener.document.SCORE.submit();
 1831:       }
 1832:       self.close()
 1833:     }
 1834: </script>
 1835: INNERJS
 1836: 
 1837:     my $start_page_highlight_central =
 1838:         &Apache::loncommon::start_page('Highlight Central',
 1839:                                        $inner_js_highlight_central,
 1840:                                        {'js_ready'  => 1,
 1841:                                         'only_body' => 1,
 1842:                                         'bgcolor'   =>'#FFFFFF',});
 1843:     my $end_page_highlight_central =
 1844:         &Apache::loncommon::end_page({'js_ready' => 1});
 1845: 
 1846:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1847:     $docopen=~s/^document\.//;
 1848: 
 1849:     my %js_lt = &Apache::lonlocal::texthash(
 1850:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1851:                 plse => 'Please select a word or group of words from document and then click this link.',
 1852:                 adds => 'Add selection to keyword list? Edit if desired.',
 1853:                 col1 => 'red',
 1854:                 col2 => 'green',
 1855:                 col3 => 'blue',
 1856:                 siz1 => 'normal',
 1857:                 siz2 => '+1',
 1858:                 siz3 => '+2',
 1859:                 sty1 => 'normal',
 1860:                 sty2 => 'italic',
 1861:                 sty3 => 'bold',
 1862:              );
 1863:     my %html_js_lt = &Apache::lonlocal::texthash(
 1864:                 save => 'Save',
 1865:                 canc => 'Cancel',
 1866:                 kehi => 'Keyword Highlight Options',
 1867:                 txtc => 'Text Color',
 1868:                 font => 'Font Size',
 1869:                 fnst => 'Font Style',
 1870:              );
 1871:     &js_escape(\%js_lt);
 1872:     &html_escape(\%html_js_lt);
 1873:     &js_escape(\%html_js_lt);
 1874:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1875: 
 1876: //===================== Show list of keywords ====================
 1877:   function keywords(formname) {
 1878:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1879:     if (nret==null) return;
 1880:     formname.keywords.value = nret;
 1881: 
 1882:     if (formname.keywords.value != "") {
 1883:         formname.refresh.value = "on";
 1884:         formname.submit();
 1885:     }
 1886:     return;
 1887:   }
 1888: 
 1889: //===================== Script to add keyword(s) ==================
 1890:   function getSel() {
 1891:     if (document.getSelection) txt = document.getSelection();
 1892:     else if (document.selection) txt = document.selection.createRange().text;
 1893:     else return;
 1894:     if (typeof(txt) != 'string') {
 1895:         txt = String(txt);
 1896:     }
 1897:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1898:     if (cleantxt=="") {
 1899:         alert("$js_lt{'plse'}");
 1900:         return;
 1901:     }
 1902:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1903:     if (nret==null) return;
 1904:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1905:     if (document.SCORE.keywords.value != "") {
 1906:         document.SCORE.refresh.value = "on";
 1907:         document.SCORE.submit();
 1908:     }
 1909:     return;
 1910:   }
 1911: 
 1912: //====================== Script for keyword highlight options ==============
 1913:   function kwhighlight() {
 1914:     var kwclr    = document.SCORE.kwclr.value;
 1915:     var kwsize   = document.SCORE.kwsize.value;
 1916:     var kwstyle  = document.SCORE.kwstyle.value;
 1917:     var redsel = "";
 1918:     var grnsel = "";
 1919:     var blusel = "";
 1920:     var txtcol1 = "$js_lt{'col1'}";
 1921:     var txtcol2 = "$js_lt{'col2'}";
 1922:     var txtcol3 = "$js_lt{'col3'}";
 1923:     var txtsiz1 = "$js_lt{'siz1'}";
 1924:     var txtsiz2 = "$js_lt{'siz2'}";
 1925:     var txtsiz3 = "$js_lt{'siz3'}";
 1926:     var txtsty1 = "$js_lt{'sty1'}";
 1927:     var txtsty2 = "$js_lt{'sty2'}";
 1928:     var txtsty3 = "$js_lt{'sty3'}";
 1929:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1930:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1931:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1932:     var sznsel = "";
 1933:     var sz1sel = "";
 1934:     var sz2sel = "";
 1935:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1936:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1937:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1938:     var synsel = "";
 1939:     var syisel = "";
 1940:     var sybsel = "";
 1941:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1942:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1943:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1944:     highlightCentral();
 1945:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1946:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1947:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1948:     highlightend();
 1949:     return;
 1950:   }
 1951: 
 1952:   function highlightCentral() {
 1953: //    if (window.hwdWin) window.hwdWin.close();
 1954:     var xpos = (screen.width-400)/2;
 1955:     xpos = (xpos < 0) ? '0' : xpos;
 1956:     var ypos = (screen.height-330)/2-30;
 1957:     ypos = (ypos < 0) ? '0' : ypos;
 1958: 
 1959:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1960:     hwdWin.focus();
 1961:     var hDoc = hwdWin.document;
 1962:     hDoc.$docopen;
 1963:     hDoc.write('$start_page_highlight_central');
 1964:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1965:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1966: 
 1967:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1968:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1969:   }
 1970: 
 1971:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1972:     var hDoc = hwdWin.document;
 1973:     hDoc.write("<tr>");
 1974:     hDoc.write("<td align=\\"left\\">");
 1975:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1976:     hDoc.write("<td align=\\"left\\">");
 1977:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1978:     hDoc.write("<td align=\\"left\\">");
 1979:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1980:     hDoc.write("<\\/tr>");
 1981:   }
 1982: 
 1983:   function highlightend() { 
 1984:     var hDoc = hwdWin.document;
 1985:     hDoc.write("<\\/table><br \\/>");
 1986:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1987:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1988:     hDoc.write("<\\/form>");
 1989:     hDoc.write('$end_page_highlight_central');
 1990:     hDoc.close();
 1991:   }
 1992: 
 1993: SUBJAVASCRIPT
 1994: }
 1995: 
 1996: sub get_increment {
 1997:     my $increment = $env{'form.increment'};
 1998:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1999:         $increment != .1) {
 2000:         $increment = 1;
 2001:     }
 2002:     return $increment;
 2003: }
 2004: 
 2005: sub gradeBox_start {
 2006:     return (
 2007:         &Apache::loncommon::start_data_table()
 2008:        .&Apache::loncommon::start_data_table_header_row()
 2009:        .'<th>'.&mt('Part').'</th>'
 2010:        .'<th>'.&mt('Points').'</th>'
 2011:        .'<th>&nbsp;</th>'
 2012:        .'<th>'.&mt('Assign Grade').'</th>'
 2013:        .'<th>'.&mt('Weight').'</th>'
 2014:        .'<th>'.&mt('Grade Status').'</th>'
 2015:        .&Apache::loncommon::end_data_table_header_row()
 2016:     );
 2017: }
 2018: 
 2019: sub gradeBox_end {
 2020:     return (
 2021:         &Apache::loncommon::end_data_table()
 2022:     );
 2023: }
 2024: #--- displays the grading box, used in essay type problem and grading by page/sequence
 2025: sub gradeBox {
 2026:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 2027:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2028: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2029:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2030:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2031:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2032:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2033:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2034: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2035:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2036:     my $display_part= &get_display_part($partid,$symb);
 2037:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2038: 				       [$partid]);
 2039:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2040:     if ($last_resets{$partid}) {
 2041:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2042:     }
 2043:     my $result=&Apache::loncommon::start_data_table_row();
 2044:     my $ctr = 0;
 2045:     my $thisweight = 0;
 2046:     my $increment = &get_increment();
 2047: 
 2048:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2049:     while ($thisweight<=$wgt) {
 2050: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2051:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2052: 	    $thisweight.')" value="'.$thisweight.'" '.
 2053: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2054: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2055:         $thisweight += $increment;
 2056: 	$ctr++;
 2057:     }
 2058:     $radio.='</tr></table>';
 2059: 
 2060:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2061: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2062: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2063: 	$wgt.')" /></td>'."\n";
 2064:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2065: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2066: 	' </td>'."\n";
 2067:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2068: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2069:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2070: 	$line.='<option></option>'.
 2071: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2072:     } else {
 2073: 	$line.='<option selected="selected"></option>'.
 2074: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2075:     }
 2076:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2077: 
 2078: 
 2079:     $result .= 
 2080: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2081:     $result.=&Apache::loncommon::end_data_table_row();
 2082:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2083:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2084: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2085: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2086: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2087:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2088:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2089:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2090:         $aggtries.'" />'."\n";
 2091:     my $res_error;
 2092:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2093:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2094:     if ($res_error) {
 2095:         return &navmap_errormsg();
 2096:     }
 2097:     return $result;
 2098: }
 2099: 
 2100: sub handback_box {
 2101:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2102:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2103:     return unless ($numessay);
 2104:     my (@respids);
 2105:     my @part_response_id = &flatten_responseType($responseType);
 2106:     foreach my $part_response_id (@part_response_id) {
 2107:     	my ($part,$resp) = @{ $part_response_id };
 2108:         if ($part eq $partid) {
 2109:             push(@respids,$resp);
 2110:         }
 2111:     }
 2112:     my $result;
 2113:     foreach my $respid (@respids) {
 2114: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2115: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2116: 	next if (!@$files);
 2117: 	my $file_counter = 0;
 2118: 	foreach my $file (@$files) {
 2119: 	    if ($file =~ /\/portfolio\//) {
 2120:                 $file_counter++;
 2121:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2122:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2123:     	        $file_disp = "$name.$ext";
 2124:     	        $file = $file_path.$file_disp;
 2125:     	        $result.=&mt('Return commented version of [_1] to student.',
 2126:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2127:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2128:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2129: 	    }
 2130: 	}
 2131:         if ($file_counter) {
 2132:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2133:                        '<span class="LC_info">'.
 2134:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2135:         }
 2136:     }
 2137:     return $result;    
 2138: }
 2139: 
 2140: sub show_problem {
 2141:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2142:     my $rendered;
 2143:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2144:     &Apache::lonxml::remember_problem_counter();
 2145:     if ($mode eq 'both' or $mode eq 'text') {
 2146: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2147: 						       $env{'request.course.id'},
 2148: 						       undef,\%form);
 2149:     }
 2150:     if ($removeform) {
 2151: 	$rendered=~s|<form(.*?)>||g;
 2152: 	$rendered=~s|</form>||g;
 2153: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2154:     }
 2155:     my $companswer;
 2156:     if ($mode eq 'both' or $mode eq 'answer') {
 2157: 	&Apache::lonxml::restore_problem_counter();
 2158: 	$companswer=
 2159: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2160: 						    $env{'request.course.id'},
 2161: 						    %form);
 2162:     }
 2163:     if ($removeform) {
 2164: 	$companswer=~s|<form(.*?)>||g;
 2165: 	$companswer=~s|</form>||g;
 2166: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2167:     }
 2168:     my $renderheading = &mt('View of the problem');
 2169:     my $answerheading = &mt('Correct answer');
 2170:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2171:         my $stu_fullname = $env{'form.fullname'};
 2172:         if ($stu_fullname eq '') {
 2173:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2174:         }
 2175:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2176:         if ($forwhom ne '') {
 2177:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2178:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2179:         }
 2180:     }
 2181:     $rendered=
 2182:         '<div class="LC_Box">'
 2183:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2184:        .$rendered
 2185:        .'</div>';
 2186:     $companswer=
 2187:         '<div class="LC_Box">'
 2188:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2189:        .$companswer
 2190:        .'</div>';
 2191:     my $result;
 2192:     if ($mode eq 'both') {
 2193:         $result=$rendered.$companswer;
 2194:     } elsif ($mode eq 'text') {
 2195:         $result=$rendered;
 2196:     } elsif ($mode eq 'answer') {
 2197:         $result=$companswer;
 2198:     }
 2199:     return $result;
 2200: }
 2201: 
 2202: sub files_exist {
 2203:     my ($r, $symb) = @_;
 2204:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2205:     foreach my $student (@students) {
 2206:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2207:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2208: 					      $udom,$uname);
 2209:         my ($string)= &get_last_submission(\%record);
 2210:         foreach my $submission (@$string) {
 2211:             my ($partid,$respid) =
 2212: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2213:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2214: 					   \%record);
 2215:             return 1 if (@$files);
 2216:         }
 2217:     }
 2218:     return 0;
 2219: }
 2220: 
 2221: sub download_all_link {
 2222:     my ($r,$symb) = @_;
 2223:     unless (&files_exist($r, $symb)) {
 2224:         $r->print(&mt('There are currently no submitted documents.'));
 2225:         return;
 2226:     }
 2227:     my $all_students = 
 2228: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2229: 
 2230:     my $parts =
 2231: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2232: 
 2233:     my $identifier = &Apache::loncommon::get_cgi_id();
 2234:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2235:                              'cgi.'.$identifier.'.symb' => $symb,
 2236:                              'cgi.'.$identifier.'.parts' => $parts,});
 2237:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2238: 	      &mt('Download All Submitted Documents').'</a>');
 2239:     return;
 2240: }
 2241: 
 2242: sub submit_download_link {
 2243:     my ($request,$symb) = @_;
 2244:     if (!$symb) { return ''; }
 2245:     my $res_error;
 2246:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2247:         &response_type($symb,\$res_error);
 2248:     if ($res_error) {
 2249:         $request->print(&mt('An error occurred retrieving response types'));
 2250:         return;
 2251:     }
 2252:     unless ($numessay) {
 2253:         $request->print(&mt('No essayresponse items found'));
 2254:         return;
 2255:     }
 2256:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2257:     if (@chosenparts) {
 2258:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2259:                                           undef,undef,1));
 2260:     }
 2261:     if ($numessay) {
 2262:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2263:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2264:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2265:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2266:         if (ref($fullname) eq 'HASH') {
 2267:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2268:             if (@students) {
 2269:                 @{$env{'form.stuinfo'}} = @students;
 2270:                 if ($numdropbox) {
 2271:                     &download_all_link($request,$symb);
 2272:                 } else {
 2273:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2274:                 }
 2275: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2276: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2277:             } else {
 2278:                 $request->print(&mt('No students match the criteria you selected'));
 2279:             }
 2280:         } else {
 2281:             $request->print(&mt('Could not retrieve student information'));
 2282:         }
 2283:     } else {
 2284:         $request->print(&mt('No essayresponse items found'));
 2285:     }
 2286:     return;
 2287: }
 2288: 
 2289: sub build_section_inputs {
 2290:     my $section_inputs;
 2291:     if ($env{'form.section'} eq '') {
 2292:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2293:     } else {
 2294:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2295:         foreach my $section (@sections) {
 2296:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2297:         }
 2298:     }
 2299:     return $section_inputs;
 2300: }
 2301: 
 2302: # --------------------------- show submissions of a student, option to grade 
 2303: sub submission {
 2304:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2305:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2306:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2307:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2308:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2309: 
 2310:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2311:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2312:     my $is_tool = ($symb =~ /ext\.tool$/);
 2313:     my ($essayurl,%coursedesc_by_cid);
 2314: 
 2315:     if (!&canview($usec)) {
 2316:         $request->print(
 2317:             '<span class="LC_warning">'.
 2318:             &mt('Unable to view requested student.').
 2319:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2320:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2321:             '</span>');
 2322: 	return;
 2323:     }
 2324: 
 2325:     my $res_error;
 2326:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2327:         &response_type($symb,\$res_error);
 2328:     if ($res_error) {
 2329:         $request->print(&navmap_errormsg());
 2330:         return;
 2331:     }
 2332: 
 2333:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2334:     unless ($is_tool) { 
 2335:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2336:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2337:     }
 2338:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2339:         $env{'form.compmsg'} = 1;
 2340:     }
 2341:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2342:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2343: 	'" src="'.$request->dir_config('lonIconsURL').
 2344: 	'/check.gif" height="16" border="0" />';
 2345: 
 2346:     # header info
 2347:     if ($counter == 0) {
 2348:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2349:         if (@chosenparts) {
 2350:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2351:         } elsif ($divforres) {
 2352:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2353:         } else {
 2354:             $request->print('<br clear="all" />');
 2355:         }
 2356: 	&sub_page_js($request);
 2357:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2358: 	&sub_page_kw_js($request) if ($numessay);
 2359: 
 2360: 	# option to display problem, only once else it cause problems 
 2361:         # with the form later since the problem has a form.
 2362: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2363: 	    my $mode;
 2364: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2365: 		$mode='both';
 2366: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2367: 		$mode='text';
 2368: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2369: 		$mode='answer';
 2370: 	    }
 2371: 	    &Apache::lonxml::clear_problem_counter();
 2372: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2373: 	}
 2374: 
 2375: 	my %keyhash = ();
 2376: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2377: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2378: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2379: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2380: 	}
 2381: 	# kwclr is the only variable that is guaranteed not to be blank
 2382: 	# if this subroutine has been called once.
 2383: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2384: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2385: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2386: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2387: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2388: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2389: 	}
 2390: 	if ($env{'form.compmsg'}) {
 2391: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2392: 		$keyhash{$symb.'_subject'} : $probtitle;
 2393: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2394: 	}
 2395: 
 2396: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2397: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2398: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2399: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2400: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2401: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2402: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2403: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2404: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2405: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2406: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2407: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2408: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2409: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2410: 			&build_section_inputs().
 2411: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2412: 			'<input type="hidden" name="NCT"'.
 2413: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2414: 	if ($env{'form.compmsg'}) {
 2415: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2416: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2417: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2418: 	}
 2419: 	if ($numessay) {
 2420: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2421: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2422: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2423: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2424: 	}
 2425: 
 2426: 	my ($cts,$prnmsg) = (1,'');
 2427: 	while ($cts <= $env{'form.savemsgN'}) {
 2428: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2429: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2430: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2431: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2432: 		'" />'."\n".
 2433: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2434: 	    $cts++;
 2435: 	}
 2436: 	$request->print($prnmsg);
 2437: 
 2438: 	if ($numessay) {
 2439: 
 2440:             my %lt = &Apache::lonlocal::texthash(
 2441:                           keyh => 'Keyword Highlighting for Essays',
 2442:                           keyw => 'Keyword Options',
 2443:                           list => 'List',
 2444:                           past => 'Paste Selection to List',
 2445:                           high => 'Highlight Attribute',
 2446:                      );
 2447: #
 2448: # Print out the keyword options line
 2449: #
 2450: 	    $request->print(
 2451:                 '<div class="LC_columnSection">'
 2452:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2453:                .&Apache::lonhtmlcommon::funclist_from_array(
 2454:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2455:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2456:  class="page">'.$lt{'past'}.'</a>',
 2457:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2458:                     {legend => $lt{'keyw'}})
 2459:                .'</fieldset></div>'
 2460:             );
 2461: 
 2462: #
 2463: # Load the other essays for similarity check
 2464: #
 2465:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2466:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2467:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2468:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2469:                 if ($cdom ne '' && $cnum ne '') {
 2470:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2471:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2472:                         my $apath = $1.'_'.$id;
 2473:                         $apath=~s/\W/\_/gs;
 2474:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2475:                     }
 2476:                 }
 2477:             } else {
 2478: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2479: 	        $apath=&escape($apath);
 2480: 	        $apath=~s/\W/\_/gs;
 2481:                 &init_old_essays($symb,$apath,$adom,$aname);
 2482:             }
 2483:         }
 2484:     }
 2485: 
 2486: # This is where output for one specific student would start
 2487:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2488:     $request->print(
 2489:         "\n\n"
 2490:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2491:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2492:        ."\n"
 2493:     );
 2494: 
 2495:     # Show additional functions if allowed
 2496:     if ($perm{'vgr'}) {
 2497:         $request->print(
 2498:             &Apache::loncommon::track_student_link(
 2499:                 'View recent activity',
 2500:                 $uname,$udom,'check')
 2501:            .' '
 2502:         );
 2503:     }
 2504:     if ($perm{'opa'}) {
 2505:         $request->print(
 2506:             &Apache::loncommon::pprmlink(
 2507:                 &mt('Set/Change parameters'),
 2508:                 $uname,$udom,$symb,'check'));
 2509:     }
 2510: 
 2511:     # Show Problem
 2512:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2513: 	my $mode;
 2514: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2515: 	    $mode='both';
 2516: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2517: 	    $mode='text';
 2518: 	} elsif ($env{'form.vAns'} eq 'all') {
 2519: 	    $mode='answer';
 2520: 	}
 2521: 	&Apache::lonxml::clear_problem_counter();
 2522: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2523:     }
 2524: 
 2525:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2526: 
 2527:     # Display student info
 2528:     $request->print(($counter == 0 ? '' : '<br />'));
 2529: 
 2530:     my $boxtitle = &mt('Submissions');
 2531:     if ($is_tool) {
 2532:         $boxtitle = &mt('Transactions')
 2533:     }
 2534:     my $result='<div class="LC_Box">'
 2535:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2536:     $result.='<input type="hidden" name="name'.$counter.
 2537:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2538:     if (($numresp > $numessay) && !$is_tool) {
 2539:         $result.='<p class="LC_info">'
 2540:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2541:                 ."</p>\n";
 2542:     }
 2543: 
 2544:     # If any part of the problem is an essayresponse, then check for collaborators
 2545:     my $fullname;
 2546:     my $col_fullnames = [];
 2547:     if ($numessay) {
 2548: 	(my $sub_result,$fullname,$col_fullnames)=
 2549: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2550: 				 $counter);
 2551: 	$result.=$sub_result;
 2552:     }
 2553:     $request->print($result."\n");
 2554: 
 2555:     # print student answer/submission
 2556:     # Options are (1) Last submission only
 2557:     #             (2) Last submission (with detailed information for that submission)
 2558:     #             (3) All transactions (by date)
 2559:     #             (4) The whole record (with detailed information for all transactions)
 2560: 
 2561:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
 2562:         &get_last_submission(\%record,$is_tool);
 2563: 
 2564:     my $lastsubonly;
 2565: 
 2566:     if ($timestamp eq '') {
 2567:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>'; 
 2568:     } elsif ($is_tool) {
 2569:         $lastsubonly =
 2570:             '<div class="LC_grade_submissions_body">'
 2571:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
 2572:     } else {
 2573:         my ($shownsubmdate,$showngradedate);
 2574:         if ($lastsubmittime && $lastgradetime) {
 2575:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
 2576:             if ($lastgradetime > $lastsubmittime) {
 2577:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
 2578:              }
 2579:         } else {
 2580:             $shownsubmdate = $timestamp;
 2581:         }
 2582:         $lastsubonly =
 2583:             '<div class="LC_grade_submissions_body">'
 2584:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
 2585:         if ($showngradedate) {
 2586:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
 2587:         }
 2588: 
 2589: 	my %seenparts;
 2590: 	my @part_response_id = &flatten_responseType($responseType);
 2591: 	foreach my $part (@part_response_id) {
 2592: 	    my ($partid,$respid) = @{ $part };
 2593: 	    my $display_part=&get_display_part($partid,$symb);
 2594: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2595: 		if (exists($seenparts{$partid})) { next; }
 2596: 		$seenparts{$partid}=1;
 2597:                 $request->print(
 2598:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2599:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2600:                                '<a href="javascript:viewSubmitter(\''.
 2601:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2602:                                '\');" target="_self">'.
 2603:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2604:                     '<br />');
 2605: 		next;
 2606: 	    }
 2607: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2608: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2609:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2610:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2611:                     ' <span class="LC_internal_info">'.
 2612:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2613:                     '</span>&nbsp; &nbsp;'.
 2614: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2615: 		next;
 2616: 	    }
 2617: 	    foreach my $submission (@$string) {
 2618: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2619: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2620: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2621: 		# Similarity check
 2622:                 my $similar='';
 2623:                 my ($type,$trial,$rndseed);
 2624:                 if ($hide eq 'rand') {
 2625:                     $type = 'randomizetry';
 2626:                     $trial = $record{"resource.$partid.tries"};
 2627:                     $rndseed = $record{"resource.$partid.rndseed"};
 2628:                 }
 2629: 	        if ($env{'form.checkPlag'}) {
 2630: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2631: 		    &most_similar($uname,$udom,$symb,$subval);
 2632: 		    if ($osim) {
 2633: 			$osim=int($osim*100.0);
 2634:                         if ($hide eq 'anon') {
 2635:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2636:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2637:                         } else {
 2638: 			    $similar='<hr />';
 2639:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2640:                                 $similar .= '<h3><span class="LC_warning">'.
 2641:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2642:                                                 $osim,
 2643:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2644:                                             '</span></h3>';
 2645:                             } else {
 2646:                                 my %old_course_desc;
 2647:                                 if ($ocrsid ne '') {
 2648:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2649:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2650:                                     } else {
 2651:                                         my $args;
 2652:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2653:                                             $args = {'one_time' => 1};
 2654:                                         }
 2655:                                         %old_course_desc =
 2656:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2657:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2658:                                     }
 2659:                                     $similar .=
 2660:                                         '<h3><span class="LC_warning">'.
 2661:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2662:                                             $osim,
 2663:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2664:                                             $old_course_desc{'description'},
 2665:                                             $old_course_desc{'num'},
 2666:                                             $old_course_desc{'domain'}).
 2667:                                         '</span></h3>';
 2668:                                 } else {
 2669:                                     $similar .=
 2670:                                         '<h3><span class="LC_warning">'.
 2671:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2672:                                             $osim,
 2673:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2674:                                         '</span></h3>';
 2675:                                 }
 2676:                             }
 2677:                             $similar .= '<blockquote><i>'.
 2678:                                         &keywords_highlight($oessay).
 2679:                                         '</i></blockquote><hr />';
 2680:                         }
 2681: 	            }
 2682: 		}
 2683: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2684:                                      undef,$type,$trial,$rndseed);
 2685:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2686:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2687:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2688: 		    my $display_part=&get_display_part($partid,$symb);
 2689:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2690:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2691:                         ' <span class="LC_internal_info">'.
 2692:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2693:                         '</span>&nbsp; &nbsp;';
 2694: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2695: 		    if (@$files) {
 2696:                         if ($hide eq 'anon') {
 2697:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2698:                         } else {
 2699:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2700:                                         .'<br /><span class="LC_warning">';
 2701:                             if(@$files == 1) {
 2702:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2703:                             } else {
 2704:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2705:                             }
 2706:                             $lastsubonly .= '</span>';
 2707:                             foreach my $file (@$files) {
 2708:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2709:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2710:                             }
 2711:                         }
 2712: 			$lastsubonly.='<br />';
 2713:                     }
 2714:                     if ($hide eq 'anon') {
 2715:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2716:                     } else {
 2717:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2718:                         if ($draft) {
 2719:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2720:                         }
 2721:                         $subval =
 2722: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2723: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2724:                         if ($responsetype eq 'essay') {
 2725:                             $subval =~ s{\n}{<br />}g;
 2726:                         }
 2727:                         $lastsubonly.=$subval."\n";
 2728:                     }
 2729:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2730: 		    $lastsubonly.='</div>';
 2731: 		}
 2732:             }
 2733: 	}
 2734: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2735:     }
 2736:     $request->print($lastsubonly);
 2737:     if ($env{'form.lastSub'} eq 'datesub') {
 2738:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2739: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2740:     }
 2741:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2742:         my $identifier = (&canmodify($usec)? $counter : '');
 2743:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2744: 								 $env{'request.course.id'},
 2745: 								 $last,'.submission',
 2746: 								 'Apache::grades::keywords_highlight',
 2747:                                                                  $usec,$identifier));
 2748:     }
 2749:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2750: 	.$udom.'" />'."\n");
 2751:     # return if view submission with no grading option
 2752:     if (!&canmodify($usec)) {
 2753: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2754: 	return;
 2755:     } else {
 2756: 	$request->print('</div>'."\n");
 2757:     }
 2758: 
 2759:     # grading message center
 2760: 
 2761:     if ($env{'form.compmsg'}) {
 2762:         my $result='<div class="LC_Box">'.
 2763:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2764:                    '<div class="LC_grade_message_center_body">';
 2765:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2766:         my $msgfor = $givenn.' '.$lastname;
 2767:         if (scalar(@$col_fullnames) > 0) {
 2768:             my $lastone = pop(@$col_fullnames);
 2769:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2770:         }
 2771:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2772:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2773:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2774:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2775:                  ',\''.$msgfor.'\');" target="_self">'.
 2776:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2777:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2778:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2779:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2780:                  '<br />&nbsp;('.
 2781:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2782:                  '</div></div>';
 2783:         $request->print($result);
 2784:     }
 2785: 
 2786:     my %seen = ();
 2787:     my @partlist;
 2788:     my @gradePartRespid;
 2789:     my @part_response_id;
 2790:     if ($is_tool) {
 2791:         @part_response_id = ([0,'']);
 2792:     } else {
 2793:         @part_response_id = &flatten_responseType($responseType);
 2794:     }
 2795:     $request->print(
 2796:         '<div class="LC_Box">'
 2797:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2798:     );
 2799:     $request->print(&gradeBox_start());
 2800:     foreach my $part_response_id (@part_response_id) {
 2801:     	my ($partid,$respid) = @{ $part_response_id };
 2802: 	my $part_resp = join('_',@{ $part_response_id });
 2803: 	next if ($seen{$partid} > 0);
 2804: 	$seen{$partid}++;
 2805: 	push(@partlist,$partid);
 2806: 	push(@gradePartRespid,$partid.'.'.$respid);
 2807: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2808:     }
 2809:     $request->print(&gradeBox_end()); # </div>
 2810:     $request->print('</div>');
 2811: 
 2812:     $request->print('<div class="LC_grade_info_links">');
 2813:     $request->print('</div>');
 2814: 
 2815:     $result='<input type="hidden" name="partlist'.$counter.
 2816: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2817:     $result.='<input type="hidden" name="gradePartRespid'.
 2818: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2819:     my $ctr = 0;
 2820:     while ($ctr < scalar(@partlist)) {
 2821: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2822: 	    $partlist[$ctr].'" />'."\n";
 2823: 	$ctr++;
 2824:     }
 2825:     $request->print($result.''."\n");
 2826: 
 2827: # Done with printing info for one student
 2828: 
 2829:     $request->print('</div>');#LC_grade_show_user
 2830: 
 2831: 
 2832:     # print end of form
 2833:     if ($counter == $total) {
 2834:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2835: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2836: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2837: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2838: 	my $ntstu ='<select name="NTSTU">'.
 2839: 	    '<option>1</option><option>2</option>'.
 2840: 	    '<option>3</option><option>5</option>'.
 2841: 	    '<option>7</option><option>10</option></select>'."\n";
 2842: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2843: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2844:         $endform.=&mt('[_1]student(s)',$ntstu);
 2845: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2846: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2847: 	    '<input type="button" value="'.&mt('Next').'" '.
 2848: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2849:         $endform.='<span class="LC_warning">'.
 2850:                   &mt('(Next and Previous (student) do not save the scores.)').
 2851:                   '</span>'."\n" ;
 2852:         $endform.="<input type='hidden' value='".&get_increment().
 2853:             "' name='increment' />";
 2854: 	$endform.='</td></tr></table></form>';
 2855: 	$request->print($endform);
 2856:     }
 2857:     return '';
 2858: }
 2859: 
 2860: sub check_collaborators {
 2861:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2862:     my ($result,@col_fullnames);
 2863:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2864:     foreach my $part (keys(%$handgrade)) {
 2865: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2866: 					'.maxcollaborators',
 2867: 					$symb,$udom,$uname);
 2868: 	next if ($ncol <= 0);
 2869: 	$part =~ s/\_/\./g;
 2870: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2871: 	my (@good_collaborators, @bad_collaborators);
 2872: 	foreach my $possible_collaborator
 2873: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2874: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2875: 	    next if ($possible_collaborator eq '');
 2876: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2877: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2878: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2879: 	    # Doing this grep allows 'fuzzy' specification
 2880: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2881: 			       keys(%$classlist));
 2882: 	    if (! scalar(@matches)) {
 2883: 		push(@bad_collaborators, $possible_collaborator);
 2884: 	    } else {
 2885: 		push(@good_collaborators, @matches);
 2886: 	    }
 2887: 	}
 2888: 	if (scalar(@good_collaborators) != 0) {
 2889: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2890: 	    foreach my $name (@good_collaborators) {
 2891: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2892: 		push(@col_fullnames, $givenn.' '.$lastname);
 2893: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2894: 	    }
 2895: 	    $result.='</ol><br />'."\n";
 2896: 	    my ($part)=split(/\./,$part);
 2897: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2898: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2899: 		"\n";
 2900: 	}
 2901: 	if (scalar(@bad_collaborators) > 0) {
 2902: 	    $result.='<div class="LC_warning">';
 2903: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2904: 	    $result .= '</div>';
 2905: 	}         
 2906: 	if (scalar(@bad_collaborators > $ncol)) {
 2907: 	    $result .= '<div class="LC_warning">';
 2908: 	    $result .= &mt('This student has submitted too many '.
 2909: 		'collaborators.  Maximum is [_1].',$ncol);
 2910: 	    $result .= '</div>';
 2911: 	}
 2912:     }
 2913:     return ($result,$fullname,\@col_fullnames);
 2914: }
 2915: 
 2916: #--- Retrieve the last submission for all the parts
 2917: sub get_last_submission {
 2918:     my ($returnhash,$is_tool)=@_;
 2919:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
 2920:     if ($$returnhash{'version'}) {
 2921: 	my %lasthash=();
 2922:         my %prevsolved=();
 2923:         my %solved=();
 2924: 	my $version;
 2925: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2926:             my %handgraded = ();
 2927: 	    foreach my $key (sort(split(/\:/,
 2928: 					$$returnhash{$version.':keys'}))) {
 2929: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2930:                 if ($key =~ /\.([^.]+)\.regrader$/) {
 2931:                     $handgraded{$1} = 1;
 2932:                 } elsif ($key =~ /\.portfiles$/) {
 2933:                     if (($$returnhash{$version.':'.$key} ne '') &&
 2934:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
 2935:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2936:                     }
 2937:                 } elsif ($key =~ /\.submission$/) {
 2938:                     if ($$returnhash{$version.':'.$key} ne '') {
 2939:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2940:                     }
 2941:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
 2942:                     $prevsolved{$1} = $solved{$1};
 2943:                     $solved{$1} = $lasthash{$key};
 2944:                 }
 2945:             }
 2946:             foreach my $partid (keys(%handgraded)) {
 2947:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
 2948:                     (($solved{$partid} eq 'incorrect_by_override') ||
 2949:                      ($solved{$partid} eq 'correct_by_override'))) {
 2950:                     $lastgradetime = $$returnhash{$version.':timestamp'};
 2951:                 }
 2952:                 if ($solved{$partid} ne '') {
 2953:                     $prevsolved{$partid} = $solved{$partid};
 2954:                 }
 2955: 	    }
 2956:             $timestamp =
 2957:                 &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2958: 	}
 2959:         my (%typeparts,%randombytry);
 2960:         my $showsurv = 
 2961:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2962:         foreach my $key (sort(keys(%lasthash))) {
 2963:             if ($key =~ /\.type$/) {
 2964:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2965:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2966:                     ($lasthash{$key} eq 'randomizetry')) {
 2967:                     my ($ign,@parts) = split(/\./,$key);
 2968:                     pop(@parts);
 2969:                     my $id = join('.',@parts);
 2970:                     if ($lasthash{$key} eq 'randomizetry') {
 2971:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2972:                     } else {
 2973:                         unless ($showsurv) {
 2974:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2975:                         }
 2976:                     }
 2977:                     delete($lasthash{$key});
 2978:                 }
 2979:             }
 2980:         }
 2981:         my @hidden = keys(%typeparts);
 2982:         my @randomize = keys(%randombytry);
 2983: 	foreach my $key (keys(%lasthash)) {
 2984: 	    next if ($key !~ /\.submission$/);
 2985:             my $hide;
 2986:             if (@hidden) {
 2987:                 foreach my $id (@hidden) {
 2988:                     if ($key =~ /^\Q$id\E/) {
 2989:                         $hide = 'anon';
 2990:                         last;
 2991:                     }
 2992:                 }
 2993:             }
 2994:             unless ($hide) {
 2995:                 if (@randomize) {
 2996:                     foreach my $id (@randomize) {
 2997:                         if ($key =~ /^\Q$id\E/) {
 2998:                             $hide = 'rand';
 2999:                             last;
 3000:                         }
 3001:                     }
 3002:                 }
 3003:             }
 3004: 	    my ($partid,$foo) = split(/submission$/,$key);
 3005: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 3006:             push(@string, join(':', $key, $hide, $draft, (
 3007:                 ref($lasthash{$key}) eq 'ARRAY' ?
 3008:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 3009: 	}
 3010:     }
 3011:     if (!@string) {
 3012:         my $msg;
 3013:         if ($is_tool) {
 3014:             $msg = &mt('No grade passed back.');
 3015:         } else {
 3016:             $msg = &mt('Nothing submitted - no attempts.');
 3017:         }
 3018: 	$string[0] =
 3019: 	    '<span class="LC_warning">'.$msg.'</span>';
 3020:     }
 3021:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
 3022: }
 3023: 
 3024: #--- High light keywords, with style choosen by user.
 3025: sub keywords_highlight {
 3026:     my $string    = shift;
 3027:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 3028:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 3029:     (my $styleoff = $styleon) =~ s/\</\<\//;
 3030:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 3031:     foreach my $keyword (@keylist) {
 3032: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 3033:     }
 3034:     return $string;
 3035: }
 3036: 
 3037: # For Tasks provide a mechanism to display previous version for one specific student
 3038: 
 3039: sub show_previous_task_version {
 3040:     my ($request,$symb) = @_;
 3041:     if ($symb eq '') {
 3042:         $request->print(
 3043:             '<span class="LC_error">'.
 3044:             &mt('Unable to handle ambiguous references.').
 3045:             '</span>');
 3046:         return '';
 3047:     }
 3048:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 3049:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 3050:     if (!&canview($usec)) {
 3051:         $request->print(
 3052:             '<span class="LC_warning">'.
 3053:             &mt('Unable to view previous version for requested student.').
 3054:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 3055:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3056:             '</span>');
 3057:         return;
 3058:     }
 3059:     my $mode = 'both';
 3060:     my $isTask = ($symb =~/\.task$/);
 3061:     if ($isTask) {
 3062:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3063:             if ($env{'form.fullname'} eq '') {
 3064:                 $env{'form.fullname'} =
 3065:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3066:             }
 3067:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3068:             $request->print("\n\n".
 3069:                             '<div class="LC_grade_show_user">'.
 3070:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3071:                             '</h2>'."\n");
 3072:             &Apache::lonxml::clear_problem_counter();
 3073:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3074:                             {'previousversion' => $env{'form.previousversion'} }));
 3075:             $request->print("\n</div>");
 3076:         }
 3077:     }
 3078:     return;
 3079: }
 3080: 
 3081: sub choose_task_version_form {
 3082:     my ($symb,$uname,$udom,$nomenu) = @_;
 3083:     my $isTask = ($symb =~/\.task$/);
 3084:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3085:     if ($isTask) {
 3086:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3087:                                               $udom,$uname);
 3088:         if (($record{'resource.0.version'} eq '') ||
 3089:             ($record{'resource.0.version'} < 2)) {
 3090:             return ($record{'resource.0.version'},
 3091:                     $record{'resource.0.version'},$result,$js);
 3092:         } else {
 3093:             $current = $record{'resource.0.version'};
 3094:         }
 3095:         if ($env{'form.previousversion'}) {
 3096:             $displayed = $env{'form.previousversion'};
 3097:             $rowtitle = &mt('Choose another version:')
 3098:         } else {
 3099:             $displayed = $current;
 3100:             $rowtitle = &mt('Show earlier version:');
 3101:         }
 3102:         $result = '<div class="LC_left_float">';
 3103:         my $list;
 3104:         my $numversions = 0;
 3105:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3106:             if ($i == $current) {
 3107:                 if (!$env{'form.previousversion'} || $nomenu) {
 3108:                     next;
 3109:                 } else {
 3110:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3111:                     $numversions ++;
 3112:                 }
 3113:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3114:                 unless ($i == $env{'form.previousversion'}) {
 3115:                     $numversions ++;
 3116:                 }
 3117:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3118:             }
 3119:         }
 3120:         if ($numversions) {
 3121:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3122:             $result .=
 3123:                 '<form name="getprev" method="post" action=""'.
 3124:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3125:                 &Apache::loncommon::start_data_table().
 3126:                 &Apache::loncommon::start_data_table_row().
 3127:                 '<th align="left">'.$rowtitle.'</th>'.
 3128:                 '<td><select name="version">'.
 3129:                 '<option>'.&mt('Select').'</option>'.
 3130:                 $list.
 3131:                 '</select></td>'.
 3132:                 &Apache::loncommon::end_data_table_row();
 3133:             unless ($nomenu) {
 3134:                 $result .= &Apache::loncommon::start_data_table_row().
 3135:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3136:                 '<td><span class="LC_nobreak">'.
 3137:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3138:                 &mt('Yes').'</label>'.
 3139:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3140:                 '</span></td>'.
 3141:                 &Apache::loncommon::end_data_table_row();
 3142:             }
 3143:             $result .=
 3144:                 &Apache::loncommon::start_data_table_row().
 3145:                 '<th align="left">&nbsp;</th>'.
 3146:                 '<td>'.
 3147:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3148:                 '</td>'.
 3149:                 &Apache::loncommon::end_data_table_row().
 3150:                 &Apache::loncommon::end_data_table().
 3151:                 '</form>';
 3152:             $js = &previous_display_javascript($nomenu,$current);
 3153:         } elsif ($displayed && $nomenu) {
 3154:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3155:         } else {
 3156:             $result .= &mt('No previous versions to show for this student');
 3157:         }
 3158:         $result .= '</div>';
 3159:     }
 3160:     return ($current,$displayed,$result,$js);
 3161: }
 3162: 
 3163: sub previous_display_javascript {
 3164:     my ($nomenu,$current) = @_;
 3165:     my $js = <<"JSONE";
 3166: <script type="text/javascript">
 3167: // <![CDATA[
 3168: function previousVersion(uname,udom,symb) {
 3169:     var current = '$current';
 3170:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3171:     var prevstr = new RegExp("^\\\\d+\$");
 3172:     if (!prevstr.test(version)) {
 3173:         return false;
 3174:     }
 3175:     var url = '';
 3176:     if (version == current) {
 3177:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3178:     } else {
 3179:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3180:     }
 3181: JSONE
 3182:     if ($nomenu) {
 3183:         $js .= <<"JSTWO";
 3184:     document.location.href = url;
 3185: JSTWO
 3186:     } else {
 3187:         $js .= <<"JSTHREE";
 3188:     var newwin = 0;
 3189:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3190:         if (document.getprev.prevwin[i].checked == true) {
 3191:             newwin = document.getprev.prevwin[i].value;
 3192:         }
 3193:     }
 3194:     if (newwin == 1) {
 3195:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3196:         url = url+'&inhibitmenu=yes';
 3197:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3198:             previousWin = window.open(url,'',options,1);
 3199:         } else {
 3200:             previousWin.location.href = url;
 3201:         }
 3202:         previousWin.focus();
 3203:         return false;
 3204:     } else {
 3205:         document.location.href = url;
 3206:         return false;
 3207:     }
 3208: JSTHREE
 3209:     }
 3210:     $js .= <<"ENDJS";
 3211:     return false;
 3212: }
 3213: // ]]>
 3214: </script>
 3215: ENDJS
 3216: 
 3217: }
 3218: 
 3219: #--- Called from submission routine
 3220: sub processHandGrade {
 3221:     my ($request,$symb) = @_;
 3222:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3223:     my $button = $env{'form.gradeOpt'};
 3224:     my $ngrade = $env{'form.NCT'};
 3225:     my $ntstu  = $env{'form.NTSTU'};
 3226:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3227:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3228:     my ($res_error,%queueable);
 3229:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3230:     if ($res_error) {
 3231:         $request->print(&navmap_errormsg());
 3232:         return;
 3233:     } else {
 3234:         foreach my $part (@{$partlist}) {
 3235:             if (ref($responseType->{$part}) eq 'HASH') {
 3236:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3237:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3238:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3239:                         $queueable{$part} = 1;
 3240:                         last;
 3241:                     }
 3242:                 }
 3243:             }
 3244:         }
 3245:     }
 3246: 
 3247:     if ($button eq 'Save & Next') {
 3248: 	my $ctr = 0;
 3249: 	while ($ctr < $ngrade) {
 3250: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3251: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3252:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3253: 	    if ($errorflag eq 'no_score') {
 3254: 		$ctr++;
 3255: 		next;
 3256: 	    }
 3257: 	    if ($errorflag eq 'not_allowed') {
 3258: 		$request->print(
 3259:                     '<span class="LC_error">'
 3260:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3261:                    .'</span>');
 3262: 		$ctr++;
 3263: 		next;
 3264: 	    }
 3265:             if ($numhidden) {
 3266:                 $request->print(
 3267:                     '<span class="LC_info">'
 3268:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3269:                    .'</span><br />');
 3270:             }
 3271: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3272: 	    my ($subject,$message,$msgstatus) = ('','','');
 3273: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3274:             my ($feedurl,$showsymb) =
 3275: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3276: 	    my $messagetail;
 3277: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3278: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3279: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3280: 		$subject.=' ['.$restitle.']';
 3281: 		my (@msgnum) = split(/,/,$includemsg);
 3282: 		foreach (@msgnum) {
 3283: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3284: 		}
 3285: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3286: 		if ($env{'form.withgrades'.$ctr}) {
 3287: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3288: 		    $messagetail = " for <a href=\"".
 3289: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3290: 		}
 3291: 		$msgstatus = 
 3292:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3293: 						     $message.$messagetail,
 3294:                                                      undef,$feedurl,undef,
 3295:                                                      undef,undef,$showsymb,
 3296:                                                      $restitle);
 3297: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3298: 				$msgstatus.'<br />');
 3299: 	    }
 3300: 	    if ($env{'form.collaborator'.$ctr}) {
 3301: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3302: 		foreach my $collabstr (@collabstrs) {
 3303: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3304: 		    foreach my $collaborator (@collaborators) {
 3305: 			my ($errorflag,$pts,$wgt) = 
 3306: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3307: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3308: 			if ($errorflag eq 'not_allowed') {
 3309: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3310: 			    next;
 3311: 			} elsif ($message ne '') {
 3312: 			    my ($baseurl,$showsymb) = 
 3313: 				&get_feedurl_and_symb($symb,$collaborator,
 3314: 						      $udom);
 3315: 			    if ($env{'form.withgrades'.$ctr}) {
 3316: 				$messagetail = " for <a href=\"".
 3317:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3318: 			    }
 3319: 			    $msgstatus = 
 3320: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3321: 			}
 3322: 		    }
 3323: 		}
 3324: 	    }
 3325: 	    $ctr++;
 3326: 	}
 3327:     }
 3328: 
 3329:     my %keyhash = ();
 3330:     if ($numessay) {
 3331: 	# Keywords sorted in alphabatical order
 3332: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3333: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3334: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3335: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3336: 	$env{'form.keywords'} = join(' ',@keywords);
 3337: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3338: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3339: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3340: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3341: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3342:     }
 3343: 
 3344:     if ($env{'form.compmsg'}) {
 3345: 	# message center - Order of message gets changed. Blank line is eliminated.
 3346: 	# New messages are saved in env for the next student.
 3347: 	# All messages are saved in nohist_handgrade.db
 3348: 	my ($ctr,$idx) = (1,1);
 3349: 	while ($ctr <= $env{'form.savemsgN'}) {
 3350: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3351: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3352: 		$idx++;
 3353: 	    }
 3354: 	    $ctr++;
 3355: 	}
 3356: 	$ctr = 0;
 3357: 	while ($ctr < $ngrade) {
 3358: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3359: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3360: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3361: 	        $idx++;
 3362: 	    }
 3363: 	    $ctr++;
 3364: 	}
 3365: 	$env{'form.savemsgN'} = --$idx;
 3366: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3367:     }
 3368:     if (($numessay) || ($env{'form.compmsg'})) {
 3369:         my $putresult = &Apache::lonnet::put
 3370:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3371:     }
 3372: 
 3373:     # Called by Save & Refresh from Highlight Attribute Window
 3374:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3375:     if ($env{'form.refresh'} eq 'on') {
 3376: 	my ($ctr,$total) = (0,0);
 3377: 	while ($ctr < $ngrade) {
 3378: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3379: 	    $ctr++;
 3380: 	}
 3381: 	$env{'form.NTSTU'}=$ngrade;
 3382: 	$ctr = 0;
 3383: 	while ($ctr < $total) {
 3384: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3385: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3386: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3387: 	    &submission($request,$ctr,$total-1,$symb);
 3388: 	    $ctr++;
 3389: 	}
 3390: 	return '';
 3391:     }
 3392: 
 3393:     # Get the next/previous one or group of students
 3394:     my $firststu = $env{'form.unamedom0'};
 3395:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3396:     my $ctr = 2;
 3397:     while ($laststu eq '') {
 3398: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3399: 	$ctr++;
 3400: 	$laststu = $firststu if ($ctr > $ngrade);
 3401:     }
 3402: 
 3403:     my (@parsedlist,@nextlist);
 3404:     my ($nextflg) = 0;
 3405:     foreach my $item (sort 
 3406: 	     {
 3407: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3408: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3409: 		 }
 3410: 		 return $a cmp $b;
 3411: 	     } (keys(%$fullname))) {
 3412: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3413: 	    push(@parsedlist,$item);
 3414: 	}
 3415: 	$nextflg = 1 if ($item eq $laststu);
 3416: 	if ($button eq 'Previous') {
 3417: 	    last if ($item eq $firststu);
 3418: 	    push(@parsedlist,$item);
 3419: 	}
 3420:     }
 3421:     $ctr = 0;
 3422:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3423:     foreach my $student (@parsedlist) {
 3424: 	my $submitonly=$env{'form.submitonly'};
 3425: 	my ($uname,$udom) = split(/:/,$student);
 3426: 	
 3427: 	if ($submitonly eq 'queued') {
 3428: 	    my %queue_status = 
 3429: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3430: 							$udom,$uname);
 3431: 	    next if (!defined($queue_status{'gradingqueue'}));
 3432: 	}
 3433: 
 3434: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3435: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3436: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3437: 	    my $submitted = 0;
 3438: 	    my $ungraded = 0;
 3439: 	    my $incorrect = 0;
 3440: 	    foreach my $item (keys(%status)) {
 3441: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3442: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3443: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3444: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3445: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3446: 		    $submitted = 0;
 3447: 		}
 3448: 	    }
 3449: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3450: 				     $submitonly eq 'incorrect' ||
 3451: 				     $submitonly eq 'graded'));
 3452: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3453: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3454: 	}
 3455: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3456: 	last if ($ctr == $ntstu);
 3457: 	$ctr++;
 3458:     }
 3459: 
 3460:     $ctr = 0;
 3461:     my $total = scalar(@nextlist)-1;
 3462: 
 3463:     foreach (sort(@nextlist)) {
 3464: 	my ($uname,$udom,$submitter) = split(/:/);
 3465: 	$env{'form.student'}  = $uname;
 3466: 	$env{'form.userdom'}  = $udom;
 3467: 	$env{'form.fullname'} = $$fullname{$_};
 3468: 	&submission($request,$ctr,$total,$symb);
 3469: 	$ctr++;
 3470:     }
 3471:     if ($total < 0) {
 3472: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3473: 	$request->print($the_end);
 3474:     }
 3475:     return '';
 3476: }
 3477: 
 3478: #---- Save the score and award for each student, if changed
 3479: sub saveHandGrade {
 3480:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3481:     my @version_parts;
 3482:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3483: 					   $env{'request.course.id'});
 3484:     if (!&canmodify($usec)) { return('not_allowed'); }
 3485:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3486:     my @parts_graded;
 3487:     my %newrecord  = ();
 3488:     my ($pts,$wgt,$totchg) = ('','',0);
 3489:     my %aggregate = ();
 3490:     my $aggregateflag = 0;
 3491:     if ($env{'form.HIDE'.$newflg}) {
 3492:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3493:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3494:         $totchg += $numchgs;
 3495:     }
 3496:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3497:     foreach my $new_part (@parts) {
 3498: 	#collaborator ($submi may vary for different parts
 3499: 	if ($submitter && $new_part ne $part) { next; }
 3500: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3501: 	if ($dropMenu eq 'excused') {
 3502: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3503: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3504: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3505: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3506: 		}
 3507: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3508: 	    }
 3509: 	} elsif ($dropMenu eq 'reset status'
 3510: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3511: 	    foreach my $key (keys(%record)) {
 3512: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3513: 	    }
 3514: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3515: 		"$env{'user.name'}:$env{'user.domain'}";
 3516:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3517: 
 3518:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3519: 					       [$new_part]);
 3520:             my $aggtries =$totaltries;
 3521:             if ($last_resets{$new_part}) {
 3522:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3523: 					   $new_part);
 3524:             }
 3525: 
 3526:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3527:             if ($aggtries > 0) {
 3528:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3529:                 $aggregateflag = 1;
 3530:             }
 3531: 	} elsif ($dropMenu eq '') {
 3532: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3533: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3534: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3535: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3536: 		next;
 3537: 	    }
 3538: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3539: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3540: 	    my $partial= $pts/$wgt;
 3541: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3542: 		#do not update score for part if not changed.
 3543:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3544: 		next;
 3545: 	    } else {
 3546: 	        push(@parts_graded,$new_part);
 3547: 	    }
 3548: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3549: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3550: 	    }
 3551: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3552: 	    if ($partial == 0) {
 3553: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3554: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3555: 		}
 3556: 	    } else {
 3557: 		if ($record{$reckey} ne 'correct_by_override') {
 3558: 		    $newrecord{$reckey} = 'correct_by_override';
 3559: 		}
 3560: 	    }	    
 3561: 	    if ($submitter && 
 3562: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3563: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3564: 	    }
 3565: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3566: 		"$env{'user.name'}:$env{'user.domain'}";
 3567: 	}
 3568: 	# unless problem has been graded, set flag to version the submitted files
 3569: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3570: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3571: 	        $dropMenu eq 'reset status')
 3572: 	   {
 3573: 	    push(@version_parts,$new_part);
 3574: 	}
 3575:     }
 3576:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3577:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3578: 
 3579:     if (%newrecord) {
 3580:         if (@version_parts) {
 3581:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3582:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3583: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3584: 	    foreach my $new_part (@version_parts) {
 3585: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3586: 				$new_part,\%newrecord);
 3587: 	    }
 3588:         }
 3589: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3590: 				$env{'request.course.id'},$domain,$stuname);
 3591: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3592: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3593:     }
 3594:     if ($aggregateflag) {
 3595:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3596: 			      $cdom,$cnum);
 3597:     }
 3598:     return ('',$pts,$wgt,$totchg);
 3599: }
 3600: 
 3601: sub makehidden {
 3602:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3603:     return unless (ref($record) eq 'HASH');
 3604:     my %modified;
 3605:     my $numchanged = 0;
 3606:     if (exists($record->{$version.':keys'})) {
 3607:         my $partsregexp = $parts;
 3608:         $partsregexp =~ s/,/|/g;
 3609:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3610:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3611:                  my $item = $1;
 3612:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3613:                      $modified{$key} = $record->{$version.':'.$key};
 3614:                  }
 3615:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3616:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3617:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3618:                 $modified{$key} = $record->{$version.':'.$key};
 3619:             }
 3620:         }
 3621:         if (keys(%modified)) {
 3622:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3623:                                           $domain,$stuname,$tolog) eq 'ok') {
 3624:                 $numchanged ++;
 3625:             }
 3626:         }
 3627:     }
 3628:     return $numchanged;
 3629: }
 3630: 
 3631: sub check_and_remove_from_queue {
 3632:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3633:     my @ungraded_parts;
 3634:     foreach my $part (@{$parts}) {
 3635: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3636: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3637: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3638: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3639: 		) {
 3640:             if ($queueable->{$part}) {
 3641: 	        push(@ungraded_parts, $part);
 3642:             }
 3643: 	}
 3644:     }
 3645:     if ( !@ungraded_parts ) {
 3646: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3647: 					       $cnum,$domain,$stuname);
 3648:     }
 3649: }
 3650: 
 3651: sub handback_files {
 3652:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3653:     my $portfolio_root = '/userfiles/portfolio';
 3654:     my $res_error;
 3655:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3656:     if ($res_error) {
 3657:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3658:         return;
 3659:     }
 3660:     my @handedback;
 3661:     my $file_msg;
 3662:     my @part_response_id = &flatten_responseType($responseType);
 3663:     foreach my $part_response_id (@part_response_id) {
 3664:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3665: 	my $part_resp = join('_',@{ $part_response_id });
 3666:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3667:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3668:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3669:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3670:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3671:                     my ($directory,$answer_file) = 
 3672:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3673:                     my ($answer_name,$answer_ver,$answer_ext) =
 3674: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3675: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3676:                     my $getpropath = 1;
 3677:                     my ($dir_list,$listerror) =
 3678:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3679:                                                  $domain,$stuname,$getpropath);
 3680: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3681:                     # fix filename
 3682:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3683:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3684:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3685:             	                                $save_file_name);
 3686:                     if ($result !~ m|^/uploaded/|) {
 3687:                         $request->print('<br /><span class="LC_error">'.
 3688:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3689:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3690:                                         '</span>');
 3691:                     } else {
 3692:                         # mark the file as read only
 3693:                         push(@handedback,$save_file_name);
 3694: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3695: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3696: 			}
 3697:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3698: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3699:                     }
 3700:                     $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>'));
 3701:                 }
 3702:             }
 3703:         }
 3704:     }
 3705:     if (@handedback > 0) {
 3706:         $request->print('<br />');
 3707:         my @what = ($symb,$env{'request.course.id'},'handback');
 3708:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3709:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3710:         my ($subject,$message);
 3711:         if (scalar(@handedback) == 1) {
 3712:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3713:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3714:         } else {
 3715:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3716:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3717:         }
 3718:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3719:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3720:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3721:         my ($feedurl,$showsymb) =
 3722:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3723:         my $restitle = &Apache::lonnet::gettitle($symb);
 3724:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3725:         my $msgstatus =
 3726:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3727:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3728:                  $restitle);
 3729:         if ($msgstatus) {
 3730:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3731:         }
 3732:     }
 3733:     return;
 3734: }
 3735: 
 3736: sub get_feedurl_and_symb {
 3737:     my ($symb,$uname,$udom) = @_;
 3738:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3739:     $url = &Apache::lonnet::clutter($url);
 3740:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3741: 					$symb,$udom,$uname);
 3742:     if ($encrypturl =~ /^yes$/i) {
 3743: 	&Apache::lonenc::encrypted(\$url,1);
 3744: 	&Apache::lonenc::encrypted(\$symb,1);
 3745:     }
 3746:     return ($url,$symb);
 3747: }
 3748: 
 3749: sub get_submitted_files {
 3750:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3751:     my @files;
 3752:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3753:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3754:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3755:     	    push(@files,$file_url.$file);
 3756:         }
 3757:     }
 3758:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3759:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3760:     }
 3761:     return (\@files);
 3762: }
 3763: 
 3764: # ----------- Provides number of tries since last reset.
 3765: sub get_num_tries {
 3766:     my ($record,$last_reset,$part) = @_;
 3767:     my $timestamp = '';
 3768:     my $num_tries = 0;
 3769:     if ($$record{'version'}) {
 3770:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3771:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3772:                 $timestamp = $$record{$version.':timestamp'};
 3773:                 if ($timestamp > $last_reset) {
 3774:                     $num_tries ++;
 3775:                 } else {
 3776:                     last;
 3777:                 }
 3778:             }
 3779:         }
 3780:     }
 3781:     return $num_tries;
 3782: }
 3783: 
 3784: # ----------- Determine decrements required in aggregate totals 
 3785: sub decrement_aggs {
 3786:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3787:     my %decrement = (
 3788:                         attempts => 0,
 3789:                         users => 0,
 3790:                         correct => 0
 3791:                     );
 3792:     $decrement{'attempts'} = $aggtries;
 3793:     if ($solvedstatus =~ /^correct/) {
 3794:         $decrement{'correct'} = 1;
 3795:     }
 3796:     if ($aggtries == $totaltries) {
 3797:         $decrement{'users'} = 1;
 3798:     }
 3799:     foreach my $type (keys(%decrement)) {
 3800:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3801:     }
 3802:     return;
 3803: }
 3804: 
 3805: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3806: sub get_last_resets {
 3807:     my ($symb,$courseid,$partids) =@_;
 3808:     my %last_resets;
 3809:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3810:     my $cname = $env{'course.'.$courseid.'.num'};
 3811:     my @keys;
 3812:     foreach my $part (@{$partids}) {
 3813: 	push(@keys,"$symb\0$part\0resettime");
 3814:     }
 3815:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3816: 				     $cdom,$cname);
 3817:     foreach my $part (@{$partids}) {
 3818: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3819:     }
 3820:     return %last_resets;
 3821: }
 3822: 
 3823: # ----------- Handles creating versions for portfolio files as answers
 3824: sub version_portfiles {
 3825:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3826:     my $version_parts = join('|',@$v_flag);
 3827:     my @returned_keys;
 3828:     my $parts = join('|', @$parts_graded);
 3829:     foreach my $key (keys(%$record)) {
 3830:         my $new_portfiles;
 3831:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3832:             my @versioned_portfiles;
 3833:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3834:             if (@portfiles) {
 3835:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3836:                                                       \@versioned_portfiles);
 3837:             }
 3838:             $$record{$key} = join(',',@versioned_portfiles);
 3839:             push(@returned_keys,$key);
 3840:         }
 3841:     } 
 3842:     return (@returned_keys);   
 3843: }
 3844: 
 3845: #--------------------------------------------------------------------------------------
 3846: #
 3847: #-------------------------- Next few routines handles grading by section or whole class
 3848: #
 3849: #--- Javascript to handle grading by section or whole class
 3850: sub viewgrades_js {
 3851:     my ($request) = shift;
 3852: 
 3853:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3854:     &js_escape(\$alertmsg);
 3855:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3856:    function writePoint(partid,weight,point) {
 3857: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3858: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3859: 	if (point == "textval") {
 3860: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3861: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3862: 		alert("$alertmsg"+parseFloat(point));
 3863: 		var resetbox = false;
 3864: 		for (var i=0; i<radioButton.length; i++) {
 3865: 		    if (radioButton[i].checked) {
 3866: 			textbox.value = i;
 3867: 			resetbox = true;
 3868: 		    }
 3869: 		}
 3870: 		if (!resetbox) {
 3871: 		    textbox.value = "";
 3872: 		}
 3873: 		return;
 3874: 	    }
 3875: 	    if (parseFloat(point) > parseFloat(weight)) {
 3876: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3877: 				   ") greater than the weight for the part. Accept?");
 3878: 		if (resp == false) {
 3879: 		    textbox.value = "";
 3880: 		    return;
 3881: 		}
 3882: 	    }
 3883: 	    for (var i=0; i<radioButton.length; i++) {
 3884: 		radioButton[i].checked=false;
 3885: 		if (parseFloat(point) == i) {
 3886: 		    radioButton[i].checked=true;
 3887: 		}
 3888: 	    }
 3889: 
 3890: 	} else {
 3891: 	    textbox.value = parseFloat(point);
 3892: 	}
 3893: 	for (i=0;i<document.classgrade.total.value;i++) {
 3894: 	    var user = document.classgrade["ctr"+i].value;
 3895: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3896: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3897: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3898: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3899: 	    if (saveval != "correct") {
 3900: 		scorename.value = point;
 3901: 		if (selname[0].selected != true) {
 3902: 		    selname[0].selected = true;
 3903: 		}
 3904: 	    }
 3905: 	}
 3906: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3907:     }
 3908: 
 3909:     function writeRadText(partid,weight) {
 3910: 	var selval   = document.classgrade["SELVAL_"+partid];
 3911: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3912:         var override = document.classgrade["FORCE_"+partid].checked;
 3913: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3914: 	if (selval[1].selected || selval[2].selected) {
 3915: 	    for (var i=0; i<radioButton.length; i++) {
 3916: 		radioButton[i].checked=false;
 3917: 
 3918: 	    }
 3919: 	    textbox.value = "";
 3920: 
 3921: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3922: 		var user = document.classgrade["ctr"+i].value;
 3923: 		user = user.replace(new RegExp(':', 'g'),"_");
 3924: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3925: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3926: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3927: 		if ((saveval != "correct") || override) {
 3928: 		    scorename.value = "";
 3929: 		    if (selval[1].selected) {
 3930: 			selname[1].selected = true;
 3931: 		    } else {
 3932: 			selname[2].selected = true;
 3933: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3934: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3935: 		    }
 3936: 		}
 3937: 	    }
 3938: 	} else {
 3939: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3940: 		var user = document.classgrade["ctr"+i].value;
 3941: 		user = user.replace(new RegExp(':', 'g'),"_");
 3942: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3943: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3944: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3945: 		if ((saveval != "correct") || override) {
 3946: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3947: 		    selname[0].selected = true;
 3948: 		}
 3949: 	    }
 3950: 	}	    
 3951:     }
 3952: 
 3953:     function changeSelect(partid,user) {
 3954: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3955: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3956: 	var point  = textbox.value;
 3957: 	var weight = document.classgrade["weight_"+partid].value;
 3958: 
 3959: 	if (isNaN(point) || parseFloat(point) < 0) {
 3960: 	    alert("$alertmsg"+parseFloat(point));
 3961: 	    textbox.value = "";
 3962: 	    return;
 3963: 	}
 3964: 	if (parseFloat(point) > parseFloat(weight)) {
 3965: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3966: 			       ") greater than the weight of the part. Accept?");
 3967: 	    if (resp == false) {
 3968: 		textbox.value = "";
 3969: 		return;
 3970: 	    }
 3971: 	}
 3972: 	selval[0].selected = true;
 3973:     }
 3974: 
 3975:     function changeOneScore(partid,user) {
 3976: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3977: 	if (selval[1].selected || selval[2].selected) {
 3978: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3979: 	    if (selval[2].selected) {
 3980: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3981: 	    }
 3982:         }
 3983:     }
 3984: 
 3985:     function resetEntry(numpart) {
 3986: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3987: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3988: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3989: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3990: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3991: 	    for (var i=0; i<radioButton.length; i++) {
 3992: 		radioButton[i].checked=false;
 3993: 
 3994: 	    }
 3995: 	    textbox.value = "";
 3996: 	    selval[0].selected = true;
 3997: 
 3998: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3999: 		var user = document.classgrade["ctr"+i].value;
 4000: 		user = user.replace(new RegExp(':', 'g'),"_");
 4001: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 4002: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 4003: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 4004: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 4005: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 4006: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 4007: 		if (saveselval == "excused") {
 4008: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 4009: 		} else {
 4010: 		    if (selname[0].selected == false) {selname[0].selected = true};
 4011: 		}
 4012: 	    }
 4013: 	}
 4014:     }
 4015: 
 4016: VIEWJAVASCRIPT
 4017: }
 4018: 
 4019: #--- show scores for a section or whole class w/ option to change/update a score
 4020: sub viewgrades {
 4021:     my ($request,$symb) = @_;
 4022:     my ($is_tool,$toolsymb);
 4023:     if ($symb =~ /ext\.tool$/) {
 4024:         $is_tool = 1;
 4025:         $toolsymb = $symb;
 4026:     }
 4027:     &viewgrades_js($request);
 4028: 
 4029:     #need to make sure we have the correct data for later EXT calls, 
 4030:     #thus invalidate the cache
 4031:     &Apache::lonnet::devalidatecourseresdata(
 4032:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4033:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4034:     &Apache::lonnet::clear_EXT_cache_status();
 4035: 
 4036:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 4037: 
 4038:     #view individual student submission form - called using Javascript viewOneStudent
 4039:     $result.=&jscriptNform($symb);
 4040: 
 4041:     #beginning of class grading form
 4042:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4043:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4044: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4045: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4046: 	&build_section_inputs().
 4047: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4048: 
 4049:     #retrieve selected groups
 4050:     my (@groups,$group_display);
 4051:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4052:     if (grep(/^all$/,@groups)) {
 4053:         @groups = ('all');
 4054:     } elsif (grep(/^none$/,@groups)) {
 4055:         @groups = ('none');
 4056:     } elsif (@groups > 0) {
 4057:         $group_display = join(', ',@groups);
 4058:     }
 4059: 
 4060:     my ($common_header,$specific_header,@sections,$section_display);
 4061:     if ($env{'request.course.sec'} ne '') {
 4062:         @sections = ($env{'request.course.sec'});
 4063:     } else {
 4064:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4065:     }
 4066: 
 4067: # Check if Save button should be usable
 4068:     my $disabled = ' disabled="disabled"';
 4069:     if ($perm{'mgr'}) {
 4070:         if (grep(/^all$/,@sections)) {
 4071:             undef($disabled);
 4072:         } else {
 4073:             foreach my $sec (@sections) {
 4074:                 if (&canmodify($sec)) {
 4075:                     undef($disabled);
 4076:                     last;
 4077:                 }
 4078:             }
 4079:         }
 4080:     }
 4081:     if (grep(/^all$/,@sections)) {
 4082:         @sections = ('all');
 4083:         if ($group_display) {
 4084:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4085:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4086:         } elsif (grep(/^none$/,@groups)) {
 4087:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4088:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4089:         } else {
 4090: 	    $common_header = &mt('Assign Common Grade to Class');
 4091:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4092:         }
 4093:     } elsif (grep(/^none$/,@sections)) {
 4094:         @sections = ('none');
 4095:         if ($group_display) {
 4096:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4097:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4098:         } elsif (grep(/^none$/,@groups)) {
 4099:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4100:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4101:         } else {
 4102:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4103: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4104:         }
 4105:     } else {
 4106:         $section_display = join (", ",@sections);
 4107:         if ($group_display) {
 4108:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4109:                                  $section_display,$group_display);
 4110:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4111:                                    $section_display,$group_display);
 4112:         } elsif (grep(/^none$/,@groups)) {
 4113:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4114:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4115:         } else {
 4116:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4117: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4118:         }
 4119:     }
 4120:     my %submit_types = &substatus_options();
 4121:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4122: 
 4123:     if ($env{'form.submitonly'} eq 'all') {
 4124:         $result.= '<h3>'.$common_header.'</h3>';
 4125:     } else {
 4126:         my $text;
 4127:         if ($is_tool) {
 4128:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4129:         } else {
 4130:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4131:         }
 4132:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4133:     }
 4134:     $result .= &Apache::loncommon::start_data_table();
 4135:     #radio buttons/text box for assigning points for a section or class.
 4136:     #handles different parts of a problem
 4137:     my $res_error;
 4138:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4139:     if ($res_error) {
 4140:         return &navmap_errormsg();
 4141:     }
 4142:     my %weight = ();
 4143:     my $ctsparts = 0;
 4144:     my %seen = ();
 4145:     my @part_response_id;
 4146:     if ($is_tool) {
 4147:         @part_response_id = ([0,'']);
 4148:     } else {
 4149:         @part_response_id = &flatten_responseType($responseType);
 4150:     }
 4151:     foreach my $part_response_id (@part_response_id) {
 4152:     	my ($partid,$respid) = @{ $part_response_id };
 4153: 	my $part_resp = join('_',@{ $part_response_id });
 4154: 	next if $seen{$partid};
 4155: 	$seen{$partid}++;
 4156: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4157: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4158: 
 4159: 	my $display_part=&get_display_part($partid,$symb);
 4160: 	my $radio.='<table border="0"><tr>';  
 4161: 	my $ctr = 0;
 4162: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4163: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4164: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4165: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4166: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4167: 	    $ctr++;
 4168: 	}
 4169: 	$radio.='</tr></table>';
 4170: 	my $line = '<input type="text" name="TEXTVAL_'.
 4171: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4172: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4173: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4174:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4175:             '<select name="SELVAL_'.$partid.'" '.
 4176:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4177:                 $weight{$partid}.')"> '.
 4178: 	    '<option selected="selected"> </option>'.
 4179: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4180: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4181: 	    '</select></td>'.
 4182:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4183: 	$line.='<input type="hidden" name="partid_'.
 4184: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4185: 	$line.='<input type="hidden" name="weight_'.
 4186: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4187: 
 4188: 	$result.=
 4189: 	    &Apache::loncommon::start_data_table_row()."\n".
 4190: 	    '<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>'.
 4191: 	    &Apache::loncommon::end_data_table_row()."\n";
 4192: 	$ctsparts++;
 4193:     }
 4194:     $result.=&Apache::loncommon::end_data_table()."\n".
 4195: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4196:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4197: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4198: 
 4199:     #table listing all the students in a section/class
 4200:     #header of table
 4201:     if ($env{'form.submitonly'} eq 'all') {
 4202:         $result.= '<h3>'.$specific_header.'</h3>';
 4203:     } else {
 4204:         my $text;
 4205:         if ($is_tool) {
 4206:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4207:         } else {
 4208:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4209:         }
 4210:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4211:     }
 4212:     $result.= &Apache::loncommon::start_data_table().
 4213: 	      &Apache::loncommon::start_data_table_header_row().
 4214: 	      '<th>'.&mt('No.').'</th>'.
 4215: 	      '<th>'.&nameUserString('header')."</th>\n";
 4216:     my $partserror;
 4217:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4218:     if ($partserror) {
 4219:         return &navmap_errormsg();
 4220:     }
 4221:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4222:     my @partids = ();
 4223:     foreach my $part (@parts) {
 4224: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4225:         my $narrowtext = &mt('Tries');
 4226: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4227: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4228: 	my ($partid) = &split_part_type($part);
 4229:         push(@partids,$partid);
 4230: #
 4231: # FIXME: Looks like $display looks at English text
 4232: #
 4233: 	my $display_part=&get_display_part($partid,$symb);
 4234: 	if ($display =~ /^Partial Credit Factor/) {
 4235: 	    $result.='<th>'.
 4236: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4237: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4238: 	    next;
 4239: 	    
 4240: 	} else {
 4241: 	    if ($display =~ /Problem Status/) {
 4242: 		my $grade_status_mt = &mt('Grade Status');
 4243: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4244: 	    }
 4245: 	    my $part_mt = &mt('Part:');
 4246: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4247: 	}
 4248: 
 4249: 	$result.='<th>'.$display.'</th>'."\n";
 4250:     }
 4251:     $result.=&Apache::loncommon::end_data_table_header_row();
 4252: 
 4253:     my %last_resets = 
 4254: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4255: 
 4256:     #get info for each student
 4257:     #list all the students - with points and grade status
 4258:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4259:     my $ctr = 0;
 4260:     foreach (sort 
 4261: 	     {
 4262: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4263: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4264: 		 }
 4265: 		 return $a cmp $b;
 4266: 	     } (keys(%$fullname))) {
 4267: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4268: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4269:     }
 4270:     $result.=&Apache::loncommon::end_data_table();
 4271:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4272:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4273: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4274:     if ($ctr == 0) {
 4275:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4276:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4277:                 '<span class="LC_warning">';
 4278:         if ($env{'form.submitonly'} eq 'all') {
 4279:             if (grep(/^all$/,@sections)) {
 4280:                 if (grep(/^all$/,@groups)) {
 4281:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4282:                                    $stu_status);
 4283:                 } elsif (grep(/^none$/,@groups)) {
 4284:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4285:                                    $stu_status); 
 4286:                 } else {
 4287:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4288:                                    $group_display,$stu_status);
 4289:                 }
 4290:             } elsif (grep(/^none$/,@sections)) {
 4291:                 if (grep(/^all$/,@groups)) {
 4292:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4293:                                    $stu_status);
 4294:                 } elsif (grep(/^none$/,@groups)) {
 4295:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4296:                                    $stu_status);
 4297:                 } else {
 4298:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4299:                                    $group_display,$stu_status);
 4300:                 }
 4301:             } else {
 4302:                 if (grep(/^all$/,@groups)) {
 4303:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4304:                                    $section_display,$stu_status);
 4305:                 } elsif (grep(/^none$/,@groups)) {
 4306:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4307:                                    $section_display,$stu_status);
 4308:                 } else {
 4309:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4310:                                    $section_display,$group_display,$stu_status);
 4311:                 }
 4312:             }
 4313:         } else {
 4314:             if (grep(/^all$/,@sections)) {
 4315:                 if (grep(/^all$/,@groups)) {
 4316:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4317:                                    $stu_status,$submission_status);
 4318:                 } elsif (grep(/^none$/,@groups)) {
 4319:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4320:                                    $stu_status,$submission_status);
 4321:                 } else {
 4322:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4323:                                    $group_display,$stu_status,$submission_status);
 4324:                 }
 4325:             } elsif (grep(/^none$/,@sections)) {
 4326:                 if (grep(/^all$/,@groups)) {
 4327:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4328:                                    $stu_status,$submission_status);
 4329:                 } elsif (grep(/^none$/,@groups)) {
 4330:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4331:                                    $stu_status,$submission_status);
 4332:                 } else {
 4333:                     $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.',
 4334:                                    $group_display,$stu_status,$submission_status);
 4335:                 }
 4336:             } else {
 4337:                 if (grep(/^all$/,@groups)) {
 4338: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4339: 	                           $section_display,$stu_status,$submission_status);
 4340:                 } elsif (grep(/^none$/,@groups)) {
 4341:                     $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.',
 4342:                                    $section_display,$stu_status,$submission_status);
 4343:                 } else {
 4344:                     $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.',
 4345:                                    $section_display,$group_display,$stu_status,$submission_status);
 4346:                 }
 4347:             }
 4348:         }
 4349: 	$result .= '</span><br />';
 4350:     }
 4351:     return $result;
 4352: }
 4353: 
 4354: #--- call by previous routine to display each student who satisfies submission filter. 
 4355: sub viewstudentgrade {
 4356:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4357:     my ($uname,$udom) = split(/:/,$student);
 4358:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4359:     my $submitonly = $env{'form.submitonly'};
 4360:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4361:         my %partstatus = ();
 4362:         if (ref($parts) eq 'ARRAY') {
 4363:             foreach my $apart (@{$parts}) {
 4364:                 my ($part,$type) = &split_part_type($apart);
 4365:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4366:                 $status = 'nothing' if ($status eq '');
 4367:                 $partstatus{$part}      = $status;
 4368:                 my $subkey = "resource.$part.submitted_by";
 4369:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4370:             }
 4371:             my $submitted = 0;
 4372:             my $graded = 0;
 4373:             my $incorrect = 0;
 4374:             foreach my $key (keys(%partstatus)) {
 4375:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4376:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4377:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4378: 
 4379:                 my $partid = (split(/\./,$key))[1];
 4380:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4381:                     $submitted = 0;
 4382:                 }
 4383:             }
 4384:             return if (!$submitted && ($submitonly eq 'yes' ||
 4385:                                        $submitonly eq 'incorrect' ||
 4386:                                        $submitonly eq 'graded'));
 4387:             return if (!$graded && ($submitonly eq 'graded'));
 4388:             return if (!$incorrect && $submitonly eq 'incorrect');
 4389:         }
 4390:     }
 4391:     if ($submitonly eq 'queued') {
 4392:         my ($cdom,$cnum) = split(/_/,$courseid);
 4393:         my %queue_status =
 4394:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4395:                                                     $udom,$uname);
 4396:         return if (!defined($queue_status{'gradingqueue'}));
 4397:     }
 4398:     $$ctr++;
 4399:     my %aggregates = ();
 4400:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4401: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4402: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4403: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4404: 	'\');" target="_self">'.$fullname.'</a> '.
 4405: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4406:     $student=~s/:/_/; # colon doen't work in javascript for names
 4407:     foreach my $apart (@$parts) {
 4408: 	my ($part,$type) = &split_part_type($apart);
 4409: 	my $score=$record{"resource.$part.$type"};
 4410:         $result.='<td align="center">';
 4411:         my ($aggtries,$totaltries);
 4412:         unless (exists($aggregates{$part})) {
 4413: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4414: 	    $aggtries = $totaltries;
 4415:             if ($$last_resets{$part}) {  
 4416:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4417: 					   $part);
 4418:             }
 4419:             $result.='<input type="hidden" name="'.
 4420:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4421:             $result.='<input type="hidden" name="'.
 4422:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4423:             $aggregates{$part} = 1;
 4424:         }
 4425: 	if ($type eq 'awarded') {
 4426: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4427: 	    $result.='<input type="hidden" name="'.
 4428: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4429: 	    $result.='<input type="text" name="'.
 4430: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4431:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4432: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4433: 	} elsif ($type eq 'solved') {
 4434: 	    my ($status,$foo)=split(/_/,$score,2);
 4435: 	    $status = 'nothing' if ($status eq '');
 4436: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4437: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4438: 	    $result.='&nbsp;<select name="'.
 4439: 		'GD_'.$student.'_'.$part.'_solved" '.
 4440:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4441: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4442: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4443: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4444: 	    $result.="</select>&nbsp;</td>\n";
 4445: 	} else {
 4446: 	    $result.='<input type="hidden" name="'.
 4447: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4448: 		    "\n";
 4449: 	    $result.='<input type="text" name="'.
 4450: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4451: 		'value="'.$score.'" size="4" /></td>'."\n";
 4452: 	}
 4453:     }
 4454:     $result.=&Apache::loncommon::end_data_table_row();
 4455:     return $result;
 4456: }
 4457: 
 4458: #--- change scores for all the students in a section/class
 4459: #    record does not get update if unchanged
 4460: sub editgrades {
 4461:     my ($request,$symb) = @_;
 4462:     my $toolsymb;
 4463:     if ($symb =~ /ext\.tool$/) {
 4464:         $toolsymb = $symb;
 4465:     }
 4466: 
 4467:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4468:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4469:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4470: 
 4471:     my $result= &Apache::loncommon::start_data_table().
 4472: 	&Apache::loncommon::start_data_table_header_row().
 4473: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4474: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4475:     my %scoreptr = (
 4476: 		    'correct'  =>'correct_by_override',
 4477: 		    'incorrect'=>'incorrect_by_override',
 4478: 		    'excused'  =>'excused',
 4479: 		    'ungraded' =>'ungraded_attempted',
 4480:                     'credited' =>'credit_attempted',
 4481: 		    'nothing'  => '',
 4482: 		    );
 4483:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4484: 
 4485:     my (@partid);
 4486:     my %weight = ();
 4487:     my %columns = ();
 4488:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4489: 
 4490:     my $partserror;
 4491:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4492:     if ($partserror) {
 4493:         return &navmap_errormsg();
 4494:     }
 4495:     my $header;
 4496:     while ($ctr < $env{'form.totalparts'}) {
 4497: 	my $partid = $env{'form.partid_'.$ctr};
 4498: 	push(@partid,$partid);
 4499: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4500: 	$ctr++;
 4501:     }
 4502:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4503:     my $totcolspan = 0;
 4504:     foreach my $partid (@partid) {
 4505: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4506: 	    '<th align="center">'.&mt('New Score').'</th>';
 4507: 	$columns{$partid}=2;
 4508: 	foreach my $stores (@parts) {
 4509: 	    my ($part,$type) = &split_part_type($stores);
 4510: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4511: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4512: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4513: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4514:             my $narrowtext = &mt('Tries');
 4515: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4516: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4517: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4518: 	    $columns{$partid}+=2;
 4519: 	}
 4520:         $totcolspan += $columns{$partid};
 4521:     }
 4522:     foreach my $partid (@partid) {
 4523: 	my $display_part=&get_display_part($partid,$symb);
 4524: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4525: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4526: 	    '</th>';
 4527: 
 4528:     }
 4529:     $result .= &Apache::loncommon::end_data_table_header_row().
 4530: 	&Apache::loncommon::start_data_table_header_row().
 4531: 	$header.
 4532: 	&Apache::loncommon::end_data_table_header_row();
 4533:     my @noupdate;
 4534:     my ($updateCtr,$noupdateCtr) = (1,1);
 4535:     my ($got_types,%queueable);
 4536:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4537: 	my $user = $env{'form.ctr'.$i};
 4538: 	my ($uname,$udom)=split(/:/,$user);
 4539: 	my %newrecord;
 4540: 	my $updateflag = 0;
 4541: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4542: 	my $canmodify = &canmodify($usec);
 4543: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4544: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4545: 	if (!$canmodify) {
 4546: 	    push(@noupdate,
 4547: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4548: 		 &mt('Not allowed to modify student')."</span></td>");
 4549: 	    next;
 4550: 	}
 4551:         my %aggregate = ();
 4552:         my $aggregateflag = 0;
 4553: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4554: 	foreach (@partid) {
 4555: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4556: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4557: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4558: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4559: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4560: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4561: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4562: 	    my $score;
 4563: 	    if ($partial eq '') {
 4564: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4565: 	    } elsif ($partial > 0) {
 4566: 		$score = 'correct_by_override';
 4567: 	    } elsif ($partial == 0) {
 4568: 		$score = 'incorrect_by_override';
 4569: 	    }
 4570: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4571: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4572: 
 4573: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4574: 		"$env{'user.name'}:$env{'user.domain'}";
 4575: 	    if ($dropMenu eq 'reset status' &&
 4576: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4577: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4578: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4579: 		$newrecord{'resource.'.$_.'.award'} = '';
 4580: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4581: 		$updateflag = 1;
 4582:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4583:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4584:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4585:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4586:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4587:                     $aggregateflag = 1;
 4588:                 }
 4589: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4590: 		$updateflag = 1;
 4591: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4592: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4593: 		$rec_update++;
 4594: 	    }
 4595: 
 4596: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4597: 		'<td align="center">'.$awarded.
 4598: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4599: 
 4600: 
 4601: 	    my $partid=$_;
 4602: 	    foreach my $stores (@parts) {
 4603: 		my ($part,$type) = &split_part_type($stores);
 4604: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4605: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4606: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4607: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4608: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4609: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4610: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4611: 		    $updateflag=1;
 4612: 		}
 4613: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4614: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4615: 	    }
 4616: 	}
 4617: 	$line.="\n";
 4618: 
 4619: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4620: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4621: 
 4622: 	if ($updateflag) {
 4623: 	    $count++;
 4624: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4625: 				    $udom,$uname);
 4626: 
 4627: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4628: 					      $cnum,$udom,$uname)) {
 4629: 		# need to figure out if should be in queue.
 4630: 		my %record =  
 4631: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4632: 					     $udom,$uname);
 4633: 		my $all_graded = 1;
 4634: 		my $none_graded = 1;
 4635:                 unless ($got_types) {
 4636:                     my $error;
 4637:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4638:                     unless ($error) {
 4639:                         foreach my $part (@parts) {
 4640:                             if (ref($resptype->{$part}) eq 'HASH') {
 4641:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4642:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4643:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4644:                                         $queueable{$part} = 1;
 4645:                                         last;
 4646:                                     }
 4647:                                 }
 4648:                             }
 4649:                         }
 4650:                     }
 4651:                     $got_types = 1;
 4652:                 }
 4653: 		foreach my $part (@parts) {
 4654:                     if ($queueable{$part}) {
 4655: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4656: 			    $all_graded = 0;
 4657: 		        } else {
 4658: 			    $none_graded = 0;
 4659: 		        }
 4660: 		    }
 4661:                 }
 4662: 		if ($all_graded || $none_graded) {
 4663: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4664: 							   $symb,$cdom,$cnum,
 4665: 							   $udom,$uname);
 4666: 		}
 4667: 	    }
 4668: 
 4669: 	    $result.=&Apache::loncommon::start_data_table_row().
 4670: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4671: 		&Apache::loncommon::end_data_table_row();
 4672: 	    $updateCtr++;
 4673: 	} else {
 4674: 	    push(@noupdate,
 4675: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4676: 	    $noupdateCtr++;
 4677: 	}
 4678:         if ($aggregateflag) {
 4679:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4680: 				  $cdom,$cnum);
 4681:         }
 4682:     }
 4683:     if (@noupdate) {
 4684:         my $numcols=$totcolspan+2;
 4685: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4686: 	    '<td align="center" colspan="'.$numcols.'">'.
 4687: 	    &mt('No Changes Occurred For the Students Below').
 4688: 	    '</td>'.
 4689: 	    &Apache::loncommon::end_data_table_row();
 4690: 	foreach my $line (@noupdate) {
 4691: 	    $result.=
 4692: 		&Apache::loncommon::start_data_table_row().
 4693: 		$line.
 4694: 		&Apache::loncommon::end_data_table_row();
 4695: 	}
 4696:     }
 4697:     $result .= &Apache::loncommon::end_data_table();
 4698:     my $msg = '<p><b>'.
 4699: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4700: 	    $rec_update,$count).'</b><br />'.
 4701: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4702: 	'</b></p>';
 4703:     return $title.$msg.$result;
 4704: }
 4705: 
 4706: sub split_part_type {
 4707:     my ($partstr) = @_;
 4708:     my ($temp,@allparts)=split(/_/,$partstr);
 4709:     my $type=pop(@allparts);
 4710:     my $part=join('_',@allparts);
 4711:     return ($part,$type);
 4712: }
 4713: 
 4714: #------------- end of section for handling grading by section/class ---------
 4715: #
 4716: #----------------------------------------------------------------------------
 4717: 
 4718: 
 4719: #----------------------------------------------------------------------------
 4720: #
 4721: #-------------------------- Next few routines handles grading by csv upload
 4722: #
 4723: #--- Javascript to handle csv upload
 4724: sub csvupload_javascript_reverse_associate {
 4725:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4726:     my $error2=&mt('You need to specify at least one grading field');
 4727:   &js_escape(\$error1);
 4728:   &js_escape(\$error2);
 4729:   return(<<ENDPICK);
 4730:   function verify(vf) {
 4731:     var foundsomething=0;
 4732:     var founduname=0;
 4733:     var foundID=0;
 4734:     var foundclicker=0;
 4735:     for (i=0;i<=vf.nfields.value;i++) {
 4736:       tw=eval('vf.f'+i+'.selectedIndex');
 4737:       if (i==0 && tw!=0) { foundID=1; }
 4738:       if (i==1 && tw!=0) { founduname=1; }
 4739:       if (i==2 && tw!=0) { foundclicker=1; }
 4740:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4741:     }
 4742:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4743: 	alert('$error1');
 4744: 	return;
 4745:     }
 4746:     if (foundsomething==0) {
 4747: 	alert('$error2');
 4748: 	return;
 4749:     }
 4750:     vf.submit();
 4751:   }
 4752:   function flip(vf,tf) {
 4753:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4754:     var i;
 4755:     for (i=0;i<=vf.nfields.value;i++) {
 4756:       //can not pick the same destination field for both name and domain
 4757:       if (((i ==0)||(i ==1)) && 
 4758:           ((tf==0)||(tf==1)) && 
 4759:           (i!=tf) &&
 4760:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4761:         eval('vf.f'+i+'.selectedIndex=0;')
 4762:       }
 4763:     }
 4764:   }
 4765: ENDPICK
 4766: }
 4767: 
 4768: sub csvupload_javascript_forward_associate {
 4769:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4770:     my $error2=&mt('You need to specify at least one grading field');
 4771:   &js_escape(\$error1);
 4772:   &js_escape(\$error2);
 4773:   return(<<ENDPICK);
 4774:   function verify(vf) {
 4775:     var foundsomething=0;
 4776:     var founduname=0;
 4777:     var foundID=0;
 4778:     var foundclicker=0;
 4779:     for (i=0;i<=vf.nfields.value;i++) {
 4780:       tw=eval('vf.f'+i+'.selectedIndex');
 4781:       if (tw==1) { foundID=1; }
 4782:       if (tw==2) { founduname=1; }
 4783:       if (tw==3) { foundclicker=1; }
 4784:       if (tw>4) { foundsomething=1; }
 4785:     }
 4786:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4787: 	alert('$error1');
 4788: 	return;
 4789:     }
 4790:     if (foundsomething==0) {
 4791: 	alert('$error2');
 4792: 	return;
 4793:     }
 4794:     vf.submit();
 4795:   }
 4796:   function flip(vf,tf) {
 4797:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4798:     var i;
 4799:     //can not pick the same destination field twice
 4800:     for (i=0;i<=vf.nfields.value;i++) {
 4801:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4802:         eval('vf.f'+i+'.selectedIndex=0;')
 4803:       }
 4804:     }
 4805:   }
 4806: ENDPICK
 4807: }
 4808: 
 4809: sub csvuploadmap_header {
 4810:     my ($request,$symb,$datatoken,$distotal)= @_;
 4811:     my $javascript;
 4812:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4813: 	$javascript=&csvupload_javascript_reverse_associate();
 4814:     } else {
 4815: 	$javascript=&csvupload_javascript_forward_associate();
 4816:     }
 4817: 
 4818:     $symb = &Apache::lonenc::check_encrypt($symb);
 4819:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4820:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4821:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4822:     my $reverse=&mt("Reverse Association");
 4823:     $request->print(<<ENDPICK);
 4824: <br />
 4825: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4826: <input type="hidden" name="associate"  value="" />
 4827: <input type="hidden" name="phase"      value="three" />
 4828: <input type="hidden" name="datatoken"  value="$datatoken" />
 4829: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4830: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4831: <input type="hidden" name="upfile_associate" 
 4832:                                        value="$env{'form.upfile_associate'}" />
 4833: <input type="hidden" name="symb"       value="$symb" />
 4834: <input type="hidden" name="command"    value="csvuploadoptions" />
 4835: <hr />
 4836: ENDPICK
 4837:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4838:     return '';
 4839: 
 4840: }
 4841: 
 4842: sub csvupload_fields {
 4843:     my ($symb,$errorref) = @_;
 4844:     my $toolsymb;
 4845:     if ($symb =~ /ext\.tool$/) {
 4846:         $toolsymb = $symb;
 4847:     }
 4848:     my (@parts) = &getpartlist($symb,$errorref);
 4849:     if (ref($errorref)) {
 4850:         if ($$errorref) {
 4851:             return;
 4852:         }
 4853:     }
 4854: 
 4855:     my @fields=(['ID','Student/Employee ID'],
 4856: 		['username','Student Username'],
 4857: 		['clicker','Clicker ID'],
 4858: 		['domain','Student Domain']);
 4859:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4860:     foreach my $part (sort(@parts)) {
 4861: 	my @datum;
 4862: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4863: 	my $name=$part;
 4864: 	if (!$display) { $display = $name; }
 4865: 	@datum=($name,$display);
 4866: 	if ($name=~/^stores_(.*)_awarded/) {
 4867: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4868: 	}
 4869: 	push(@fields,\@datum);
 4870:     }
 4871:     return (@fields);
 4872: }
 4873: 
 4874: sub csvuploadmap_footer {
 4875:     my ($request,$i,$keyfields) =@_;
 4876:     my $buttontext = &mt('Assign Grades');
 4877:     $request->print(<<ENDPICK);
 4878: </table>
 4879: <input type="hidden" name="nfields" value="$i" />
 4880: <input type="hidden" name="keyfields" value="$keyfields" />
 4881: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4882: </form>
 4883: ENDPICK
 4884: }
 4885: 
 4886: sub checkforfile_js {
 4887:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4888:     &js_escape(\$alertmsg);
 4889:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4890:     function checkUpload(formname) {
 4891: 	if (formname.upfile.value == "") {
 4892: 	    alert("$alertmsg");
 4893: 	    return false;
 4894: 	}
 4895: 	formname.submit();
 4896:     }
 4897: CSVFORMJS
 4898:     return $result;
 4899: }
 4900: 
 4901: sub upcsvScores_form {
 4902:     my ($request,$symb) = @_;
 4903:     if (!$symb) {return '';}
 4904:     my $result=&checkforfile_js();
 4905:     $result.=&Apache::loncommon::start_data_table().
 4906:              &Apache::loncommon::start_data_table_header_row().
 4907:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4908:              &Apache::loncommon::end_data_table_header_row().
 4909:              &Apache::loncommon::start_data_table_row().'<td>';
 4910:     my $upload=&mt("Upload Scores");
 4911:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4912:     my $ignore=&mt('Ignore First Line');
 4913:     $symb = &Apache::lonenc::check_encrypt($symb);
 4914:     $result.=<<ENDUPFORM;
 4915: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4916: <input type="hidden" name="symb" value="$symb" />
 4917: <input type="hidden" name="command" value="csvuploadmap" />
 4918: $upfile_select
 4919: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4920: </form>
 4921: ENDUPFORM
 4922:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4923:                            &mt("How do I create a CSV file from a spreadsheet")).
 4924:              '</td>'.
 4925:             &Apache::loncommon::end_data_table_row().
 4926:             &Apache::loncommon::end_data_table();
 4927:     return $result;
 4928: }
 4929: 
 4930: 
 4931: sub csvuploadmap {
 4932:     my ($request,$symb) = @_;
 4933:     if (!$symb) {return '';}
 4934: 
 4935:     my $datatoken;
 4936:     if (!$env{'form.datatoken'}) {
 4937: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4938:     } else {
 4939: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4940:         if ($datatoken ne '') {
 4941: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4942:         }
 4943:     }
 4944:     my @records=&Apache::loncommon::upfile_record_sep();
 4945:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4946:     my ($i,$keyfields);
 4947:     if (@records) {
 4948:         my $fieldserror;
 4949: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4950:         if ($fieldserror) {
 4951:             $request->print(&navmap_errormsg());
 4952:             return;
 4953:         }
 4954: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4955: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4956: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4957: 							  \@fields);
 4958: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4959: 	    chop($keyfields);
 4960: 	} else {
 4961: 	    unshift(@fields,['none','']);
 4962: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4963: 							    \@fields);
 4964:             foreach my $rec (@records) {
 4965:                 my %temp = &Apache::loncommon::record_sep($rec);
 4966:                 if (%temp) {
 4967:                     $keyfields=join(',',sort(keys(%temp)));
 4968:                     last;
 4969:                 }
 4970:             }
 4971: 	}
 4972:     }
 4973:     &csvuploadmap_footer($request,$i,$keyfields);
 4974: 
 4975:     return '';
 4976: }
 4977: 
 4978: sub csvuploadoptions {
 4979:     my ($request,$symb)= @_;
 4980:     my $overwrite=&mt('Overwrite any existing score');
 4981:     $request->print(<<ENDPICK);
 4982: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4983: <input type="hidden" name="command"    value="csvuploadassign" />
 4984: <p>
 4985: <label>
 4986:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4987:    $overwrite
 4988: </label>
 4989: </p>
 4990: ENDPICK
 4991:     my %fields=&get_fields();
 4992:     if (!defined($fields{'domain'})) {
 4993: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4994: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4995:     }
 4996:     foreach my $key (sort(keys(%env))) {
 4997: 	if ($key !~ /^form\.(.*)$/) { next; }
 4998: 	my $cleankey=$1;
 4999: 	if ($cleankey eq 'command') { next; }
 5000: 	$request->print('<input type="hidden" name="'.$cleankey.
 5001: 			'"  value="'.$env{$key}.'" />'."\n");
 5002:     }
 5003:     # FIXME do a check for any duplicated user ids...
 5004:     # FIXME do a check for any invalid user ids?...
 5005:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 5006: <hr /></form>'."\n");
 5007:     return '';
 5008: }
 5009: 
 5010: sub get_fields {
 5011:     my %fields;
 5012:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 5013:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 5014: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 5015: 	    if ($env{'form.f'.$i} ne 'none') {
 5016: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 5017: 	    }
 5018: 	} else {
 5019: 	    if ($env{'form.f'.$i} ne 'none') {
 5020: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 5021: 	    }
 5022: 	}
 5023:     }
 5024:     return %fields;
 5025: }
 5026: 
 5027: sub csvuploadassign {
 5028:     my ($request,$symb) = @_;
 5029:     if (!$symb) {return '';}
 5030:     my $error_msg = '';
 5031:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 5032:     if ($datatoken ne '') { 
 5033:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 5034:     }
 5035:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 5036:     my %fields=&get_fields();
 5037:     my $courseid=$env{'request.course.id'};
 5038:     my ($classlist) = &getclasslist('all',0);
 5039:     my @notallowed;
 5040:     my @skipped;
 5041:     my @warnings;
 5042:     my $countdone=0;
 5043:     foreach my $grade (@gradedata) {
 5044: 	my %entries=&Apache::loncommon::record_sep($grade);
 5045: 	my $domain;
 5046: 	if ($entries{$fields{'domain'}}) {
 5047: 	    $domain=$entries{$fields{'domain'}};
 5048: 	} else {
 5049: 	    $domain=$env{'form.default_domain'};
 5050: 	}
 5051: 	$domain=~s/\s//g;
 5052: 	my $username=$entries{$fields{'username'}};
 5053: 	$username=~s/\s//g;
 5054: 	if (!$username) {
 5055: 	    my $id=$entries{$fields{'ID'}};
 5056: 	    $id=~s/\s//g;
 5057:             if ($id ne '') {
 5058: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 5059: 	        $username=$ids{$id};
 5060:             } else {
 5061:                 if ($entries{$fields{'clicker'}}) {
 5062:                     my $clicker = $entries{$fields{'clicker'}};
 5063:                     $clicker=~s/\s//g;
 5064:                     if ($clicker ne '') {
 5065:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 5066:                         if ($clickers{$clicker} ne '') {  
 5067:                             my $match = 0;
 5068:                             my @inclass;
 5069:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 5070:                                 if (exists($$classlist{"$poss:$domain"})) {
 5071:                                     $username = $poss;
 5072:                                     push(@inclass,$poss);
 5073:                                     $match ++;
 5074:                                     
 5075:                                 }
 5076:                             }
 5077:                             if ($match > 1) {
 5078:                                 undef($username); 
 5079:                                 $request->print('<p class="LC_warning">'.
 5080:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 5081:                                                 $clicker,join(', ',@inclass)).'</p>');
 5082:                             }
 5083:                         }
 5084:                     }
 5085:                 }
 5086:             }
 5087: 	}
 5088: 	if (!exists($$classlist{"$username:$domain"})) {
 5089: 	    my $id=$entries{$fields{'ID'}};
 5090: 	    $id=~s/\s//g;
 5091:             my $clicker = $entries{$fields{'clicker'}};
 5092:             $clicker=~s/\s//g;
 5093:             if ($clicker) {
 5094:                 push(@skipped,"$clicker:$domain");
 5095: 	    } elsif ($id) {
 5096: 		push(@skipped,"$id:$domain");
 5097: 	    } else {
 5098: 		push(@skipped,"$username:$domain");
 5099: 	    }
 5100: 	    next;
 5101: 	}
 5102: 	my $usec=$classlist->{"$username:$domain"}[5];
 5103: 	if (!&canmodify($usec)) {
 5104: 	    push(@notallowed,"$username:$domain");
 5105: 	    next;
 5106: 	}
 5107: 	my %points;
 5108: 	my %grades;
 5109: 	foreach my $dest (keys(%fields)) {
 5110: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5111: 		$dest eq 'domain') { next; }
 5112: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5113: 	    if ($dest=~/stores_(.*)_points/) {
 5114: 		my $part=$1;
 5115: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5116: 					      $symb,$domain,$username);
 5117:                 if ($wgt) {
 5118:                     $entries{$fields{$dest}}=~s/\s//g;
 5119:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5120:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5121:                                           : 'correct_by_override';
 5122:                     if ($pcr>1) {
 5123:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5124:                     }
 5125:                     $grades{"resource.$part.awarded"}=$pcr;
 5126:                     $grades{"resource.$part.solved"}=$award;
 5127:                     $points{$part}=1;
 5128:                 } else {
 5129:                     $error_msg = "<br />" .
 5130:                         &mt("Some point values were assigned"
 5131:                             ." for problems with a weight "
 5132:                             ."of zero. These values were "
 5133:                             ."ignored.");
 5134:                 }
 5135: 	    } else {
 5136: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5137: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5138: 		my $store_key=$dest;
 5139: 		$store_key=~s/^stores/resource/;
 5140: 		$store_key=~s/_/\./g;
 5141: 		$grades{$store_key}=$entries{$fields{$dest}};
 5142: 	    }
 5143: 	}
 5144: 	if (! %grades) {
 5145:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5146:         } else {
 5147: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5148: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5149: 					   $env{'request.course.id'},
 5150: 					   $domain,$username);
 5151: 	   if ($result eq 'ok') {
 5152: # Successfully stored
 5153: 	      $request->print('.');
 5154: # Remove from grading queue
 5155:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5156:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5157:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5158:                                              $domain,$username);
 5159:               $countdone++;
 5160:            } else {
 5161: 	      $request->print("<p><span class=\"LC_error\">".
 5162:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5163:                                   "$username:$domain",$result)."</span></p>");
 5164: 	   }
 5165: 	   $request->rflush();
 5166:         }
 5167:     }
 5168:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5169:     if (@warnings) {
 5170:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5171:         $request->print(join(', ',@warnings));
 5172:     }
 5173:     if (@skipped) {
 5174: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5175:         $request->print(join(', ',@skipped));
 5176:     }
 5177:     if (@notallowed) {
 5178: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5179: 	$request->print(join(', ',@notallowed));
 5180:     }
 5181:     $request->print("<br />\n");
 5182:     return $error_msg;
 5183: }
 5184: #------------- end of section for handling csv file upload ---------
 5185: #
 5186: #-------------------------------------------------------------------
 5187: #
 5188: #-------------- Next few routines handle grading by page/sequence
 5189: #
 5190: #--- Select a page/sequence and a student to grade
 5191: sub pickStudentPage {
 5192:     my ($request,$symb) = @_;
 5193: 
 5194:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5195:     &js_escape(\$alertmsg);
 5196:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5197: 
 5198: function checkPickOne(formname) {
 5199:     if (radioSelection(formname.student) == null) {
 5200: 	alert("$alertmsg");
 5201: 	return;
 5202:     }
 5203:     ptr = pullDownSelection(formname.selectpage);
 5204:     formname.page.value = formname["page"+ptr].value;
 5205:     formname.title.value = formname["title"+ptr].value;
 5206:     formname.submit();
 5207: }
 5208: 
 5209: LISTJAVASCRIPT
 5210:     &commonJSfunctions($request);
 5211: 
 5212:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5213:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5214:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5215:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5216: 
 5217:     my $result='<h3><span class="LC_info">&nbsp;'.
 5218: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5219: 
 5220:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5221:     my $map_error;
 5222:     my ($titles,$symbx) = &getSymbMap($map_error);
 5223:     if ($map_error) {
 5224:         $request->print(&navmap_errormsg());
 5225:         return; 
 5226:     }
 5227:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5228: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5229: #    my $type=($curpage =~ /\.(page|sequence)/);
 5230: 
 5231:     # Collection of hidden fields
 5232:     my $ctr=0;
 5233:     foreach (@$titles) {
 5234:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5235:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5236:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5237:         $ctr++;
 5238:     }
 5239:     $result.='<input type="hidden" name="page" />'."\n".
 5240:         '<input type="hidden" name="title" />'."\n";
 5241: 
 5242:     $result.=&build_section_inputs();
 5243:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5244:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5245: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5246: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5247: 
 5248:     # Show grading options
 5249:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5250:     my $select = '<select name="selectpage">'."\n";
 5251:     $ctr=0;
 5252:     foreach (@$titles) {
 5253: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5254: 	$select.='<option value="'.$ctr.'"'.
 5255: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5256: 	    '>'.$showtitle.'</option>'."\n";
 5257: 	$ctr++;
 5258:     }
 5259:     $select.= '</select>';
 5260: 
 5261:     $result.=
 5262:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5263:        .$select
 5264:        .&Apache::lonhtmlcommon::row_closure();
 5265: 
 5266:     $result.=
 5267:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5268:        .'<label><input type="radio" name="vProb" value="no"'
 5269:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5270:        .'<label><input type="radio" name="vProb" value="yes" />'
 5271:            .&mt('yes').'</label>'."\n"
 5272:        .&Apache::lonhtmlcommon::row_closure();
 5273: 
 5274:     $result.=
 5275:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5276:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5277:            .&mt('none').' </label>'."\n"
 5278:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5279:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5280:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5281:            .&mt('all submissions with details').' </label>'
 5282:        .&Apache::lonhtmlcommon::row_closure();
 5283:     
 5284:     $result.=
 5285:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5286:        .'<input type="text" name="CODE" value="" />'
 5287:        .&Apache::lonhtmlcommon::row_closure(1)
 5288:        .&Apache::lonhtmlcommon::end_pick_box();
 5289: 
 5290:     # Show list of students to select for grading
 5291:     $result.='<br /><input type="button" '.
 5292:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5293: 
 5294:     $request->print($result);
 5295: 
 5296:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5297: 	&Apache::loncommon::start_data_table().
 5298: 	&Apache::loncommon::start_data_table_header_row().
 5299: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5300: 	'<th>'.&nameUserString('header').'</th>'.
 5301: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5302: 	'<th>'.&nameUserString('header').'</th>'.
 5303: 	&Apache::loncommon::end_data_table_header_row();
 5304:  
 5305:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5306:     my $ptr = 1;
 5307:     foreach my $student (sort 
 5308: 			 {
 5309: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5310: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5311: 			     }
 5312: 			     return $a cmp $b;
 5313: 			 } (keys(%$fullname))) {
 5314: 	my ($uname,$udom) = split(/:/,$student);
 5315: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5316:                                   : '</td>');
 5317: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5318: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5319: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5320: 	$studentTable.=
 5321: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5322:                          : '');
 5323: 	$ptr++;
 5324:     }
 5325:     if ($ptr%2 == 0) {
 5326: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5327: 	    &Apache::loncommon::end_data_table_row();
 5328:     }
 5329:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5330:     $studentTable.='<input type="button" '.
 5331:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5332: 
 5333:     $request->print($studentTable);
 5334: 
 5335:     return '';
 5336: }
 5337: 
 5338: sub getSymbMap {
 5339:     my ($map_error) = @_;
 5340:     my $navmap = Apache::lonnavmaps::navmap->new();
 5341:     unless (ref($navmap)) {
 5342:         if (ref($map_error)) {
 5343:             $$map_error = 'navmap';
 5344:         }
 5345:         return;
 5346:     }
 5347:     my %symbx = ();
 5348:     my @titles = ();
 5349:     my $minder = 0;
 5350: 
 5351:     # Gather every sequence that has problems.
 5352:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5353: 					       1,0,1);
 5354:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5355: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5356: 	    my $title = $minder.'.'.
 5357: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5358: 	    push(@titles, $title); # minder in case two titles are identical
 5359: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5360: 	    $minder++;
 5361: 	}
 5362:     }
 5363:     return \@titles,\%symbx;
 5364: }
 5365: 
 5366: #
 5367: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5368: sub displayPage {
 5369:     my ($request,$symb) = @_;
 5370:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5371:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5372:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5373:     my $pageTitle = $env{'form.page'};
 5374:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5375:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5376:     my $usec=$classlist->{$env{'form.student'}}[5];
 5377: 
 5378:     #need to make sure we have the correct data for later EXT calls, 
 5379:     #thus invalidate the cache
 5380:     &Apache::lonnet::devalidatecourseresdata(
 5381:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5382:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5383:     &Apache::lonnet::clear_EXT_cache_status();
 5384: 
 5385:     if (!&canview($usec)) {
 5386:         $request->print(
 5387:             '<span class="LC_warning">'.
 5388:             &mt('Unable to view requested student. ([_1])',
 5389:                     $env{'form.student'}).
 5390:             '</span>');
 5391:         return;
 5392:     }
 5393:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5394:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5395: 	'</h3>'."\n";
 5396:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5397:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5398: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5399:     } else {
 5400: 	delete($env{'form.CODE'});
 5401:     }
 5402:     &sub_page_js($request);
 5403:     $request->print($result);
 5404: 
 5405:     my $navmap = Apache::lonnavmaps::navmap->new();
 5406:     unless (ref($navmap)) {
 5407:         $request->print(&navmap_errormsg());
 5408:         return;
 5409:     }
 5410:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5411:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5412:     if (!$map) {
 5413: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5414: 	return; 
 5415:     }
 5416:     my $iterator = $navmap->getIterator($map->map_start(),
 5417: 					$map->map_finish());
 5418: 
 5419:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5420: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5421: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5422: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5423: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5424: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5425: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5426: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5427: 
 5428:     if (defined($env{'form.CODE'})) {
 5429: 	$studentTable.=
 5430: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5431:     }
 5432:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5433: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5434: 
 5435:     $studentTable.='&nbsp;<span class="LC_info">'.
 5436:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5437:         '</span>'."\n".
 5438: 	&Apache::loncommon::start_data_table().
 5439: 	&Apache::loncommon::start_data_table_header_row().
 5440: 	'<th>'.&mt('Prob.').'</th>'.
 5441: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5442: 	&Apache::loncommon::end_data_table_header_row();
 5443: 
 5444:     &Apache::lonxml::clear_problem_counter();
 5445:     my ($depth,$question,$prob) = (1,1,1);
 5446:     $iterator->next(); # skip the first BEGIN_MAP
 5447:     my $curRes = $iterator->next(); # for "current resource"
 5448:     while ($depth > 0) {
 5449:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5450:         if($curRes == $iterator->END_MAP) { $depth--; }
 5451: 
 5452:         if (ref($curRes) && $curRes->is_gradable()) {
 5453: 	    my $parts = $curRes->parts();
 5454:             my $title = $curRes->compTitle();
 5455: 	    my $symbx = $curRes->symb();
 5456:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5457: 	    $studentTable.=
 5458: 		&Apache::loncommon::start_data_table_row().
 5459: 		'<td align="center" valign="top" >'.$prob.
 5460: 		(scalar(@{$parts}) == 1 ? '' 
 5461: 		                        : '<br />('.&mt('[_1]parts',
 5462: 							scalar(@{$parts}).'&nbsp;').')'
 5463: 		 ).
 5464: 		 '</td>';
 5465: 	    $studentTable.='<td valign="top">';
 5466: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5467:             if ($is_tool) {
 5468:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5469:             } else {
 5470: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5471: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5472: 					         undef,'both',\%form);
 5473: 	        } else {
 5474: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5475: 		    $companswer =~ s|<form(.*?)>||g;
 5476: 		    $companswer =~ s|</form>||g;
 5477: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5478: #		        $companswer =~ s/$1/ /ms;
 5479: #		        $request->print('match='.$1."<br />\n");
 5480: #		    }
 5481: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5482: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5483: 		}
 5484: 	    }
 5485: 
 5486: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5487: 
 5488: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5489: 		if ($record{'version'} eq '') {
 5490:                     my $msg = &mt('No recorded submission for this problem.');
 5491:                     if ($is_tool) {
 5492:                         $msg = &mt('No recorded transactions for this external tool');
 5493:                     }
 5494: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5495: 		} else {
 5496: 		    my %responseType = ();
 5497: 		    foreach my $partid (@{$parts}) {
 5498: 			my @responseIds =$curRes->responseIds($partid);
 5499: 			my @responseType =$curRes->responseType($partid);
 5500: 			my %responseIds;
 5501: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5502: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5503: 			}
 5504: 			$responseType{$partid} = \%responseIds;
 5505: 		    }
 5506: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5507: 		}
 5508: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5509: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5510:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5511: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5512: 									$env{'request.course.id'},
 5513: 									'','.submission',undef,
 5514:                                                                         $usec,$identifier);
 5515:  
 5516: 	    }
 5517: 	    if (&canmodify($usec)) {
 5518:             $studentTable.=&gradeBox_start();
 5519: 		foreach my $partid (@{$parts}) {
 5520: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5521: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5522: 		    $question++;
 5523: 		}
 5524:             $studentTable.=&gradeBox_end();
 5525: 		$prob++;
 5526: 	    }
 5527: 	    $studentTable.='</td></tr>';
 5528: 
 5529: 	}
 5530:         $curRes = $iterator->next();
 5531:     }
 5532:     my $disabled;
 5533:     unless (&canmodify($usec)) {
 5534:         $disabled = ' disabled="disabled"';
 5535:     }
 5536: 
 5537:     $studentTable.=
 5538:         '</table>'."\n".
 5539:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5540:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5541:         '</form>'."\n";
 5542:     $request->print($studentTable);
 5543: 
 5544:     return '';
 5545: }
 5546: 
 5547: sub displaySubByDates {
 5548:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5549:     my $isCODE=0;
 5550:     my $isTask = ($symb =~/\.task$/);
 5551:     my $is_tool = ($symb =~/\.tool$/);
 5552:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5553:     my $studentTable=&Apache::loncommon::start_data_table().
 5554: 	&Apache::loncommon::start_data_table_header_row().
 5555: 	'<th>'.&mt('Date/Time').'</th>'.
 5556: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5557:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5558: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5559: 	'<th>'.&mt('Status').'</th>'.
 5560: 	&Apache::loncommon::end_data_table_header_row();
 5561:     my ($version);
 5562:     my %mark;
 5563:     my %orders;
 5564:     $mark{'correct_by_student'} = $checkIcon;
 5565:     if (!exists($$record{'1:timestamp'})) {
 5566:         if ($is_tool) {
 5567:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5568:         } else {
 5569:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5570:         }
 5571:     }
 5572: 
 5573:     my $interaction;
 5574:     my $no_increment = 1;
 5575:     my (%lastrndseed,%lasttype);
 5576:     for ($version=1;$version<=$$record{'version'};$version++) {
 5577: 	my $timestamp = 
 5578: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5579: 	if (exists($$record{$version.':resource.0.version'})) {
 5580: 	    $interaction = $$record{$version.':resource.0.version'};
 5581: 	}
 5582:         if ($isTask && $env{'form.previousversion'}) {
 5583:             next unless ($interaction == $env{'form.previousversion'});
 5584:         }
 5585: 	my $where = ($isTask ? "$version:resource.$interaction"
 5586: 		             : "$version:resource");
 5587: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5588: 	    '<td>'.$timestamp.'</td>';
 5589: 	if ($isCODE) {
 5590: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5591: 	}
 5592:         if ($isTask) {
 5593:             $studentTable.='<td>'.$interaction.'</td>';
 5594:         }
 5595: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5596: 	my @displaySub = ();
 5597: 	foreach my $partid (@{$parts}) {
 5598:             my ($hidden,$type);
 5599:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5600:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5601:                 $hidden = 1;
 5602:             }
 5603:             my @matchKey;
 5604:             if ($isTask) {
 5605:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5606:             } elsif ($is_tool) {
 5607:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5608:             } else {
 5609:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5610:             }
 5611: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5612: 	    my $display_part=&get_display_part($partid,$symb);
 5613: 	    foreach my $matchKey (@matchKey) {
 5614: 		if (exists($$record{$version.':'.$matchKey}) &&
 5615: 		    $$record{$version.':'.$matchKey} ne '') {
 5616:                     if ($is_tool) {
 5617:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5618:                     } else {
 5619: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5620: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5621:                         $displaySub[0].='<span class="LC_nobreak">';
 5622:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5623:                                        .' <span class="LC_internal_info">'
 5624:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5625:                                        .'</span>'
 5626:                                        .' <b>';
 5627:                         if ($hidden) {
 5628:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5629:                         } else {
 5630:                             my ($trial,$rndseed,$newvariation);
 5631:                             if ($type eq 'randomizetry') {
 5632:                                 $trial = $$record{"$where.$partid.tries"};
 5633:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5634:                             }
 5635: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5636: 			        $displaySub[0].=&mt('Trial not counted');
 5637: 		            } else {
 5638: 			        $displaySub[0].=&mt('Trial: [_1]',
 5639: 					        $$record{"$where.$partid.tries"});
 5640:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5641:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5642:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5643:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5644:                                     }
 5645:                                 }
 5646:                                 $lastrndseed{$partid} = $rndseed;
 5647:                                 $lasttype{$partid} = $type;
 5648: 		            }
 5649: 		            my $responseType=($isTask ? 'Task'
 5650:                                               : $responseType->{$partid}->{$responseId});
 5651: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5652: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5653: 			        $orders{$partid}->{$responseId}=
 5654: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5655:                                                $no_increment,$type,$trial,$rndseed);
 5656: 		            }
 5657: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5658: 		            $displaySub[0].='&nbsp; '.
 5659: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5660:                         }
 5661:                     }
 5662: 		}
 5663: 	    }
 5664: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5665: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5666: 				    $$record{"$where.$partid.checkedin"},
 5667: 				    $$record{"$where.$partid.checkedin.slot"}).
 5668: 					'<br />';
 5669: 	    }
 5670: 	    if (exists $$record{"$where.$partid.award"}) {
 5671: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5672: 		    lc($$record{"$where.$partid.award"}).' '.
 5673: 		    $mark{$$record{"$where.$partid.solved"}}.
 5674: 		    '<br />';
 5675: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5676: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5677: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5678: 		}
 5679: 	    }
 5680: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5681: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5682: 		unless ($is_tool) {
 5683: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5684: 		}
 5685: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5686: 		$displaySub[2].=
 5687: 		    $$record{"$version:resource.$partid.regrader"};
 5688:                 unless ($is_tool) {
 5689: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5690:                 }
 5691: 	    }
 5692: 	}
 5693: 	# needed because old essay regrader has not parts info
 5694: 	if (exists $$record{"$version:resource.regrader"}) {
 5695: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5696: 	}
 5697: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5698: 	if ($displaySub[2]) {
 5699: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5700: 	}
 5701: 	$studentTable.='&nbsp;</td>'.
 5702: 	    &Apache::loncommon::end_data_table_row();
 5703:     }
 5704:     $studentTable.=&Apache::loncommon::end_data_table();
 5705:     return $studentTable;
 5706: }
 5707: 
 5708: sub updateGradeByPage {
 5709:     my ($request,$symb) = @_;
 5710: 
 5711:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5712:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5713:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5714:     my $pageTitle = $env{'form.page'};
 5715:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5716:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5717:     my $usec=$classlist->{$env{'form.student'}}[5];
 5718:     if (!&canmodify($usec)) {
 5719: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5720: 	return;
 5721:     }
 5722:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5723:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5724: 	'</h3>'."\n";
 5725: 
 5726:     $request->print($result);
 5727: 
 5728: 
 5729:     my $navmap = Apache::lonnavmaps::navmap->new();
 5730:     unless (ref($navmap)) {
 5731:         $request->print(&navmap_errormsg());
 5732:         return;
 5733:     }
 5734:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5735:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5736:     if (!$map) {
 5737: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5738: 	return; 
 5739:     }
 5740:     my $iterator = $navmap->getIterator($map->map_start(),
 5741: 					$map->map_finish());
 5742: 
 5743:     my $studentTable=
 5744: 	&Apache::loncommon::start_data_table().
 5745: 	&Apache::loncommon::start_data_table_header_row().
 5746: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5747: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5748: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5749: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5750: 	&Apache::loncommon::end_data_table_header_row();
 5751: 
 5752:     $iterator->next(); # skip the first BEGIN_MAP
 5753:     my $curRes = $iterator->next(); # for "current resource"
 5754:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5755:     while ($depth > 0) {
 5756:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5757:         if($curRes == $iterator->END_MAP) { $depth--; }
 5758: 
 5759:         if (ref($curRes) && $curRes->is_problem()) {
 5760: 	    my $parts = $curRes->parts();
 5761:             my $title = $curRes->compTitle();
 5762: 	    my $symbx = $curRes->symb();
 5763: 	    $studentTable.=
 5764: 		&Apache::loncommon::start_data_table_row().
 5765: 		'<td align="center" valign="top" >'.$prob.
 5766: 		(scalar(@{$parts}) == 1 ? '' 
 5767:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5768: 		.')').'</td>';
 5769: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5770: 
 5771: 	    my %newrecord=();
 5772: 	    my @displayPts=();
 5773:             my %aggregate = ();
 5774:             my $aggregateflag = 0;
 5775:             my %queueable;
 5776:             if ($env{'form.HIDE'.$prob}) {
 5777:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5778:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5779:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5780:                 $hideflag += $numchgs;
 5781:             }
 5782: 	    foreach my $partid (@{$parts}) {
 5783: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5784: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5785:                 my @types = $curRes->responseType($partid);
 5786:                 if (grep(/^essay$/,@types)) {
 5787:                     $queueable{$partid} = 1;
 5788:                 } else {
 5789:                     my @ids = $curRes->responseIds($partid);
 5790:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5791:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
 5792:                                                           '.handgrade',$symb);
 5793:                         if (lc($hndgrd) eq 'yes') {
 5794:                             $queueable{$partid} = 1;
 5795:                             last;
 5796:                         }
 5797:                     }
 5798:                 }
 5799: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5800: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5801: 		my $partial = $newpts/$wgt;
 5802: 		my $score;
 5803: 		if ($partial > 0) {
 5804: 		    $score = 'correct_by_override';
 5805: 		} elsif ($newpts ne '') { #empty is taken as 0
 5806: 		    $score = 'incorrect_by_override';
 5807: 		}
 5808: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5809: 		if ($dropMenu eq 'excused') {
 5810: 		    $partial = '';
 5811: 		    $score = 'excused';
 5812: 		} elsif ($dropMenu eq 'reset status'
 5813: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5814: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5815: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5816: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5817: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5818: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5819: 		    $changeflag++;
 5820: 		    $newpts = '';
 5821:                     
 5822:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5823:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5824:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5825:                     if ($aggtries > 0) {
 5826:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5827:                         $aggregateflag = 1;
 5828:                     }
 5829: 		}
 5830: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5831: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5832: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5833: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5834: 		    '&nbsp;<br />';
 5835: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5836: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5837: 		    '&nbsp;<br />';
 5838: 		$question++;
 5839: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5840: 
 5841: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5842: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5843: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5844: 		    if (scalar(keys(%newrecord)) > 0);
 5845: 
 5846: 		$changeflag++;
 5847: 	    }
 5848: 	    if (scalar(keys(%newrecord)) > 0) {
 5849: 		my %record = 
 5850: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5851: 					     $udom,$uname);
 5852: 
 5853: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5854: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5855: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5856: 		    $newrecord{'resource.CODE'} = '';
 5857: 		}
 5858: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5859: 					$udom,$uname);
 5860: 		%record = &Apache::lonnet::restore($symbx,
 5861: 						   $env{'request.course.id'},
 5862: 						   $udom,$uname);
 5863: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5864: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5865: 	    }
 5866: 	    
 5867:             if ($aggregateflag) {
 5868:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5869:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5870:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5871:             }
 5872: 
 5873: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5874: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5875: 		&Apache::loncommon::end_data_table_row();
 5876: 
 5877: 	    $prob++;
 5878: 	}
 5879:         $curRes = $iterator->next();
 5880:     }
 5881: 
 5882:     $studentTable.=&Apache::loncommon::end_data_table();
 5883:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5884: 		  &mt('The scores were changed for [quant,_1,problem].',
 5885: 		  $changeflag).'<br />');
 5886:     my $hidemsg=($hideflag == 0 ? '' :
 5887:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5888:                      $hideflag).'<br />');
 5889:     $request->print($hidemsg.$grademsg.$studentTable);
 5890: 
 5891:     return '';
 5892: }
 5893: 
 5894: #-------- end of section for handling grading by page/sequence ---------
 5895: #
 5896: #-------------------------------------------------------------------
 5897: 
 5898: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5899: #
 5900: #------ start of section for handling grading by page/sequence ---------
 5901: 
 5902: =pod
 5903: 
 5904: =head1 Bubble sheet grading routines
 5905: 
 5906:   For this documentation:
 5907: 
 5908:    'scanline' refers to the full line of characters
 5909:    from the file that we are parsing that represents one entire sheet
 5910: 
 5911:    'bubble line' refers to the data
 5912:    representing the line of bubbles that are on the physical bubblesheet
 5913: 
 5914: 
 5915: The overall process is that a scanned in bubblesheet data is uploaded
 5916: into a course. When a user wants to grade, they select a
 5917: sequence/folder of resources, a file of bubblesheet info, and pick
 5918: one of the predefined configurations for what each scanline looks
 5919: like.
 5920: 
 5921: Next each scanline is checked for any errors of either 'missing
 5922: bubbles' (it's an error because it may have been mis-scanned
 5923: because too light bubbling), 'double bubble' (each bubble line should
 5924: have no more than one letter picked), invalid or duplicated CODE,
 5925: invalid student/employee ID
 5926: 
 5927: If the CODE option is used that determines the randomization of the
 5928: homework problems, either way the student/employee ID is looked up into a
 5929: username:domain.
 5930: 
 5931: During the validation phase the instructor can choose to skip scanlines. 
 5932: 
 5933: After the validation phase, there are now 3 bubblesheet files
 5934: 
 5935:   scantron_original_filename (unmodified original file)
 5936:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5937:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5938: 
 5939: Also there is a separate hash nohist_scantrondata that contains extra
 5940: correction information that isn't representable in the bubblesheet
 5941: file (see &scantron_getfile() for more information)
 5942: 
 5943: After all scanlines are either valid, marked as valid or skipped, then
 5944: foreach line foreach problem in the picked sequence, an ssi request is
 5945: made that simulates a user submitting their selected letter(s) against
 5946: the homework problem.
 5947: 
 5948: =over 4
 5949: 
 5950: 
 5951: 
 5952: =item defaultFormData
 5953: 
 5954:   Returns html hidden inputs used to hold context/default values.
 5955: 
 5956:  Arguments:
 5957:   $symb - $symb of the current resource 
 5958: 
 5959: =cut
 5960: 
 5961: sub defaultFormData {
 5962:     my ($symb)=@_;
 5963:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5964: }
 5965: 
 5966: 
 5967: =pod 
 5968: 
 5969: =item getSequenceDropDown
 5970: 
 5971:    Return html dropdown of possible sequences to grade
 5972:  
 5973:  Arguments:
 5974:    $symb - $symb of the current resource
 5975:    $map_error - ref to scalar which will container error if
 5976:                 $navmap object is unavailable in &getSymbMap().
 5977: 
 5978: =cut
 5979: 
 5980: sub getSequenceDropDown {
 5981:     my ($symb,$map_error)=@_;
 5982:     my $result='<select name="selectpage">'."\n";
 5983:     my ($titles,$symbx) = &getSymbMap($map_error);
 5984:     if (ref($map_error)) {
 5985:         return if ($$map_error);
 5986:     }
 5987:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5988:     my $ctr=0;
 5989:     foreach (@$titles) {
 5990: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5991: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5992: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5993: 	    '>'.$showtitle.'</option>'."\n";
 5994: 	$ctr++;
 5995:     }
 5996:     $result.= '</select>';
 5997:     return $result;
 5998: }
 5999: 
 6000: my %bubble_lines_per_response;     # no. bubble lines for each response.
 6001:                                    # key is zero-based index - 0, 1, 2 ...
 6002: 
 6003: my %first_bubble_line;             # First bubble line no. for each bubble.
 6004: 
 6005: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 6006:                                    # matchresponse or rankresponse, where 
 6007:                                    # an individual response can have multiple 
 6008:                                    # lines
 6009: 
 6010: my %responsetype_per_response;     # responsetype for each response
 6011: 
 6012: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 6013:                                    # numbered response. Needed when randomorder
 6014:                                    # or randompick are in use. Key is ID, value 
 6015:                                    # is response number.
 6016: 
 6017: # Save and restore the bubble lines array to the form env.
 6018: 
 6019: 
 6020: sub save_bubble_lines {
 6021:     foreach my $line (keys(%bubble_lines_per_response)) {
 6022: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 6023: 	$env{"form.scantron.first_bubble_line.$line"} =
 6024: 	    $first_bubble_line{$line};
 6025:         $env{"form.scantron.sub_bubblelines.$line"} = 
 6026:             $subdivided_bubble_lines{$line};
 6027:         $env{"form.scantron.responsetype.$line"} =
 6028:             $responsetype_per_response{$line};
 6029:     }
 6030:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 6031:         my $line = $masterseq_id_responsenum{$resid};
 6032:         $env{"form.scantron.residpart.$line"} = $resid;
 6033:     }
 6034: }
 6035: 
 6036: 
 6037: sub restore_bubble_lines {
 6038:     my $line = 0;
 6039:     %bubble_lines_per_response = ();
 6040:     %masterseq_id_responsenum = ();
 6041:     while ($env{"form.scantron.bubblelines.$line"}) {
 6042: 	my $value = $env{"form.scantron.bubblelines.$line"};
 6043: 	$bubble_lines_per_response{$line} = $value;
 6044: 	$first_bubble_line{$line}  =
 6045: 	    $env{"form.scantron.first_bubble_line.$line"};
 6046:         $subdivided_bubble_lines{$line} =
 6047:             $env{"form.scantron.sub_bubblelines.$line"};
 6048:         $responsetype_per_response{$line} =
 6049:             $env{"form.scantron.responsetype.$line"};
 6050:         my $id = $env{"form.scantron.residpart.$line"};
 6051:         $masterseq_id_responsenum{$id} = $line;
 6052: 	$line++;
 6053:     }
 6054: }
 6055: 
 6056: =pod 
 6057: 
 6058: =item scantron_filenames
 6059: 
 6060:    Returns a list of the scantron files in the current course 
 6061: 
 6062: =cut
 6063: 
 6064: sub scantron_filenames {
 6065:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6066:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6067:     my $getpropath = 1;
 6068:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6069:                                                         $cname,$getpropath);
 6070:     my @possiblenames;
 6071:     if (ref($dirlist) eq 'ARRAY') {
 6072:         foreach my $filename (sort(@{$dirlist})) {
 6073: 	    ($filename)=split(/&/,$filename);
 6074: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6075: 	    $filename=~s/^scantron_orig_//;
 6076: 	    push(@possiblenames,$filename);
 6077:         }
 6078:     }
 6079:     return @possiblenames;
 6080: }
 6081: 
 6082: =pod 
 6083: 
 6084: =item scantron_uploads
 6085: 
 6086:    Returns  html drop-down list of scantron files in current course.
 6087: 
 6088:  Arguments:
 6089:    $file2grade - filename to set as selected in the dropdown
 6090: 
 6091: =cut
 6092: 
 6093: sub scantron_uploads {
 6094:     my ($file2grade) = @_;
 6095:     my $result=	'<select name="scantron_selectfile">';
 6096:     $result.="<option></option>";
 6097:     foreach my $filename (sort(&scantron_filenames())) {
 6098: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6099:     }
 6100:     $result.="</select>";
 6101:     return $result;
 6102: }
 6103: 
 6104: =pod 
 6105: 
 6106: =item scantron_scantab
 6107: 
 6108:   Returns html drop down of the scantron formats in the scantronformat.tab
 6109:   file.
 6110: 
 6111: =cut
 6112: 
 6113: sub scantron_scantab {
 6114:     my $result='<select name="scantron_format">'."\n";
 6115:     $result.='<option></option>'."\n";
 6116:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6117:     if (@lines > 0) {
 6118:         foreach my $line (@lines) {
 6119:             next if (($line =~ /^\#/) || ($line eq ''));
 6120: 	    my ($name,$descrip)=split(/:/,$line);
 6121: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6122:         }
 6123:     }
 6124:     $result.='</select>'."\n";
 6125:     return $result;
 6126: }
 6127: 
 6128: =pod 
 6129: 
 6130: =item scantron_CODElist
 6131: 
 6132:   Returns html drop down of the saved CODE lists from current course,
 6133:   generated from earlier printings.
 6134: 
 6135: =cut
 6136: 
 6137: sub scantron_CODElist {
 6138:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6139:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6140:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6141:     my $namechoice='<option></option>';
 6142:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6143: 	if ($name =~ /^error: 2 /) { next; }
 6144: 	if ($name =~ /^type\0/) { next; }
 6145: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6146:     }
 6147:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6148:     return $namechoice;
 6149: }
 6150: 
 6151: =pod 
 6152: 
 6153: =item scantron_CODEunique
 6154: 
 6155:   Returns the html for "Each CODE to be used once" radio.
 6156: 
 6157: =cut
 6158: 
 6159: sub scantron_CODEunique {
 6160:     my $result='<span class="LC_nobreak">
 6161:                  <label><input type="radio" name="scantron_CODEunique"
 6162:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6163:                 </span>
 6164:                 <span class="LC_nobreak">
 6165:                  <label><input type="radio" name="scantron_CODEunique"
 6166:                         value="no" />'.&mt('No').' </label>
 6167:                 </span>';
 6168:     return $result;
 6169: }
 6170: 
 6171: =pod 
 6172: 
 6173: =item scantron_selectphase
 6174: 
 6175:   Generates the initial screen to start the bubblesheet process.
 6176:   Allows for - starting a grading run.
 6177:              - downloading existing scan data (original, corrected
 6178:                                                 or skipped info)
 6179: 
 6180:              - uploading new scan data
 6181: 
 6182:  Arguments:
 6183:   $r          - The Apache request object
 6184:   $file2grade - name of the file that contain the scanned data to score
 6185: 
 6186: =cut
 6187: 
 6188: sub scantron_selectphase {
 6189:     my ($r,$file2grade,$symb) = @_;
 6190:     if (!$symb) {return '';}
 6191:     my $map_error;
 6192:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6193:     if ($map_error) {
 6194:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6195:         return;
 6196:     }
 6197:     my $default_form_data=&defaultFormData($symb);
 6198:     my $file_selector=&scantron_uploads($file2grade);
 6199:     my $format_selector=&scantron_scantab();
 6200:     my $CODE_selector=&scantron_CODElist();
 6201:     my $CODE_unique=&scantron_CODEunique();
 6202:     my $result;
 6203: 
 6204:     $ssi_error = 0;
 6205: 
 6206:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6207: 
 6208: 	# Chunk of form to prompt for a scantron file upload.
 6209: 
 6210:         $r->print('
 6211:     <br />');
 6212:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6213:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6214:     my $csec= $env{'request.course.sec'};
 6215:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6216:     &js_escape(\$alertmsg);
 6217:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6218:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6219:     function checkUpload(formname) {
 6220: 	if (formname.upfile.value == "") {
 6221: 	    alert("'.$alertmsg.'");
 6222: 	    return false;
 6223: 	}
 6224: 	formname.submit();
 6225:     }'."\n".$formatjs));
 6226:     $r->print('
 6227:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6228:                 '.$default_form_data.'
 6229:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6230:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6231:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6232:                 <input name="command" value="scantronupload_save" type="hidden" />
 6233:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6234:               '.&Apache::loncommon::start_data_table_header_row().'
 6235:                 <th>
 6236:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6237:                 </th>
 6238:               '.&Apache::loncommon::end_data_table_header_row().'
 6239:               '.&Apache::loncommon::start_data_table_row().'
 6240:             <td>
 6241:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6242:     if ($formatoptions) {
 6243:         $r->print('</td>
 6244:                  '.&Apache::loncommon::end_data_table_row().'
 6245:                  '.&Apache::loncommon::start_data_table_row().'
 6246:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6247:                  </td>
 6248:                  '.&Apache::loncommon::end_data_table_row().'
 6249:                  '.&Apache::loncommon::start_data_table_row().'
 6250:                  <td>'
 6251:         );
 6252:     } else {
 6253:         $r->print(' <br />');
 6254:     }
 6255:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6256:               </td>
 6257:              '.&Apache::loncommon::end_data_table_row().'
 6258:              '.&Apache::loncommon::end_data_table().'
 6259:              </form>'
 6260:     );
 6261: 
 6262:     }
 6263: 
 6264:     # Chunk of form to prompt for a file to grade and how:
 6265: 
 6266:     $result.= '
 6267:     <br />
 6268:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6269:     <input type="hidden" name="command" value="scantron_warning" />
 6270:     '.$default_form_data.'
 6271:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6272:        '.&Apache::loncommon::start_data_table_header_row().'
 6273:             <th colspan="2">
 6274:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6275:             </th>
 6276:        '.&Apache::loncommon::end_data_table_header_row().'
 6277:        '.&Apache::loncommon::start_data_table_row().'
 6278:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6279:        '.&Apache::loncommon::end_data_table_row().'
 6280:        '.&Apache::loncommon::start_data_table_row().'
 6281:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6282:        '.&Apache::loncommon::end_data_table_row().'
 6283:        '.&Apache::loncommon::start_data_table_row().'
 6284:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6285:        '.&Apache::loncommon::end_data_table_row().'
 6286:        '.&Apache::loncommon::start_data_table_row().'
 6287:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6288:        '.&Apache::loncommon::end_data_table_row().'
 6289:        '.&Apache::loncommon::start_data_table_row().'
 6290:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6291:        '.&Apache::loncommon::end_data_table_row().'
 6292:        '.&Apache::loncommon::start_data_table_row().'
 6293: 	    <td> '.&mt('Options:').' </td>
 6294:             <td>
 6295: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6296:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6297:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6298: 	    </td>
 6299:        '.&Apache::loncommon::end_data_table_row().'
 6300:        '.&Apache::loncommon::start_data_table_row().'
 6301:             <td colspan="2">
 6302:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6303:             </td>
 6304:        '.&Apache::loncommon::end_data_table_row().'
 6305:     '.&Apache::loncommon::end_data_table().'
 6306:     </form>
 6307: ';
 6308:    
 6309:     $r->print($result);
 6310: 
 6311:     # Chunk of the form that prompts to view a scoring office file,
 6312:     # corrected file, skipped records in a file.
 6313: 
 6314:     $r->print('
 6315:    <br />
 6316:    <form action="/adm/grades" name="scantron_download">
 6317:      '.$default_form_data.'
 6318:      <input type="hidden" name="command" value="scantron_download" />
 6319:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6320:        '.&Apache::loncommon::start_data_table_header_row().'
 6321:               <th>
 6322:                 &nbsp;'.&mt('Download a scoring office file').'
 6323:               </th>
 6324:        '.&Apache::loncommon::end_data_table_header_row().'
 6325:        '.&Apache::loncommon::start_data_table_row().'
 6326:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6327:                 <br />
 6328:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6329:        '.&Apache::loncommon::end_data_table_row().'
 6330:      '.&Apache::loncommon::end_data_table().'
 6331:    </form>
 6332:    <br />
 6333: ');
 6334: 
 6335:     &Apache::lonpickcode::code_list($r,2);
 6336: 
 6337:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6338:              $default_form_data."\n".
 6339:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6340:              &Apache::loncommon::start_data_table_header_row()."\n".
 6341:              '<th colspan="2">
 6342:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6343:              '</th>'."\n".
 6344:               &Apache::loncommon::end_data_table_header_row()."\n".
 6345:               &Apache::loncommon::start_data_table_row()."\n".
 6346:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6347:               '<td> '.$sequence_selector.' </td>'.
 6348:               &Apache::loncommon::end_data_table_row()."\n".
 6349:               &Apache::loncommon::start_data_table_row()."\n".
 6350:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6351:               '<td> '.$file_selector.' </td>'."\n".
 6352:               &Apache::loncommon::end_data_table_row()."\n".
 6353:               &Apache::loncommon::start_data_table_row()."\n".
 6354:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6355:               '<td> '.$format_selector.' </td>'."\n".
 6356:               &Apache::loncommon::end_data_table_row()."\n".
 6357:               &Apache::loncommon::start_data_table_row()."\n".
 6358:               '<td> '.&mt('Options').' </td>'."\n".
 6359:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6360:               &Apache::loncommon::end_data_table_row()."\n".
 6361:               &Apache::loncommon::start_data_table_row()."\n".
 6362:               '<td colspan="2">'."\n".
 6363:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6364:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6365:               '</td>'."\n".
 6366:               &Apache::loncommon::end_data_table_row()."\n".
 6367:               &Apache::loncommon::end_data_table()."\n".
 6368:               '</form><br />');
 6369:     return;
 6370: }
 6371: 
 6372: =pod 
 6373: 
 6374: =item username_to_idmap
 6375: 
 6376:     creates a hash keyed by student/employee ID with values of the corresponding
 6377:     student username:domain. If a single ID occurs for more than one student,
 6378:     the status of the student is checked, and if Active, the value in the hash
 6379:     will be set to the Active student.
 6380: 
 6381:   Arguments:
 6382: 
 6383:     $classlist - reference to the class list hash. This is a hash
 6384:                  keyed by student name:domain  whose elements are references
 6385:                  to arrays containing various chunks of information
 6386:                  about the student. (See loncoursedata for more info).
 6387: 
 6388:   Returns
 6389:     %idmap - the constructed hash
 6390: 
 6391: =cut
 6392: 
 6393: sub username_to_idmap {
 6394:     my ($classlist)= @_;
 6395:     my %idmap;
 6396:     foreach my $student (keys(%$classlist)) {
 6397:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6398:         unless ($id eq '') {
 6399:             if (!exists($idmap{$id})) {
 6400:                 $idmap{$id} = $student;
 6401:             } else {
 6402:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6403:                 if ($status eq 'Active') {
 6404:                     $idmap{$id} = $student;
 6405:                 }
 6406:             }
 6407:         }
 6408:     }
 6409:     return %idmap;
 6410: }
 6411: 
 6412: =pod
 6413: 
 6414: =item scantron_fixup_scanline
 6415: 
 6416:    Process a requested correction to a scanline.
 6417: 
 6418:   Arguments:
 6419:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6420:     $scan_data         - hash of correction information 
 6421:                           (see &scantron_getfile())
 6422:     $line              - existing scanline
 6423:     $whichline         - line number of the passed in scanline
 6424:     $field             - type of change to process 
 6425:                          (either 
 6426:                           'ID'     -> correct the student/employee ID
 6427:                           'CODE'   -> correct the CODE
 6428:                           'answer' -> fixup the submitted answers)
 6429:     
 6430:    $args               - hash of additional info,
 6431:                           - 'ID' 
 6432:                                'newid' -> studentID to use in replacement
 6433:                                           of existing one
 6434:                           - 'CODE' 
 6435:                                'CODE_ignore_dup' - set to true if duplicates
 6436:                                                    should be ignored.
 6437: 	                       'CODE' - is new code or 'use_unfound'
 6438:                                         if the existing unfound code should
 6439:                                         be used as is
 6440:                           - 'answer'
 6441:                                'response' - new answer or 'none' if blank
 6442:                                'question' - the bubble line to change
 6443:                                'questionnum' - the question identifier,
 6444:                                                may include subquestion. 
 6445: 
 6446:   Returns:
 6447:     $line - the modified scanline
 6448: 
 6449:   Side effects: 
 6450:     $scan_data - may be updated
 6451: 
 6452: =cut
 6453: 
 6454: 
 6455: sub scantron_fixup_scanline {
 6456:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6457:     if ($field eq 'ID') {
 6458: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6459: 	    return ($line,1,'New value too large');
 6460: 	}
 6461: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6462: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6463: 				     $args->{'newid'});
 6464: 	}
 6465: 	substr($line,$$scantron_config{'IDstart'}-1,
 6466: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6467: 	if ($args->{'newid'}=~/^\s*$/) {
 6468: 	    &scan_data($scan_data,"$whichline.user",
 6469: 		       $args->{'username'}.':'.$args->{'domain'});
 6470: 	}
 6471:     } elsif ($field eq 'CODE') {
 6472: 	if ($args->{'CODE_ignore_dup'}) {
 6473: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6474: 	}
 6475: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6476: 	if ($args->{'CODE'} ne 'use_unfound') {
 6477: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6478: 		return ($line,1,'New CODE value too large');
 6479: 	    }
 6480: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6481: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6482: 	    }
 6483: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6484: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6485: 	}
 6486:     } elsif ($field eq 'answer') {
 6487: 	my $length=$scantron_config->{'Qlength'};
 6488: 	my $off=$scantron_config->{'Qoff'};
 6489: 	my $on=$scantron_config->{'Qon'};
 6490: 	my $answer=${off}x$length;
 6491: 	if ($args->{'response'} eq 'none') {
 6492: 	    &scan_data($scan_data,
 6493: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6494: 	} else {
 6495: 	    if ($on eq 'letter') {
 6496: 		my @alphabet=('A'..'Z');
 6497: 		$answer=$alphabet[$args->{'response'}];
 6498: 	    } elsif ($on eq 'number') {
 6499: 		$answer=$args->{'response'}+1;
 6500: 		if ($answer == 10) { $answer = '0'; }
 6501: 	    } else {
 6502: 		substr($answer,$args->{'response'},1)=$on;
 6503: 	    }
 6504: 	    &scan_data($scan_data,
 6505: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6506: 	}
 6507: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6508: 	substr($line,$where-1,$length)=$answer;
 6509:     }
 6510:     return $line;
 6511: }
 6512: 
 6513: =pod
 6514: 
 6515: =item scan_data
 6516: 
 6517:     Edit or look up  an item in the scan_data hash.
 6518: 
 6519:   Arguments:
 6520:     $scan_data  - The hash (see scantron_getfile)
 6521:     $key        - shorthand of the key to edit (actual key is
 6522:                   scantronfilename_key).
 6523:     $data        - New value of the hash entry.
 6524:     $delete      - If true, the entry is removed from the hash.
 6525: 
 6526:   Returns:
 6527:     The new value of the hash table field (undefined if deleted).
 6528: 
 6529: =cut
 6530: 
 6531: 
 6532: sub scan_data {
 6533:     my ($scan_data,$key,$value,$delete)=@_;
 6534:     my $filename=$env{'form.scantron_selectfile'};
 6535:     if (defined($value)) {
 6536: 	$scan_data->{$filename.'_'.$key} = $value;
 6537:     }
 6538:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6539:     return $scan_data->{$filename.'_'.$key};
 6540: }
 6541: 
 6542: # ----- These first few routines are general use routines.----
 6543: 
 6544: # Return the number of occurences of a pattern in a string.
 6545: 
 6546: sub occurence_count {
 6547:     my ($string, $pattern) = @_;
 6548: 
 6549:     my @matches = ($string =~ /$pattern/g);
 6550: 
 6551:     return scalar(@matches);
 6552: }
 6553: 
 6554: 
 6555: # Take a string known to have digits and convert all the
 6556: # digits into letters in the range J,A..I.
 6557: 
 6558: sub digits_to_letters {
 6559:     my ($input) = @_;
 6560: 
 6561:     my @alphabet = ('J', 'A'..'I');
 6562: 
 6563:     my @input    = split(//, $input);
 6564:     my $output ='';
 6565:     for (my $i = 0; $i < scalar(@input); $i++) {
 6566: 	if ($input[$i] =~ /\d/) {
 6567: 	    $output .= $alphabet[$input[$i]];
 6568: 	} else {
 6569: 	    $output .= $input[$i];
 6570: 	}
 6571:     }
 6572:     return $output;
 6573: }
 6574: 
 6575: =pod 
 6576: 
 6577: =item scantron_parse_scanline
 6578: 
 6579:   Decodes a scanline from the selected bubblesheet file
 6580: 
 6581:  Arguments:
 6582:     line             - The text of the bubblesheet file line to process
 6583:     whichline        - Line number
 6584:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6585:     scan_data        - Hash of extra information about the scanline
 6586:                        (see scantron_getfile for more information)
 6587:     just_header      - True if should not process question answers but only
 6588:                        the stuff to the left of the answers.
 6589:     randomorder      - True if randomorder in use
 6590:     randompick       - True if randompick in use
 6591:     sequence         - Exam folder URL
 6592:     master_seq       - Ref to array containing symbs in exam folder
 6593:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6594:                        (corresponding values are resource objects)
 6595:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6596:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6597:                        are refs to an array of resource objects, ordered
 6598:                        according to order used for CODE, when randomorder
 6599:                        and or randompick are in use.
 6600:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6601:                        for current line to question number used for same question
 6602:                         in "Master Sequence" (as seen by Course Coordinator).
 6603:     startline        - Ref to hash where key is question number (0 is first)
 6604:                        and value is number of first bubble line for current 
 6605:                        student or code-based randompick and/or randomorder.
 6606:     totalref         - Ref of scalar used to score total number of bubble
 6607:                        lines needed for responses in a scan line (used when
 6608:                        randompick in use. 
 6609:     
 6610:  Returns:
 6611:    Hash containing the result of parsing the scanline
 6612: 
 6613:    Keys are all proceeded by the string 'scantron.'
 6614: 
 6615:        CODE    - the CODE in use for this scanline
 6616:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6617:                  by the operator
 6618:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6619:                             CODEs were selected, but the usage has been
 6620:                             forced by the operator
 6621:        ID  - student/employee ID
 6622:        PaperID - if used, the ID number printed on the sheet when the 
 6623:                  paper was scanned
 6624:        FirstName - first name from the sheet
 6625:        LastName  - last name from the sheet
 6626: 
 6627:      if just_header was not true these key may also exist
 6628: 
 6629:        missingerror - a list of bubble ranges that are considered to be answers
 6630:                       to a single question that don't have any bubbles filled in.
 6631:                       Of the form questionnumber:firstbubblenumber:count.
 6632:        doubleerror  - a list of bubble ranges that are considered to be answers
 6633:                       to a single question that have more than one bubble filled in.
 6634:                       Of the form questionnumber::firstbubblenumber:count
 6635:    
 6636:                 In the above, count is the number of bubble responses in the
 6637:                 input line needed to represent the possible answers to the question.
 6638:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6639:                 per line would have count = 2.
 6640: 
 6641:        maxquest     - the number of the last bubble line that was parsed
 6642: 
 6643:        (<number> starts at 1)
 6644:        <number>.answer - zero or more letters representing the selected
 6645:                          letters from the scanline for the bubble line 
 6646:                          <number>.
 6647:                          if blank there was either no bubble or there where
 6648:                          multiple bubbles, (consult the keys missingerror and
 6649:                          doubleerror if this is an error condition)
 6650: 
 6651: =cut
 6652: 
 6653: sub scantron_parse_scanline {
 6654:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6655:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6656:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6657: 
 6658:     my %record;
 6659:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6660:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6661: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6662: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6663: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6664: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6665: 	    $record{'scantron.CODE'}=substr($data,
 6666: 					    $$scantron_config{'CODEstart'}-1,
 6667: 					    $$scantron_config{'CODElength'});
 6668: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6669: 		$record{'scantron.useCODE'}=1;
 6670: 	    }
 6671: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6672: 		$record{'scantron.CODE_ignore_dup'}=1;
 6673: 	    }
 6674: 	} else {
 6675: 	    #FIXME interpret first N questions
 6676: 	}
 6677:     }
 6678:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6679: 				  $$scantron_config{'IDlength'});
 6680:     $record{'scantron.PaperID'}=
 6681: 	substr($data,$$scantron_config{'PaperID'}-1,
 6682: 	       $$scantron_config{'PaperIDlength'});
 6683:     $record{'scantron.FirstName'}=
 6684: 	substr($data,$$scantron_config{'FirstName'}-1,
 6685: 	       $$scantron_config{'FirstNamelength'});
 6686:     $record{'scantron.LastName'}=
 6687: 	substr($data,$$scantron_config{'LastName'}-1,
 6688: 	       $$scantron_config{'LastNamelength'});
 6689:     if ($just_header) { return \%record; }
 6690: 
 6691:     my @alphabet=('A'..'Z');
 6692:     my $questnum=0;
 6693:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6694: 
 6695:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6696:     if ($randompick || $randomorder) {
 6697:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6698:                                          $master_seq,$symb_to_resource,
 6699:                                          $partids_by_symb,$orderedforcode,
 6700:                                          $respnumlookup,$startline);
 6701:         if ($total) {
 6702:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6703:         }
 6704:         if (ref($totalref)) {
 6705:             $$totalref = $total;
 6706:         }
 6707:     }
 6708:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6709:     chomp($questions);		# Get rid of any trailing \n.
 6710:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6711:     while (length($questions)) {
 6712:         my $answers_needed;
 6713:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6714:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6715:         } else {
 6716: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6717:         }
 6718:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6719:                              || 1;
 6720:         $questnum++;
 6721:         my $quest_id = $questnum;
 6722:         my $currentquest = substr($questions,0,$answer_length);
 6723:         $questions       = substr($questions,$answer_length);
 6724:         if (length($currentquest) < $answer_length) { next; }
 6725: 
 6726:         my $subdivided;
 6727:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6728:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6729:         } else {
 6730:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6731:         }
 6732:         if ($subdivided =~ /,/) {
 6733:             my $subquestnum = 1;
 6734:             my $subquestions = $currentquest;
 6735:             my @subanswers_needed = split(/,/,$subdivided);
 6736:             foreach my $subans (@subanswers_needed) {
 6737:                 my $subans_length =
 6738:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6739:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6740:                 $subquestions   = substr($subquestions,$subans_length);
 6741:                 $quest_id = "$questnum.$subquestnum";
 6742:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6743:                     ($$scantron_config{'Qon'} eq 'number')) {
 6744:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6745:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6746:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6747:                         $randomorder,$randompick,$respnumlookup);
 6748:                 } else {
 6749:                     $ansnum = &scantron_validator_positional($ansnum,
 6750:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6751:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6752:                         $randomorder,$randompick,$respnumlookup);
 6753:                 }
 6754:                 $subquestnum ++;
 6755:             }
 6756:         } else {
 6757:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6758:                 ($$scantron_config{'Qon'} eq 'number')) {
 6759:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6760:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6761:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6762:                     $randomorder,$randompick,$respnumlookup);
 6763:             } else {
 6764:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6765:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6766:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6767:                     $randomorder,$randompick,$respnumlookup);
 6768:             }
 6769:         }
 6770:     }
 6771:     $record{'scantron.maxquest'}=$questnum;
 6772:     return \%record;
 6773: }
 6774: 
 6775: sub get_master_seq {
 6776:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
 6777:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6778:                    (ref($symb_to_resource) eq 'HASH'));
 6779:     if ($need_symb_in_map) {
 6780:         return unless (ref($symb_for_examcode) eq 'HASH');
 6781:     }
 6782:     my $resource_error;
 6783:     foreach my $resource (@{$resources}) {
 6784:         my $ressymb;
 6785:         if (ref($resource)) {
 6786:             $ressymb = $resource->symb();
 6787:             push(@{$master_seq},$ressymb);
 6788:             $symb_to_resource->{$ressymb} = $resource;
 6789:             if ($need_symb_in_map) {
 6790:                 unless ($resource->is_map()) {
 6791:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
 6792:                     unless (exists($symb_for_examcode->{$map})) {
 6793:                         $symb_for_examcode->{$map} = $ressymb;
 6794:                     }
 6795:                 }
 6796:             }
 6797:         } else {
 6798:             $resource_error = 1;
 6799:             last;
 6800:         }
 6801:     }
 6802:     return $resource_error;
 6803: }
 6804: 
 6805: sub get_respnum_lookups {
 6806:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6807:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6808:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6809:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6810:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6811:                    (ref($startline) eq 'HASH'));
 6812:     my ($user,$scancode);
 6813:     if ((exists($record->{'scantron.CODE'})) &&
 6814:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6815:         $scancode = $record->{'scantron.CODE'};
 6816:     } else {
 6817:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6818:     }
 6819:     my @mapresources =
 6820:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6821:                      $orderedforcode);
 6822:     my $total = 0;
 6823:     my $count = 0;
 6824:     foreach my $resource (@mapresources) {
 6825:         my $id = $resource->id();
 6826:         my $symb = $resource->symb();
 6827:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6828:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6829:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6830:                 if ($respnum ne '') {
 6831:                     $respnumlookup->{$count} = $respnum;
 6832:                     $startline->{$count} = $total;
 6833:                     $total += $bubble_lines_per_response{$respnum};
 6834:                     $count ++;
 6835:                 }
 6836:             }
 6837:         }
 6838:     }
 6839:     return $total;
 6840: }
 6841: 
 6842: sub scantron_validator_lettnum {
 6843:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6844:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6845:         $randompick,$respnumlookup) = @_;
 6846: 
 6847:     # Qon 'letter' implies for each slot in currquest we have:
 6848:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6849:     #    about anything else (esp. a value of Qoff) for missing
 6850:     #    bubbles.
 6851:     #
 6852:     # Qon 'number' implies each slot gives a digit that indexes the
 6853:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6854:     #    and * or ? for double bubbles on a single line.
 6855:     #
 6856: 
 6857:     my $matchon;
 6858:     if ($$scantron_config{'Qon'} eq 'letter') {
 6859:         $matchon = '[A-Z]';
 6860:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6861:         $matchon = '\d';
 6862:     }
 6863:     my $occurrences = 0;
 6864:     my $responsenum = $questnum-1;
 6865:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6866:        $responsenum = $respnumlookup->{$questnum-1} 
 6867:     }
 6868:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6869:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6870:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6871:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6872:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6873:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6874:         my @singlelines = split('',$currquest);
 6875:         foreach my $entry (@singlelines) {
 6876:             $occurrences = &occurence_count($entry,$matchon);
 6877:             if ($occurrences > 1) {
 6878:                 last;
 6879:             }
 6880:         }
 6881:     } else {
 6882:         $occurrences = &occurence_count($currquest,$matchon); 
 6883:     }
 6884:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6885:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6886:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6887:             my $bubble = substr($currquest,$ans,1);
 6888:             if ($bubble =~ /$matchon/ ) {
 6889:                 if ($$scantron_config{'Qon'} eq 'number') {
 6890:                     if ($bubble == 0) {
 6891:                         $bubble = 10; 
 6892:                     }
 6893:                     $record->{"scantron.$ansnum.answer"} = 
 6894:                         $alphabet->[$bubble-1];
 6895:                 } else {
 6896:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6897:                 }
 6898:             } else {
 6899:                 $record->{"scantron.$ansnum.answer"}='';
 6900:             }
 6901:             $ansnum++;
 6902:         }
 6903:     } elsif (!defined($currquest)
 6904:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6905:             || (&occurence_count($currquest,$matchon) == 0)) {
 6906:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6907:             $record->{"scantron.$ansnum.answer"}='';
 6908:             $ansnum++;
 6909:         }
 6910:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6911:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6912:         }
 6913:     } else {
 6914:         if ($$scantron_config{'Qon'} eq 'number') {
 6915:             $currquest = &digits_to_letters($currquest);            
 6916:         }
 6917:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6918:             my $bubble = substr($currquest,$ans,1);
 6919:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6920:             $ansnum++;
 6921:         }
 6922:     }
 6923:     return $ansnum;
 6924: }
 6925: 
 6926: sub scantron_validator_positional {
 6927:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6928:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6929:         $randomorder,$randompick,$respnumlookup) = @_;
 6930: 
 6931:     # Otherwise there's a positional notation;
 6932:     # each bubble line requires Qlength items, and there are filled in
 6933:     # bubbles for each case where there 'Qon' characters.
 6934:     #
 6935: 
 6936:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6937: 
 6938:     # If the split only gives us one element.. the full length of the
 6939:     # answer string, no bubbles are filled in:
 6940: 
 6941:     if ($answers_needed eq '') {
 6942:         return;
 6943:     }
 6944: 
 6945:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6946:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6947:             $record->{"scantron.$ansnum.answer"}='';
 6948:             $ansnum++;
 6949:         }
 6950:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6951:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6952:         }
 6953:     } elsif (scalar(@array) == 2) {
 6954:         my $location = length($array[0]);
 6955:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6956:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6957:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6958:             if ($ans eq $line_num) {
 6959:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6960:             } else {
 6961:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6962:             }
 6963:             $ansnum++;
 6964:          }
 6965:     } else {
 6966:         #  If there's more than one instance of a bubble character
 6967:         #  That's a double bubble; with positional notation we can
 6968:         #  record all the bubbles filled in as well as the
 6969:         #  fact this response consists of multiple bubbles.
 6970:         #
 6971:         my $responsenum = $questnum-1;
 6972:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6973:             $responsenum = $respnumlookup->{$questnum-1}
 6974:         }
 6975:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6976:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6977:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6978:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6979:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6980:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6981:             my $doubleerror = 0;
 6982:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6983:                    (!$doubleerror)) {
 6984:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6985:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6986:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6987:                if (length(@currarray) > 2) {
 6988:                    $doubleerror = 1;
 6989:                } 
 6990:             }
 6991:             if ($doubleerror) {
 6992:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6993:             }
 6994:         } else {
 6995:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6996:         }
 6997:         my $item = $ansnum;
 6998:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6999:             $record->{"scantron.$item.answer"} = '';
 7000:             $item ++;
 7001:         }
 7002: 
 7003:         my @ans=@array;
 7004:         my $i=0;
 7005:         my $increment = 0;
 7006:         while ($#ans) {
 7007:             $i+=length($ans[0]) + $increment;
 7008:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 7009:             my $bubble = $i%$$scantron_config{'Qlength'};
 7010:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 7011:             shift(@ans);
 7012:             $increment = 1;
 7013:         }
 7014:         $ansnum += $answers_needed;
 7015:     }
 7016:     return $ansnum;
 7017: }
 7018: 
 7019: =pod
 7020: 
 7021: =item scantron_add_delay
 7022: 
 7023:    Adds an error message that occurred during the grading phase to a
 7024:    queue of messages to be shown after grading pass is complete
 7025: 
 7026:  Arguments:
 7027:    $delayqueue  - arrary ref of hash ref of error messages
 7028:    $scanline    - the scanline that caused the error
 7029:    $errormesage - the error message
 7030:    $errorcode   - a numeric code for the error
 7031: 
 7032:  Side Effects:
 7033:    updates the $delayqueue to have a new hash ref of the error
 7034: 
 7035: =cut
 7036: 
 7037: sub scantron_add_delay {
 7038:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 7039:     push(@$delayqueue,
 7040: 	 {'line' => $scanline, 'emsg' => $errormessage,
 7041: 	  'ecode' => $errorcode }
 7042: 	 );
 7043: }
 7044: 
 7045: =pod
 7046: 
 7047: =item scantron_find_student
 7048: 
 7049:    Finds the username for the current scanline
 7050: 
 7051:   Arguments:
 7052:    $scantron_record - hash result from scantron_parse_scanline
 7053:    $scan_data       - hash of correction information 
 7054:                       (see &scantron_getfile() form more information)
 7055:    $idmap           - hash from &username_to_idmap()
 7056:    $line            - number of current scanline
 7057:  
 7058:   Returns:
 7059:    Either 'username:domain' or undef if unknown
 7060: 
 7061: =cut
 7062: 
 7063: sub scantron_find_student {
 7064:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 7065:     my $scanID=$$scantron_record{'scantron.ID'};
 7066:     if ($scanID =~ /^\s*$/) {
 7067:  	return &scan_data($scan_data,"$line.user");
 7068:     }
 7069:     foreach my $id (keys(%$idmap)) {
 7070:  	if (lc($id) eq lc($scanID)) {
 7071:  	    return $$idmap{$id};
 7072:  	}
 7073:     }
 7074:     return undef;
 7075: }
 7076: 
 7077: =pod
 7078: 
 7079: =item scantron_filter
 7080: 
 7081:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7082:    hidden resources was selected
 7083: 
 7084: =cut
 7085: 
 7086: sub scantron_filter {
 7087:     my ($curres)=@_;
 7088: 
 7089:     if (ref($curres) && $curres->is_problem()) {
 7090: 	# if the user has asked to not have either hidden
 7091: 	# or 'randomout' controlled resources to be graded
 7092: 	# don't include them
 7093: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7094: 	    && $curres->randomout) {
 7095: 	    return 0;
 7096: 	}
 7097: 	return 1;
 7098:     }
 7099:     return 0;
 7100: }
 7101: 
 7102: =pod
 7103: 
 7104: =item scantron_process_corrections
 7105: 
 7106:    Gets correction information out of submitted form data and corrects
 7107:    the scanline
 7108: 
 7109: =cut
 7110: 
 7111: sub scantron_process_corrections {
 7112:     my ($r) = @_;
 7113:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7114:     my ($scanlines,$scan_data)=&scantron_getfile();
 7115:     my $classlist=&Apache::loncoursedata::get_classlist();
 7116:     my $which=$env{'form.scantron_line'};
 7117:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7118:     my ($skip,$err,$errmsg);
 7119:     if ($env{'form.scantron_skip_record'}) {
 7120: 	$skip=1;
 7121:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7122: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7123: 	    $env{'form.scantron_domain'};
 7124: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7125: 	($line,$err,$errmsg)=
 7126: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7127: 				     'ID',{'newid'=>$newid,
 7128: 				    'username'=>$env{'form.scantron_username'},
 7129: 				    'domain'=>$env{'form.scantron_domain'}});
 7130:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7131: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7132: 	my $newCODE;
 7133: 	my %args;
 7134: 	if      ($resolution eq 'use_unfound') {
 7135: 	    $newCODE='use_unfound';
 7136: 	} elsif ($resolution eq 'use_found') {
 7137: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7138: 	} elsif ($resolution eq 'use_typed') {
 7139: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7140: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7141: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7142: 	}
 7143: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7144: 	    $args{'CODE_ignore_dup'}=1;
 7145: 	}
 7146: 	$args{'CODE'}=$newCODE;
 7147: 	($line,$err,$errmsg)=
 7148: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7149: 				     'CODE',\%args);
 7150:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7151: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7152: 	    ($line,$err,$errmsg)=
 7153: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7154: 					 $which,'answer',
 7155: 					 { 'question'=>$question,
 7156: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7157:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7158: 	    if ($err) { last; }
 7159: 	}
 7160:     }
 7161:     if ($err) {
 7162:         $r->print(
 7163:             '<p class="LC_error">'
 7164:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7165:                 $errmsg)
 7166:            .'</p>');
 7167:     } else {
 7168: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7169: 	&scantron_putfile($scanlines,$scan_data);
 7170:     }
 7171: }
 7172: 
 7173: =pod
 7174: 
 7175: =item reset_skipping_status
 7176: 
 7177:    Forgets the current set of remember skipped scanlines (and thus
 7178:    reverts back to considering all lines in the
 7179:    scantron_skipped_<filename> file)
 7180: 
 7181: =cut
 7182: 
 7183: sub reset_skipping_status {
 7184:     my ($scanlines,$scan_data)=&scantron_getfile();
 7185:     &scan_data($scan_data,'remember_skipping',undef,1);
 7186:     &scantron_putfile(undef,$scan_data);
 7187: }
 7188: 
 7189: =pod
 7190: 
 7191: =item start_skipping
 7192: 
 7193:    Marks a scanline to be skipped. 
 7194: 
 7195: =cut
 7196: 
 7197: sub start_skipping {
 7198:     my ($scan_data,$i)=@_;
 7199:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7200:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7201: 	$remembered{$i}=2;
 7202:     } else {
 7203: 	$remembered{$i}=1;
 7204:     }
 7205:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7206: }
 7207: 
 7208: =pod
 7209: 
 7210: =item should_be_skipped
 7211: 
 7212:    Checks whether a scanline should be skipped.
 7213: 
 7214: =cut
 7215: 
 7216: sub should_be_skipped {
 7217:     my ($scanlines,$scan_data,$i)=@_;
 7218:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7219: 	# not redoing old skips
 7220: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7221: 	return 0;
 7222:     }
 7223:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7224: 
 7225:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7226: 	return 0;
 7227:     }
 7228:     return 1;
 7229: }
 7230: 
 7231: =pod
 7232: 
 7233: =item remember_current_skipped
 7234: 
 7235:    Discovers what scanlines are in the scantron_skipped_<filename>
 7236:    file and remembers them into scan_data for later use.
 7237: 
 7238: =cut
 7239: 
 7240: sub remember_current_skipped {
 7241:     my ($scanlines,$scan_data)=&scantron_getfile();
 7242:     my %to_remember;
 7243:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7244: 	if ($scanlines->{'skipped'}[$i]) {
 7245: 	    $to_remember{$i}=1;
 7246: 	}
 7247:     }
 7248: 
 7249:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7250:     &scantron_putfile(undef,$scan_data);
 7251: }
 7252: 
 7253: =pod
 7254: 
 7255: =item check_for_error
 7256: 
 7257:     Checks if there was an error when attempting to remove a specific
 7258:     scantron_.. bubblesheet data file. Prints out an error if
 7259:     something went wrong.
 7260: 
 7261: =cut
 7262: 
 7263: sub check_for_error {
 7264:     my ($r,$result)=@_;
 7265:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7266: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7267:     }
 7268: }
 7269: 
 7270: =pod
 7271: 
 7272: =item scantron_warning_screen
 7273: 
 7274:    Interstitial screen to make sure the operator has selected the
 7275:    correct options before we start the validation phase.
 7276: 
 7277: =cut
 7278: 
 7279: sub scantron_warning_screen {
 7280:     my ($button_text,$symb)=@_;
 7281:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7282:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7283:     my $CODElist;
 7284:     if ($scantron_config{'CODElocation'} &&
 7285: 	$scantron_config{'CODEstart'} &&
 7286: 	$scantron_config{'CODElength'}) {
 7287: 	$CODElist=$env{'form.scantron_CODElist'};
 7288: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7289: 	$CODElist=
 7290: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7291: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7292:     }
 7293:     my $lastbubblepoints;
 7294:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7295:         $lastbubblepoints =
 7296:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7297:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7298:     }
 7299:     return '
 7300: <p>
 7301: <span class="LC_warning">
 7302: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7303: </p>
 7304: <table>
 7305: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7306: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7307: '.$CODElist.$lastbubblepoints.'
 7308: </table>
 7309: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7310: '.&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>
 7311: ';
 7312: }
 7313: 
 7314: =pod
 7315: 
 7316: =item scantron_do_warning
 7317: 
 7318:    Check if the operator has picked something for all required
 7319:    fields. Error out if something is missing.
 7320: 
 7321: =cut
 7322: 
 7323: sub scantron_do_warning {
 7324:     my ($r,$symb)=@_;
 7325:     if (!$symb) {return '';}
 7326:     my $default_form_data=&defaultFormData($symb);
 7327:     $r->print(&scantron_form_start().$default_form_data);
 7328:     if ( $env{'form.selectpage'} eq '' ||
 7329: 	 $env{'form.scantron_selectfile'} eq '' ||
 7330: 	 $env{'form.scantron_format'} eq '' ) {
 7331: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7332: 	if ( $env{'form.selectpage'} eq '') {
 7333: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7334: 	} 
 7335: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7336: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7337: 	}
 7338: 	if ( $env{'form.scantron_format'} eq '') {
 7339: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7340: 	}
 7341:     } else {
 7342: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7343:         my ($checksec,@possibles) = &gradable_sections();
 7344:         my $gradesections;
 7345:         if ($checksec) {
 7346:             my $file=$env{'form.scantron_selectfile'};
 7347:             if (&valid_file($file)) {
 7348:                 my %bysec = &scantron_get_sections();
 7349:                 my $table;
 7350:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7351:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7352:                     $table = &Apache::loncommon::start_data_table()."\n".
 7353:                              &Apache::loncommon::start_data_table_header_row().
 7354:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7355:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7356:                     if ($bysec{'none'}) {
 7357:                         $table .= &Apache::loncommon::start_data_table_row().
 7358:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7359:                                   &Apache::loncommon::end_data_table_row()."\n";
 7360:                     }
 7361:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7362:                         next if ($sec eq 'none');
 7363:                         $table .= &Apache::loncommon::start_data_table_row().
 7364:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7365:                                   &Apache::loncommon::end_data_table_row()."\n";
 7366:                     }
 7367:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7368:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7369:                                       '<p>'.$table.'</p>';
 7370:                     if (@possibles) {
 7371:                         $gradesections .= '<p>'.
 7372:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7373:                                               scalar(@possibles)).'<br />'.
 7374:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7375:                                               '<i>'.$checksec.'</i>').' ';
 7376:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7377:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7378:                         }
 7379:                         $gradesections .= '</p>';
 7380:                     }
 7381:                 }
 7382:             } else {
 7383:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7384:             }
 7385:         }
 7386:         my $bubbledbyhand=&hand_bubble_option();
 7387: 	$r->print('
 7388: '.$warning.$gradesections.$bubbledbyhand.'
 7389: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7390: <input type="hidden" name="command" value="scantron_validate" />
 7391: ');
 7392:     }
 7393:     $r->print("</form><br />");
 7394:     return '';
 7395: }
 7396: 
 7397: =pod
 7398: 
 7399: =item scantron_form_start
 7400: 
 7401:     html hidden input for remembering all selected grading options
 7402: 
 7403: =cut
 7404: 
 7405: sub scantron_form_start {
 7406:     my ($max_bubble)=@_;
 7407:     my $result= <<SCANTRONFORM;
 7408: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7409:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7410:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7411:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7412:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7413:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7414:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7415:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7416:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7417:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7418: SCANTRONFORM
 7419: 
 7420:   my $line = 0;
 7421:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7422:        my $chunk =
 7423: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7424:        $chunk .=
 7425: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7426:        $chunk .= 
 7427:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7428:        $chunk .=
 7429:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7430:        $chunk .=
 7431:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7432:        $result .= $chunk;
 7433:        $line++;
 7434:     }
 7435:     return $result;
 7436: }
 7437: 
 7438: =pod
 7439: 
 7440: =item scantron_validate_file
 7441: 
 7442:     Dispatch routine for doing validation of a bubblesheet data file.
 7443: 
 7444:     Also processes any necessary information resets that need to
 7445:     occur before validation begins (ignore previous corrections,
 7446:     restarting the skipped records processing)
 7447: 
 7448: =cut
 7449: 
 7450: sub scantron_validate_file {
 7451:     my ($r,$symb) = @_;
 7452:     if (!$symb) {return '';}
 7453:     my $default_form_data=&defaultFormData($symb);
 7454:     
 7455:     # do the detection of only doing skipped records first before we delete
 7456:     # them when doing the corrections reset
 7457:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7458: 	&reset_skipping_status();
 7459:     }
 7460:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7461: 	&remember_current_skipped();
 7462: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7463:     }
 7464: 
 7465:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7466: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7467: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7468: 	&check_for_error($r,&scantron_remove_scan_data());
 7469: 	$env{'form.scantron_options_ignore'}='done';
 7470:     }
 7471: 
 7472:     if ($env{'form.scantron_corrections'}) {
 7473: 	&scantron_process_corrections($r);
 7474:     }
 7475: 
 7476:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7477:     my ($checksec,@gradable);
 7478:     if ($env{'request.course.sec'}) {
 7479:         ($checksec,my @possibles) = &gradable_sections();
 7480:         if ($checksec) {
 7481:             if (@possibles) {
 7482:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7483:                 if (@chosensecs) {
 7484:                     foreach my $sec (@chosensecs) {
 7485:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7486:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7487:                                 push(@gradable,$sec);
 7488:                             }
 7489:                         }
 7490:                     }
 7491:                 }
 7492:             }
 7493:             $r->print('<p><table>');
 7494:             if (@gradable) {
 7495:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7496:                 $r->print(
 7497:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7498:             } else {
 7499:                 $r->print(
 7500:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7501:             }
 7502:             $r->print('</table></p>');
 7503:         }
 7504:     }
 7505:     $r->rflush();
 7506: 
 7507:     #get the student pick code ready
 7508:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7509:     my $nav_error;
 7510:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7511:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7512:     if ($nav_error) {
 7513:         $r->print(&navmap_errormsg());
 7514:         return '';
 7515:     }
 7516:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7517:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7518:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7519:     }
 7520:     $r->print($result);
 7521:     
 7522:     my @validate_phases=( 'sequence',
 7523: 			  'ID',
 7524: 			  'CODE',
 7525: 			  'doublebubble',
 7526: 			  'missingbubbles');
 7527:     if (!$env{'form.validatepass'}) {
 7528: 	$env{'form.validatepass'} = 0;
 7529:     }
 7530:     my $currentphase=$env{'form.validatepass'};
 7531:     my %skipbysec=();
 7532: 
 7533:     my $stop=0;
 7534:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7535: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7536: 	$r->rflush();
 7537:      
 7538: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7539: 	{
 7540: 	    no strict 'refs';
 7541:             my @extras=();
 7542:             if ($validate_phases[$currentphase] eq 'ID') {
 7543:                 @extras = (\%skipbysec,$checksec,@gradable);
 7544:             }
 7545: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7546: 	}
 7547:     }
 7548:     if (!$stop) {
 7549: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7550:         my $secinfo;
 7551:         if (keys(%skipbysec) > 0) {
 7552:             my $seclist = '<ul>';
 7553:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7554:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7555:             }
 7556:             $seclist .= '</ul>';
 7557:             $secinfo = '<p class="LC_info">'.
 7558:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7559:                            $seclist).
 7560:                        '</p>';
 7561:         }
 7562: 	$r->print(&mt('Validation process complete.').'<br />'.
 7563:                   $secinfo.$warning.
 7564:                   &mt('Perform verification for each student after storage of submissions?').
 7565:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7566:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7567:                   ('&nbsp;'x3).'<label>'.
 7568:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7569:                   '</label></span><br />'.
 7570:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7571:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7572:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7573:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7574:     } else {
 7575: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7576: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7577:     }
 7578:     if ($stop) {
 7579: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7580: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7581: 	    $r->print(' '.&mt('this error').' <br />');
 7582: 
 7583: 	    $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>');
 7584: 	} else {
 7585:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7586: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7587:             } else {
 7588:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7589:             }
 7590: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7591: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7592: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7593: 	}
 7594:     }
 7595:     $r->print(" </form><br />");
 7596:     return '';
 7597: }
 7598: 
 7599: 
 7600: =pod
 7601: 
 7602: =item scantron_remove_file
 7603: 
 7604:    Removes the requested bubblesheet data file, makes sure that
 7605:    scantron_original_<filename> is never removed
 7606: 
 7607: 
 7608: =cut
 7609: 
 7610: sub scantron_remove_file {
 7611:     my ($which)=@_;
 7612:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7613:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7614:     my $file='scantron_';
 7615:     if ($which eq 'corrected' || $which eq 'skipped') {
 7616: 	$file.=$which.'_';
 7617:     } else {
 7618: 	return 'refused';
 7619:     }
 7620:     $file.=$env{'form.scantron_selectfile'};
 7621:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7622: }
 7623: 
 7624: 
 7625: =pod
 7626: 
 7627: =item scantron_remove_scan_data
 7628: 
 7629:    Removes all scan_data correction for the requested bubblesheet
 7630:    data file.  (In the case that both the are doing skipped records we need
 7631:    to remember the old skipped lines for the time being so that element
 7632:    persists for a while.)
 7633: 
 7634: =cut
 7635: 
 7636: sub scantron_remove_scan_data {
 7637:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7638:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7639:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7640:     my @todelete;
 7641:     my $filename=$env{'form.scantron_selectfile'};
 7642:     foreach my $key (@keys) {
 7643: 	if ($key=~/^\Q$filename\E_/) {
 7644: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7645: 		$key=~/remember_skipping/) {
 7646: 		next;
 7647: 	    }
 7648: 	    push(@todelete,$key);
 7649: 	}
 7650:     }
 7651:     my $result;
 7652:     if (@todelete) {
 7653: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7654: 				       \@todelete,$cdom,$cname);
 7655:     } else {
 7656: 	$result = 'ok';
 7657:     }
 7658:     return $result;
 7659: }
 7660: 
 7661: 
 7662: =pod
 7663: 
 7664: =item scantron_getfile
 7665: 
 7666:     Fetches the requested bubblesheet data file (all 3 versions), and
 7667:     the scan_data hash
 7668:   
 7669:   Arguments:
 7670:     None
 7671: 
 7672:   Returns:
 7673:     2 hash references
 7674: 
 7675:      - first one has 
 7676:          orig      -
 7677:          corrected -
 7678:          skipped   -  each of which points to an array ref of the specified
 7679:                       file broken up into individual lines
 7680:          count     - number of scanlines
 7681:  
 7682:      - second is the scan_data hash possible keys are
 7683:        ($number refers to scanline numbered $number and thus the key affects
 7684:         only that scanline
 7685:         $bubline refers to the specific bubble line element and the aspects
 7686:         refers to that specific bubble line element)
 7687: 
 7688:        $number.user - username:domain to use
 7689:        $number.CODE_ignore_dup 
 7690:                     - ignore the duplicate CODE error 
 7691:        $number.useCODE
 7692:                     - use the CODE in the scanline as is
 7693:        $number.no_bubble.$bubline
 7694:                     - it is valid that there is no bubbled in bubble
 7695:                       at $number $bubline
 7696:        remember_skipping
 7697:                     - a frozen hash containing keys of $number and values
 7698:                       of either 
 7699:                         1 - we are on a 'do skipped records pass' and plan
 7700:                             on processing this line
 7701:                         2 - we are on a 'do skipped records pass' and this
 7702:                             scanline has been marked to skip yet again
 7703: 
 7704: =cut
 7705: 
 7706: sub scantron_getfile {
 7707:     #FIXME really would prefer a scantron directory
 7708:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7709:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7710:     my $lines;
 7711:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7712: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7713:     my %scanlines;
 7714:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7715:     my $temp=$scanlines{'orig'};
 7716:     $scanlines{'count'}=$#$temp;
 7717: 
 7718:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7719: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7720:     if ($lines eq '-1') {
 7721: 	$scanlines{'corrected'}=[];
 7722:     } else {
 7723: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7724:     }
 7725:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7726: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7727:     if ($lines eq '-1') {
 7728: 	$scanlines{'skipped'}=[];
 7729:     } else {
 7730: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7731:     }
 7732:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7733:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7734:     my %scan_data = @tmp;
 7735:     return (\%scanlines,\%scan_data);
 7736: }
 7737: 
 7738: =pod
 7739: 
 7740: =item lonnet_putfile
 7741: 
 7742:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7743: 
 7744:  Arguments:
 7745:    $contents - data to store
 7746:    $filename - filename to store $contents into
 7747: 
 7748:  Returns:
 7749:    result value from &Apache::lonnet::finishuserfileupload
 7750: 
 7751: =cut
 7752: 
 7753: sub lonnet_putfile {
 7754:     my ($contents,$filename)=@_;
 7755:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7756:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7757:     $env{'form.sillywaytopassafilearound'}=$contents;
 7758:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7759: 
 7760: }
 7761: 
 7762: =pod
 7763: 
 7764: =item scantron_putfile
 7765: 
 7766:     Stores the current version of the bubblesheet data files, and the
 7767:     scan_data hash. (Does not modify the original version only the
 7768:     corrected and skipped versions.
 7769: 
 7770:  Arguments:
 7771:     $scanlines - hash ref that looks like the first return value from
 7772:                  &scantron_getfile()
 7773:     $scan_data - hash ref that looks like the second return value from
 7774:                  &scantron_getfile()
 7775: 
 7776: =cut
 7777: 
 7778: sub scantron_putfile {
 7779:     my ($scanlines,$scan_data) = @_;
 7780:     #FIXME really would prefer a scantron directory
 7781:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7782:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7783:     if ($scanlines) {
 7784: 	my $prefix='scantron_';
 7785: # no need to update orig, shouldn't change
 7786: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7787: #		    $env{'form.scantron_selectfile'});
 7788: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7789: 			$prefix.'corrected_'.
 7790: 			$env{'form.scantron_selectfile'});
 7791: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7792: 			$prefix.'skipped_'.
 7793: 			$env{'form.scantron_selectfile'});
 7794:     }
 7795:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7796: }
 7797: 
 7798: =pod
 7799: 
 7800: =item scantron_get_line
 7801: 
 7802:    Returns the correct version of the scanline
 7803: 
 7804:  Arguments:
 7805:     $scanlines - hash ref that looks like the first return value from
 7806:                  &scantron_getfile()
 7807:     $scan_data - hash ref that looks like the second return value from
 7808:                  &scantron_getfile()
 7809:     $i         - number of the requested line (starts at 0)
 7810: 
 7811:  Returns:
 7812:    A scanline, (either the original or the corrected one if it
 7813:    exists), or undef if the requested scanline should be
 7814:    skipped. (Either because it's an skipped scanline, or it's an
 7815:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7816:    pass.
 7817: 
 7818: =cut
 7819: 
 7820: sub scantron_get_line {
 7821:     my ($scanlines,$scan_data,$i)=@_;
 7822:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7823:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7824:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7825:     return $scanlines->{'orig'}[$i]; 
 7826: }
 7827: 
 7828: =pod
 7829: 
 7830: =item scantron_todo_count
 7831: 
 7832:     Counts the number of scanlines that need processing.
 7833: 
 7834:  Arguments:
 7835:     $scanlines - hash ref that looks like the first return value from
 7836:                  &scantron_getfile()
 7837:     $scan_data - hash ref that looks like the second return value from
 7838:                  &scantron_getfile()
 7839: 
 7840:  Returns:
 7841:     $count - number of scanlines to process
 7842: 
 7843: =cut
 7844: 
 7845: sub get_todo_count {
 7846:     my ($scanlines,$scan_data)=@_;
 7847:     my $count=0;
 7848:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7849: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7850: 	if ($line=~/^[\s\cz]*$/) { next; }
 7851: 	$count++;
 7852:     }
 7853:     return $count;
 7854: }
 7855: 
 7856: =pod
 7857: 
 7858: =item scantron_put_line
 7859: 
 7860:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7861:     data file.
 7862: 
 7863:  Arguments:
 7864:     $scanlines - hash ref that looks like the first return value from
 7865:                  &scantron_getfile()
 7866:     $scan_data - hash ref that looks like the second return value from
 7867:                  &scantron_getfile()
 7868:     $i         - line number to update
 7869:     $newline   - contents of the updated scanline
 7870:     $skip      - if true make the line for skipping and update the
 7871:                  'skipped' file
 7872: 
 7873: =cut
 7874: 
 7875: sub scantron_put_line {
 7876:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7877:     if ($skip) {
 7878: 	$scanlines->{'skipped'}[$i]=$newline;
 7879: 	&start_skipping($scan_data,$i);
 7880: 	return;
 7881:     }
 7882:     $scanlines->{'corrected'}[$i]=$newline;
 7883: }
 7884: 
 7885: =pod
 7886: 
 7887: =item scantron_clear_skip
 7888: 
 7889:    Remove a line from the 'skipped' file
 7890: 
 7891:  Arguments:
 7892:     $scanlines - hash ref that looks like the first return value from
 7893:                  &scantron_getfile()
 7894:     $scan_data - hash ref that looks like the second return value from
 7895:                  &scantron_getfile()
 7896:     $i         - line number to update
 7897: 
 7898: =cut
 7899: 
 7900: sub scantron_clear_skip {
 7901:     my ($scanlines,$scan_data,$i)=@_;
 7902:     if (exists($scanlines->{'skipped'}[$i])) {
 7903: 	undef($scanlines->{'skipped'}[$i]);
 7904: 	return 1;
 7905:     }
 7906:     return 0;
 7907: }
 7908: 
 7909: =pod
 7910: 
 7911: =item scantron_filter_not_exam
 7912: 
 7913:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7914:    filter out resources that are not marked as 'exam' mode
 7915: 
 7916: =cut
 7917: 
 7918: sub scantron_filter_not_exam {
 7919:     my ($curres)=@_;
 7920:     
 7921:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7922: 	# if the user has asked to not have either hidden
 7923: 	# or 'randomout' controlled resources to be graded
 7924: 	# don't include them
 7925: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7926: 	    && $curres->randomout) {
 7927: 	    return 0;
 7928: 	}
 7929: 	return 1;
 7930:     }
 7931:     return 0;
 7932: }
 7933: 
 7934: =pod
 7935: 
 7936: =item scantron_validate_sequence
 7937: 
 7938:     Validates the selected sequence, checking for resource that are
 7939:     not set to exam mode.
 7940: 
 7941: =cut
 7942: 
 7943: sub scantron_validate_sequence {
 7944:     my ($r,$currentphase) = @_;
 7945: 
 7946:     my $navmap=Apache::lonnavmaps::navmap->new();
 7947:     unless (ref($navmap)) {
 7948:         $r->print(&navmap_errormsg());
 7949:         return (1,$currentphase);
 7950:     }
 7951:     my (undef,undef,$sequence)=
 7952: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7953: 
 7954:     my $map=$navmap->getResourceByUrl($sequence);
 7955: 
 7956:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7957:                                     value="ignore" />');
 7958:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7959: 	my @resources=
 7960: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7961: 	if (@resources) {
 7962: 	    $r->print(
 7963:                 '<p class="LC_warning">'
 7964:                .&mt('Some resources in the sequence currently are not set to'
 7965:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7966:                    .' work correctly.')
 7967:                .'</p>'
 7968:             );
 7969: 	    return (1,$currentphase);
 7970: 	}
 7971:     }
 7972: 
 7973:     return (0,$currentphase+1);
 7974: }
 7975: 
 7976: 
 7977: 
 7978: sub scantron_validate_ID {
 7979:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7980:     
 7981:     #get student info
 7982:     my $classlist=&Apache::loncoursedata::get_classlist();
 7983:     my %idmap=&username_to_idmap($classlist);
 7984:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7985: 
 7986:     #get scantron line setup
 7987:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7988:     my ($scanlines,$scan_data)=&scantron_getfile();
 7989: 
 7990:     my $nav_error;
 7991:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7992:     if ($nav_error) {
 7993:         $r->print(&navmap_errormsg());
 7994:         return(1,$currentphase);
 7995:     }
 7996: 
 7997:     my %found=('ids'=>{},'usernames'=>{});
 7998:     my $unsavedskips = 0;
 7999:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8000: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8001: 	if ($line=~/^[\s\cz]*$/) { next; }
 8002: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8003: 						 $scan_data);
 8004: 	my $id=$$scan_record{'scantron.ID'};
 8005: 	my $found;
 8006: 	foreach my $checkid (keys(%idmap)) {
 8007: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 8008: 	}
 8009: 	if ($found) {
 8010: 	    my $username=$idmap{$found};
 8011:             if ($checksec) {
 8012:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 8013:                     my $stusec = $classlist->{$username}->[$secidx];
 8014:                     if ($stusec ne $checksec) {
 8015:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 8016:                             my $skip=1;
 8017:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 8018:                             if (ref($skipbysec) eq 'HASH') {
 8019:                                 if ($stusec eq '') {
 8020:                                     $skipbysec->{'none'} ++;
 8021:                                 } else {
 8022:                                     $skipbysec->{$stusec} ++;
 8023:                                 }
 8024:                             }
 8025:                             $unsavedskips ++;
 8026:                             next;
 8027:                         }
 8028:                     }
 8029:                 }
 8030:             }
 8031: 	    if ($found{'ids'}{$found}) {
 8032: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8033: 					 $line,'duplicateID',$found);
 8034:                 if ($unsavedskips) {
 8035:                     &scantron_putfile($scanlines,$scan_data);
 8036:                     $unsavedskips = 0;
 8037:                 }
 8038: 		return(1,$currentphase);
 8039: 	    } elsif ($found{'usernames'}{$username}) {
 8040: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8041: 					 $line,'duplicateID',$username);
 8042:                 if ($unsavedskips) {
 8043:                     &scantron_putfile($scanlines,$scan_data);
 8044:                     $unsavedskips = 0;
 8045:                 }
 8046: 		return(1,$currentphase);
 8047: 	    }
 8048: 	    #FIXME store away line we previously saw the ID on to use above
 8049: 	    $found{'ids'}{$found}++;
 8050: 	    $found{'usernames'}{$username}++;
 8051: 	} else {
 8052: 	    if ($id =~ /^\s*$/) {
 8053: 		my $username=&scan_data($scan_data,"$i.user");
 8054:                 if (($checksec && $username ne '')) {
 8055:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 8056:                         my $stusec = $classlist->{$username}->[$secidx];
 8057:                         if ($stusec ne $checksec) {
 8058:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 8059:                                 my $skip=1;
 8060:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 8061:                                 if (ref($skipbysec) eq 'HASH') {
 8062:                                     if ($stusec eq '') {
 8063:                                         $skipbysec->{'none'} ++;
 8064:                                     } else {
 8065:                                         $skipbysec->{$stusec} ++;
 8066:                                     }
 8067:                                 }
 8068:                                 $unsavedskips ++;
 8069:                                 next;
 8070:                             }
 8071:                         }
 8072:                     }
 8073: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 8074: 		    &scantron_get_correction($r,$i,$scan_record,
 8075: 					     \%scantron_config,
 8076: 					     $line,'duplicateID',$username);
 8077:                     if ($unsavedskips) {
 8078:                         &scantron_putfile($scanlines,$scan_data);
 8079:                         $unsavedskips = 0;
 8080:                     }
 8081: 		    return(1,$currentphase);
 8082: 		} elsif (!defined($username)) {
 8083: 		    &scantron_get_correction($r,$i,$scan_record,
 8084: 					     \%scantron_config,
 8085: 					     $line,'incorrectID');
 8086:                     if ($unsavedskips) {
 8087:                         &scantron_putfile($scanlines,$scan_data);
 8088:                         $unsavedskips = 0;
 8089:                     }
 8090: 		    return(1,$currentphase);
 8091: 		}
 8092: 		$found{'usernames'}{$username}++;
 8093: 	    } else {
 8094: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8095: 					 $line,'incorrectID');
 8096:                 if ($unsavedskips) {
 8097:                     &scantron_putfile($scanlines,$scan_data);
 8098:                     $unsavedskips = 0;
 8099:                 }
 8100: 		return(1,$currentphase);
 8101: 	    }
 8102: 	}
 8103:     }
 8104:     if ($unsavedskips) {
 8105:         &scantron_putfile($scanlines,$scan_data);
 8106:         $unsavedskips = 0;
 8107:     }
 8108:     return (0,$currentphase+1);
 8109: }
 8110: 
 8111: sub scantron_get_sections {
 8112:     my %bysec;
 8113:     if ($env{'form.scantron_format'} ne '') {
 8114:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8115:         my ($scanlines,$scan_data)=&scantron_getfile();
 8116:         my $classlist=&Apache::loncoursedata::get_classlist();
 8117:         my %idmap=&username_to_idmap($classlist);
 8118:         foreach my $key (keys(%idmap)) {
 8119:             my $lckey = lc($key);
 8120:             $idmap{$lckey} = $idmap{$key};
 8121:         }
 8122:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 8123:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8124:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8125:             if ($line=~/^[\s\cz]*$/) { next; }
 8126:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8127:                                                      $scan_data);
 8128:             my $id=lc($$scan_record{'scantron.ID'});
 8129:             if (exists($idmap{$id})) {
 8130:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 8131:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 8132:                     if ($stusec eq '') {
 8133:                         $bysec{'none'} ++;
 8134:                     } else {
 8135:                         $bysec{$stusec} ++;
 8136:                     }
 8137:                 }
 8138:             }
 8139:         }
 8140:     }
 8141:     return %bysec;
 8142: }
 8143: 
 8144: sub scantron_get_correction {
 8145:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 8146:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 8147: #FIXME in the case of a duplicated ID the previous line, probably need
 8148: #to show both the current line and the previous one and allow skipping
 8149: #the previous one or the current one
 8150: 
 8151:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8152:         $r->print(
 8153:             '<p class="LC_warning">'
 8154:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8155:                 "<b>$error</b>",
 8156:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8157:            ."</p> \n");
 8158:     } else {
 8159:         $r->print(
 8160:             '<p class="LC_warning">'
 8161:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8162:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8163:            ."</p> \n");
 8164:     }
 8165:     my $message =
 8166:         '<p>'
 8167:        .&mt('The ID on the form is [_1]',
 8168:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8169:        .'<br />'
 8170:        .&mt('The name on the paper is [_1], [_2]',
 8171:             $$scan_record{'scantron.LastName'},
 8172:             $$scan_record{'scantron.FirstName'})
 8173:        .'</p>';
 8174: 
 8175:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8176:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8177:                            # Array populated for doublebubble or
 8178:     my @lines_to_correct;  # missingbubble errors to build javascript
 8179:                            # to validate radio button checking   
 8180: 
 8181:     if ($error =~ /ID$/) {
 8182: 	if ($error eq 'incorrectID') {
 8183:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8184: 		      "</p>\n");
 8185: 	} elsif ($error eq 'duplicateID') {
 8186:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8187: 	}
 8188: 	$r->print($message);
 8189: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8190: 	$r->print("\n<ul><li> ");
 8191: 	#FIXME it would be nice if this sent back the user ID and
 8192: 	#could do partial userID matches
 8193: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8194: 				       'scantron_username','scantron_domain'));
 8195: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8196: 	$r->print("\n:\n".
 8197: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8198: 
 8199: 	$r->print('</li>');
 8200:     } elsif ($error =~ /CODE$/) {
 8201: 	if ($error eq 'incorrectCODE') {
 8202: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8203: 	} elsif ($error eq 'duplicateCODE') {
 8204: 	    $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");
 8205: 	}
 8206: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8207: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8208:                  ."</p>\n");
 8209: 	$r->print($message);
 8210: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8211: 	$r->print("\n<br /> ");
 8212: 	my $i=0;
 8213: 	if ($error eq 'incorrectCODE' 
 8214: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8215: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8216: 	    if ($closest > 0) {
 8217: 		foreach my $testcode (@{$closest}) {
 8218: 		    my $checked='';
 8219: 		    if (!$i) { $checked=' checked="checked"'; }
 8220: 		    $r->print("
 8221:    <label>
 8222:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8223:        ".&mt("Use the similar CODE [_1] instead.",
 8224: 	    "<b><tt>".$testcode."</tt></b>")."
 8225:     </label>
 8226:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8227: 		    $r->print("\n<br />");
 8228: 		    $i++;
 8229: 		}
 8230: 	    }
 8231: 	}
 8232: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8233: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8234: 	    $r->print("
 8235:     <label>
 8236:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8237:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8238: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8239:     </label>");
 8240: 	    $r->print("\n<br />");
 8241: 	}
 8242: 
 8243: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8244: function change_radio(field) {
 8245:     var slct=document.scantronupload.scantron_CODE_resolution;
 8246:     var i;
 8247:     for (i=0;i<slct.length;i++) {
 8248:         if (slct[i].value==field) { slct[i].checked=true; }
 8249:     }
 8250: }
 8251: ENDSCRIPT
 8252: 	my $href="/adm/pickcode?".
 8253: 	   "form=".&escape("scantronupload").
 8254: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8255: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8256: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8257: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8258: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8259: 	    $r->print("
 8260:     <label>
 8261:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8262:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8263: 	     "<a target='_blank' href='$href'>","</a>")."
 8264:     </label> 
 8265:     ".&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\')" />'));
 8266: 	    $r->print("\n<br />");
 8267: 	}
 8268: 	$r->print("
 8269:     <label>
 8270:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8271:        ".&mt("Use [_1] as the CODE.",
 8272: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8273: 	$r->print("\n<br /><br />");
 8274:     } elsif ($error eq 'doublebubble') {
 8275: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8276: 
 8277: 	# The form field scantron_questions is acutally a list of line numbers.
 8278: 	# represented by this form so:
 8279: 
 8280: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8281:                                                 $respnumlookup,$startline);
 8282: 
 8283: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8284: 		  $line_list.'" />');
 8285: 	$r->print($message);
 8286: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8287: 	foreach my $question (@{$arg}) {
 8288: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8289:                                                    $scan_record, $error,
 8290:                                                    $randomorder,$randompick,
 8291:                                                    $respnumlookup,$startline);
 8292:             push(@lines_to_correct,@linenums);
 8293: 	}
 8294:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8295:     } elsif ($error eq 'missingbubble') {
 8296: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8297: 	$r->print($message);
 8298: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8299: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8300: 
 8301: 	# The form field scantron_questions is actually a list of line numbers not
 8302: 	# a list of question numbers. Therefore:
 8303: 	#
 8304: 
 8305: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8306:                                                 $respnumlookup,$startline);
 8307: 
 8308: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8309: 		  $line_list.'" />');
 8310: 	foreach my $question (@{$arg}) {
 8311: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8312:                                                    $scan_record, $error,
 8313:                                                    $randomorder,$randompick,
 8314:                                                    $respnumlookup,$startline);
 8315:             push(@lines_to_correct,@linenums);
 8316: 	}
 8317:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8318:     } else {
 8319: 	$r->print("\n<ul>");
 8320:     }
 8321:     $r->print("\n</li></ul>");
 8322: }
 8323: 
 8324: sub verify_bubbles_checked {
 8325:     my (@ansnums) = @_;
 8326:     my $ansnumstr = join('","',@ansnums);
 8327:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8328:     &js_escape(\$warning);
 8329:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8330: function verify_bubble_radio(form) {
 8331:     var ansnumArray = new Array ("$ansnumstr");
 8332:     var need_bubble_count = 0;
 8333:     for (var i=0; i<ansnumArray.length; i++) {
 8334:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8335:             var bubble_picked = 0; 
 8336:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8337:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8338:                     bubble_picked = 1;
 8339:                 }
 8340:             }
 8341:             if (bubble_picked == 0) {
 8342:                 need_bubble_count ++;
 8343:             }
 8344:         }
 8345:     }
 8346:     if (need_bubble_count) {
 8347:         alert("$warning");
 8348:         return;
 8349:     }
 8350:     form.submit(); 
 8351: }
 8352: ENDSCRIPT
 8353:     return $output;
 8354: }
 8355: 
 8356: =pod
 8357: 
 8358: =item  questions_to_line_list
 8359: 
 8360: Converts a list of questions into a string of comma separated
 8361: line numbers in the answer sheet used by the questions.  This is
 8362: used to fill in the scantron_questions form field.
 8363: 
 8364:   Arguments:
 8365:      questions    - Reference to an array of questions.
 8366:      randomorder  - True if randomorder in use.
 8367:      randompick   - True if randompick in use.
 8368:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8369:                      for current line to question number used for same question
 8370:                      in "Master Seqence" (as seen by Course Coordinator).
 8371:      startline    - Reference to hash where key is question number (0 is first)
 8372:                     and key is number of first bubble line for current student
 8373:                     or code-based randompick and/or randomorder.
 8374: 
 8375: =cut
 8376: 
 8377: 
 8378: sub questions_to_line_list {
 8379:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8380:     my @lines;
 8381: 
 8382:     foreach my $item (@{$questions}) {
 8383:         my $question = $item;
 8384:         my ($first,$count,$last);
 8385:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8386:             $question = $1;
 8387:             my $subquestion = $2;
 8388:             my $responsenum = $question-1;
 8389:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8390:                 $responsenum = $respnumlookup->{$question-1};
 8391:                 if (ref($startline) eq 'HASH') {
 8392:                     $first = $startline->{$question-1} + 1;
 8393:                 }
 8394:             } else {
 8395:                 $first = $first_bubble_line{$responsenum} + 1;
 8396:             }
 8397:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8398:             my $subcount = 1;
 8399:             while ($subcount<$subquestion) {
 8400:                 $first += $subans[$subcount-1];
 8401:                 $subcount ++;
 8402:             }
 8403:             $count = $subans[$subquestion-1];
 8404:         } else {
 8405:             my $responsenum = $question-1;
 8406:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8407:                 $responsenum = $respnumlookup->{$question-1};
 8408:                 if (ref($startline) eq 'HASH') {
 8409:                     $first = $startline->{$question-1} + 1;
 8410:                 }
 8411:             } else {
 8412:                 $first = $first_bubble_line{$responsenum} + 1;
 8413:             }
 8414: 	    $count   = $bubble_lines_per_response{$responsenum};
 8415:         }
 8416:         $last = $first+$count-1;
 8417:         push(@lines, ($first..$last));
 8418:     }
 8419:     return join(',', @lines);
 8420: }
 8421: 
 8422: =pod 
 8423: 
 8424: =item prompt_for_corrections
 8425: 
 8426: Prompts for a potentially multiline correction to the
 8427: user's bubbling (factors out common code from scantron_get_correction
 8428: for multi and missing bubble cases).
 8429: 
 8430:  Arguments:
 8431:    $r           - Apache request object.
 8432:    $question    - The question number to prompt for.
 8433:    $scan_config - The scantron file configuration hash.
 8434:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8435:    $error       - Type of error
 8436:    $randomorder - True if randomorder in use.
 8437:    $randompick  - True if randompick in use.
 8438:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8439:                     for current line to question number used for same question
 8440:                     in "Master Seqence" (as seen by Course Coordinator).
 8441:    $startline   - Reference to hash where key is question number (0 is first)
 8442:                   and value is number of first bubble line for current student
 8443:                   or code-based randompick and/or randomorder.
 8444: 
 8445: 
 8446:  Implicit inputs:
 8447:    %bubble_lines_per_response   - Starting line numbers for each question.
 8448:                                   Numbered from 0 (but question numbers are from
 8449:                                   1.
 8450:    %first_bubble_line           - Starting bubble line for each question.
 8451:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8452:                                   type problems render as separate sub-questions, 
 8453:                                   in exam mode. This hash contains a 
 8454:                                   comma-separated list of the lines per 
 8455:                                   sub-question.
 8456:    %responsetype_per_response   - essayresponse, formularesponse,
 8457:                                   stringresponse, imageresponse, reactionresponse,
 8458:                                   and organicresponse type problem parts can have
 8459:                                   multiple lines per response if the weight
 8460:                                   assigned exceeds 10.  In this case, only
 8461:                                   one bubble per line is permitted, but more 
 8462:                                   than one line might contain bubbles, e.g.
 8463:                                   bubbling of: line 1 - J, line 2 - J, 
 8464:                                   line 3 - B would assign 22 points.  
 8465: 
 8466: =cut
 8467: 
 8468: sub prompt_for_corrections {
 8469:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8470:         $randompick, $respnumlookup, $startline) = @_;
 8471:     my ($current_line,$lines);
 8472:     my @linenums;
 8473:     my $questionnum = $question;
 8474:     my ($first,$responsenum);
 8475:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8476:         $question = $1;
 8477:         my $subquestion = $2;
 8478:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8479:             $responsenum = $respnumlookup->{$question-1};
 8480:             if (ref($startline) eq 'HASH') {
 8481:                 $first = $startline->{$question-1};
 8482:             }
 8483:         } else {
 8484:             $responsenum = $question-1;
 8485:             $first = $first_bubble_line{$responsenum};
 8486:         }
 8487:         $current_line = $first + 1 ;
 8488:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8489:         my $subcount = 1;
 8490:         while ($subcount<$subquestion) {
 8491:             $current_line += $subans[$subcount-1];
 8492:             $subcount ++;
 8493:         }
 8494:         $lines = $subans[$subquestion-1];
 8495:     } else {
 8496:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8497:             $responsenum = $respnumlookup->{$question-1};
 8498:             if (ref($startline) eq 'HASH') { 
 8499:                 $first = $startline->{$question-1};
 8500:             }
 8501:         } else {
 8502:             $responsenum = $question-1;
 8503:             $first = $first_bubble_line{$responsenum};
 8504:         }
 8505:         $current_line = $first + 1;
 8506:         $lines        = $bubble_lines_per_response{$responsenum};
 8507:     }
 8508:     if ($lines > 1) {
 8509:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8510:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8511:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8512:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8513:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8514:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8515:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8516:             $r->print(
 8517:                 &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)
 8518:                .'<br /><br />'
 8519:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8520:                .'<br />'
 8521:                .&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.')
 8522:                .'<br />'
 8523:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8524:                .'<br /><br />'
 8525:             );
 8526:         } else {
 8527:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8528:         }
 8529:     }
 8530:     for (my $i =0; $i < $lines; $i++) {
 8531:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8532: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8533: 	        		  $questionnum,$error,split('', $selected));
 8534:         push(@linenums,$current_line);
 8535: 	$current_line++;
 8536:     }
 8537:     if ($lines > 1) {
 8538: 	$r->print("<hr /><br />");
 8539:     }
 8540:     return @linenums;
 8541: }
 8542: 
 8543: =pod
 8544: 
 8545: =item scantron_bubble_selector
 8546:   
 8547:    Generates the html radiobuttons to correct a single bubble line
 8548:    possibly showing the existing the selected bubbles if known
 8549: 
 8550:  Arguments:
 8551:     $r           - Apache request object
 8552:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8553:     $line        - Number of the line being displayed.
 8554:     $questionnum - Question number (may include subquestion)
 8555:     $error       - Type of error.
 8556:     @selected    - Array of bubbles picked on this line.
 8557: 
 8558: =cut
 8559: 
 8560: sub scantron_bubble_selector {
 8561:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8562:     my $max=$$scan_config{'Qlength'};
 8563: 
 8564:     my $scmode=$$scan_config{'Qon'};
 8565:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8566:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8567:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8568:             $max=$$scan_config{'BubblesPerRow'};
 8569:             if (($scmode eq 'number') && ($max > 10)) {
 8570:                 $max = 10;
 8571:             } elsif (($scmode eq 'letter') && $max > 26) {
 8572:                 $max = 26;
 8573:             }
 8574:         } else {
 8575:             $max = 10;
 8576:         }
 8577:     }
 8578: 
 8579:     my @alphabet=('A'..'Z');
 8580:     $r->print(&Apache::loncommon::start_data_table().
 8581:               &Apache::loncommon::start_data_table_row());
 8582:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8583:     for (my $i=0;$i<$max+1;$i++) {
 8584: 	$r->print("\n".'<td align="center">');
 8585: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8586: 	else { $r->print('&nbsp;'); }
 8587: 	$r->print('</td>');
 8588:     }
 8589:     $r->print(&Apache::loncommon::end_data_table_row().
 8590:               &Apache::loncommon::start_data_table_row());
 8591:     for (my $i=0;$i<$max;$i++) {
 8592: 	$r->print("\n".
 8593: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8594: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8595:     }
 8596:     my $nobub_checked = ' ';
 8597:     if ($error eq 'missingbubble') {
 8598:         $nobub_checked = ' checked = "checked" ';
 8599:     }
 8600:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8601: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8602:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8603:               $line.'" value="'.$questionnum.'" /></td>');
 8604:     $r->print(&Apache::loncommon::end_data_table_row().
 8605:               &Apache::loncommon::end_data_table());
 8606: }
 8607: 
 8608: =pod
 8609: 
 8610: =item num_matches
 8611: 
 8612:    Counts the number of characters that are the same between the two arguments.
 8613: 
 8614:  Arguments:
 8615:    $orig - CODE from the scanline
 8616:    $code - CODE to match against
 8617: 
 8618:  Returns:
 8619:    $count - integer count of the number of same characters between the
 8620:             two arguments
 8621: 
 8622: =cut
 8623: 
 8624: sub num_matches {
 8625:     my ($orig,$code) = @_;
 8626:     my @code=split(//,$code);
 8627:     my @orig=split(//,$orig);
 8628:     my $same=0;
 8629:     for (my $i=0;$i<scalar(@code);$i++) {
 8630: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8631:     }
 8632:     return $same;
 8633: }
 8634: 
 8635: =pod
 8636: 
 8637: =item scantron_get_closely_matching_CODEs
 8638: 
 8639:    Cycles through all CODEs and finds the set that has the greatest
 8640:    number of same characters as the provided CODE
 8641: 
 8642:  Arguments:
 8643:    $allcodes - hash ref returned by &get_codes()
 8644:    $CODE     - CODE from the current scanline
 8645: 
 8646:  Returns:
 8647:    2 element list
 8648:     - first elements is number of how closely matching the best fit is 
 8649:       (5 means best set has 5 matching characters)
 8650:     - second element is an arrary ref containing the set of valid CODEs
 8651:       that best fit the passed in CODE
 8652: 
 8653: =cut
 8654: 
 8655: sub scantron_get_closely_matching_CODEs {
 8656:     my ($allcodes,$CODE)=@_;
 8657:     my @CODEs;
 8658:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8659: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8660:     }
 8661: 
 8662:     return ($#CODEs,$CODEs[-1]);
 8663: }
 8664: 
 8665: =pod
 8666: 
 8667: =item get_codes
 8668: 
 8669:    Builds a hash which has keys of all of the valid CODEs from the selected
 8670:    set of remembered CODEs.
 8671: 
 8672:  Arguments:
 8673:   $old_name - name of the set of remembered CODEs
 8674:   $cdom     - domain of the course
 8675:   $cnum     - internal course name
 8676: 
 8677:  Returns:
 8678:   %allcodes - keys are the valid CODEs, values are all 1
 8679: 
 8680: =cut
 8681: 
 8682: sub get_codes {
 8683:     my ($old_name, $cdom, $cnum) = @_;
 8684:     if (!$old_name) {
 8685: 	$old_name=$env{'form.scantron_CODElist'};
 8686:     }
 8687:     if (!$cdom) {
 8688: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8689:     }
 8690:     if (!$cnum) {
 8691: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8692:     }
 8693:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8694: 				    $cdom,$cnum);
 8695:     my %allcodes;
 8696:     if ($result{"type\0$old_name"} eq 'number') {
 8697: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8698:     } else {
 8699: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8700:     }
 8701:     return %allcodes;
 8702: }
 8703: 
 8704: =pod
 8705: 
 8706: =item scantron_validate_CODE
 8707: 
 8708:    Validates all scanlines in the selected file to not have any
 8709:    invalid or underspecified CODEs and that none of the codes are
 8710:    duplicated if this was requested.
 8711: 
 8712: =cut
 8713: 
 8714: sub scantron_validate_CODE {
 8715:     my ($r,$currentphase) = @_;
 8716:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8717:     if ($scantron_config{'CODElocation'} &&
 8718: 	$scantron_config{'CODEstart'} &&
 8719: 	$scantron_config{'CODElength'}) {
 8720: 	if (!defined($env{'form.scantron_CODElist'})) {
 8721: 	    &FIXME_blow_up()
 8722: 	}
 8723:     } else {
 8724: 	return (0,$currentphase+1);
 8725:     }
 8726:     
 8727:     my %usedCODEs;
 8728: 
 8729:     my %allcodes=&get_codes();
 8730: 
 8731:     my $nav_error;
 8732:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8733:     if ($nav_error) {
 8734:         $r->print(&navmap_errormsg());
 8735:         return(1,$currentphase);
 8736:     }
 8737: 
 8738:     my ($scanlines,$scan_data)=&scantron_getfile();
 8739:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8740: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8741: 	if ($line=~/^[\s\cz]*$/) { next; }
 8742: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8743: 						 $scan_data);
 8744: 	my $CODE=$$scan_record{'scantron.CODE'};
 8745: 	my $error=0;
 8746: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8747: 	    &scantron_get_correction($r,$i,$scan_record,
 8748: 				     \%scantron_config,
 8749: 				     $line,'incorrectCODE',\%allcodes);
 8750: 	    return(1,$currentphase);
 8751: 	}
 8752: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8753: 	    && !$$scan_record{'scantron.useCODE'}) {
 8754: 	    &scantron_get_correction($r,$i,$scan_record,
 8755: 				     \%scantron_config,
 8756: 				     $line,'incorrectCODE',\%allcodes);
 8757: 	    return(1,$currentphase);
 8758: 	}
 8759: 	if (exists($usedCODEs{$CODE}) 
 8760: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8761: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8762: 	    &scantron_get_correction($r,$i,$scan_record,
 8763: 				     \%scantron_config,
 8764: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8765: 	    return(1,$currentphase);
 8766: 	}
 8767: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8768:     }
 8769:     return (0,$currentphase+1);
 8770: }
 8771: 
 8772: =pod
 8773: 
 8774: =item scantron_validate_doublebubble
 8775: 
 8776:    Validates all scanlines in the selected file to not have any
 8777:    bubble lines with multiple bubbles marked.
 8778: 
 8779: =cut
 8780: 
 8781: sub scantron_validate_doublebubble {
 8782:     my ($r,$currentphase) = @_;
 8783:     #get student info
 8784:     my $classlist=&Apache::loncoursedata::get_classlist();
 8785:     my %idmap=&username_to_idmap($classlist);
 8786:     my (undef,undef,$sequence)=
 8787:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8788: 
 8789:     #get scantron line setup
 8790:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8791:     my ($scanlines,$scan_data)=&scantron_getfile();
 8792: 
 8793:     my $navmap = Apache::lonnavmaps::navmap->new();
 8794:     unless (ref($navmap)) {
 8795:         $r->print(&navmap_errormsg());
 8796:         return(1,$currentphase);
 8797:     }
 8798:     my $map=$navmap->getResourceByUrl($sequence);
 8799:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8800:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8801:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8802:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8803: 
 8804:     my $nav_error;
 8805:     if (ref($map)) {
 8806:         $randomorder = $map->randomorder();
 8807:         $randompick = $map->randompick();
 8808:         unless ($randomorder || $randompick) {
 8809:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8810:                 if ($res->randomorder()) {
 8811:                     $randomorder = 1;
 8812:                 }
 8813:                 if ($res->randompick()) {
 8814:                     $randompick = 1;
 8815:                 }
 8816:                 last if ($randomorder || $randompick);
 8817:             }
 8818:         }
 8819:         if ($randomorder || $randompick) {
 8820:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8821:             if ($nav_error) {
 8822:                 $r->print(&navmap_errormsg());
 8823:                 return(1,$currentphase);
 8824:             }
 8825:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8826:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8827:         }
 8828:     } else {
 8829:         $r->print(&navmap_errormsg());
 8830:         return(1,$currentphase);
 8831:     }
 8832: 
 8833:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8834:     if ($nav_error) {
 8835:         $r->print(&navmap_errormsg());
 8836:         return(1,$currentphase);
 8837:     }
 8838: 
 8839:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8840: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8841: 	if ($line=~/^[\s\cz]*$/) { next; }
 8842: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8843: 						 $scan_data,undef,\%idmap,$randomorder,
 8844:                                                  $randompick,$sequence,\@master_seq,
 8845:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8846:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8847: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8848: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8849: 				 'doublebubble',
 8850: 				 $$scan_record{'scantron.doubleerror'},
 8851:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8852:     	return (1,$currentphase);
 8853:     }
 8854:     return (0,$currentphase+1);
 8855: }
 8856: 
 8857: 
 8858: sub scantron_get_maxbubble {
 8859:     my ($nav_error,$scantron_config) = @_;
 8860:     if (defined($env{'form.scantron_maxbubble'}) &&
 8861: 	$env{'form.scantron_maxbubble'}) {
 8862: 	&restore_bubble_lines();
 8863: 	return $env{'form.scantron_maxbubble'};
 8864:     }
 8865: 
 8866:     my (undef, undef, $sequence) =
 8867: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8868: 
 8869:     my $navmap=Apache::lonnavmaps::navmap->new();
 8870:     unless (ref($navmap)) {
 8871:         if (ref($nav_error)) {
 8872:             $$nav_error = 1;
 8873:         }
 8874:         return;
 8875:     }
 8876:     my $map=$navmap->getResourceByUrl($sequence);
 8877:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8878:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8879: 
 8880:     &Apache::lonxml::clear_problem_counter();
 8881: 
 8882:     my $uname       = $env{'user.name'};
 8883:     my $udom        = $env{'user.domain'};
 8884:     my $cid         = $env{'request.course.id'};
 8885:     my $total_lines = 0;
 8886:     %bubble_lines_per_response = ();
 8887:     %first_bubble_line         = ();
 8888:     %subdivided_bubble_lines   = ();
 8889:     %responsetype_per_response = ();
 8890:     %masterseq_id_responsenum  = ();
 8891: 
 8892:     my $response_number = 0;
 8893:     my $bubble_line     = 0;
 8894:     foreach my $resource (@resources) {
 8895:         my $resid = $resource->id(); 
 8896:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8897:                                                           $udom,undef,$bubbles_per_row);
 8898:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8899: 	    foreach my $part_id (@{$parts}) {
 8900:                 my $lines;
 8901: 
 8902: 	        # TODO - make this a persistent hash not an array.
 8903: 
 8904:                 # optionresponse, matchresponse and rankresponse type items 
 8905:                 # render as separate sub-questions in exam mode.
 8906:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8907:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8908:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8909:                     my ($numbub,$numshown);
 8910:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8911:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8912:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8913:                         }
 8914:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8915:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8916:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8917:                         }
 8918:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8919:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8920:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8921:                         }
 8922:                     }
 8923:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8924:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8925:                     }
 8926:                     my $bubbles_per_row =
 8927:                         &bubblesheet_bubbles_per_row($scantron_config);
 8928:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8929:                     if (($numbub % $bubbles_per_row) != 0) {
 8930:                         $inner_bubble_lines++;
 8931:                     }
 8932:                     for (my $i=0; $i<$numshown; $i++) {
 8933:                         $subdivided_bubble_lines{$response_number} .= 
 8934:                             $inner_bubble_lines.',';
 8935:                     }
 8936:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8937:                     $lines = $numshown * $inner_bubble_lines;
 8938:                 } else {
 8939:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8940:                 }
 8941: 
 8942:                 $first_bubble_line{$response_number} = $bubble_line;
 8943: 	        $bubble_lines_per_response{$response_number} = $lines;
 8944:                 $responsetype_per_response{$response_number} = 
 8945:                     $analysis->{$part_id.'.type'};
 8946:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8947: 	        $response_number++;
 8948: 
 8949: 	        $bubble_line +=  $lines;
 8950: 	        $total_lines +=  $lines;
 8951: 	    }
 8952:         }
 8953:     }
 8954:     &Apache::lonnet::delenv('scantron.');
 8955: 
 8956:     &save_bubble_lines();
 8957:     $env{'form.scantron_maxbubble'} =
 8958: 	$total_lines;
 8959:     return $env{'form.scantron_maxbubble'};
 8960: }
 8961: 
 8962: sub bubblesheet_bubbles_per_row {
 8963:     my ($scantron_config) = @_;
 8964:     my $bubbles_per_row;
 8965:     if (ref($scantron_config) eq 'HASH') {
 8966:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8967:     }
 8968:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8969:         $bubbles_per_row = 10;
 8970:     }
 8971:     return $bubbles_per_row;
 8972: }
 8973: 
 8974: sub scantron_validate_missingbubbles {
 8975:     my ($r,$currentphase) = @_;
 8976:     #get student info
 8977:     my $classlist=&Apache::loncoursedata::get_classlist();
 8978:     my %idmap=&username_to_idmap($classlist);
 8979:     my (undef,undef,$sequence)=
 8980:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8981: 
 8982:     #get scantron line setup
 8983:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8984:     my ($scanlines,$scan_data)=&scantron_getfile();
 8985: 
 8986:     my $navmap = Apache::lonnavmaps::navmap->new();
 8987:     unless (ref($navmap)) {
 8988:         $r->print(&navmap_errormsg());
 8989:         return(1,$currentphase);
 8990:     }
 8991: 
 8992:     my $map=$navmap->getResourceByUrl($sequence);
 8993:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8994:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8995:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8996:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8997: 
 8998:     my $nav_error;
 8999:     if (ref($map)) {
 9000:         $randomorder = $map->randomorder();
 9001:         $randompick = $map->randompick();
 9002:         unless ($randomorder || $randompick) {
 9003:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9004:                 if ($res->randomorder()) {
 9005:                     $randomorder = 1;
 9006:                 }
 9007:                 if ($res->randompick()) {
 9008:                     $randompick = 1;
 9009:                 }
 9010:                 last if ($randomorder || $randompick);
 9011:             }
 9012:         }
 9013:         if ($randomorder || $randompick) {
 9014:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9015:             if ($nav_error) {
 9016:                 $r->print(&navmap_errormsg());
 9017:                 return(1,$currentphase);
 9018:             }
 9019:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9020:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 9021:         }
 9022:     } else {
 9023:         $r->print(&navmap_errormsg());
 9024:         return(1,$currentphase);
 9025:     }
 9026: 
 9027: 
 9028:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 9029:     if ($nav_error) {
 9030:         $r->print(&navmap_errormsg());
 9031:         return(1,$currentphase);
 9032:     }
 9033: 
 9034:     if (!$max_bubble) { $max_bubble=2**31; }
 9035:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 9036: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9037: 	if ($line=~/^[\s\cz]*$/) { next; }
 9038: 	my $scan_record =
 9039:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 9040: 				     $randomorder,$randompick,$sequence,\@master_seq,
 9041:                                      \%symb_to_resource,\%grader_partids_by_symb,
 9042:                                      \%orderedforcode,\%respnumlookup,\%startline);
 9043: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 9044: 	my @to_correct;
 9045: 	
 9046: 	# Probably here's where the error is...
 9047: 
 9048: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 9049:             my $lastbubble;
 9050:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 9051:                my $question = $1;
 9052:                my $subquestion = $2;
 9053:                my ($first,$responsenum);
 9054:                if ($randomorder || $randompick) {
 9055:                    $responsenum = $respnumlookup{$question-1};
 9056:                    $first = $startline{$question-1};
 9057:                } else {
 9058:                    $responsenum = $question-1; 
 9059:                    $first = $first_bubble_line{$responsenum};
 9060:                }
 9061:                if (!defined($first)) { next; }
 9062:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 9063:                my $subcount = 1;
 9064:                while ($subcount<$subquestion) {
 9065:                    $first += $subans[$subcount-1];
 9066:                    $subcount ++;
 9067:                }
 9068:                my $count = $subans[$subquestion-1];
 9069:                $lastbubble = $first + $count;
 9070:             } else {
 9071:                my ($first,$responsenum);
 9072:                if ($randomorder || $randompick) {
 9073:                    $responsenum = $respnumlookup{$missing-1};
 9074:                    $first = $startline{$missing-1};
 9075:                } else {
 9076:                    $responsenum = $missing-1;
 9077:                    $first = $first_bubble_line{$responsenum};
 9078:                }
 9079:                if (!defined($first)) { next; }
 9080:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 9081:             }
 9082:             if ($lastbubble > $max_bubble) { next; }
 9083: 	    push(@to_correct,$missing);
 9084: 	}
 9085: 	if (@to_correct) {
 9086: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 9087: 				     $line,'missingbubble',\@to_correct,
 9088:                                      $randomorder,$randompick,\%respnumlookup,
 9089:                                      \%startline);
 9090: 	    return (1,$currentphase);
 9091: 	}
 9092: 
 9093:     }
 9094:     return (0,$currentphase+1);
 9095: }
 9096: 
 9097: sub hand_bubble_option {
 9098:     my (undef, undef, $sequence) =
 9099:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9100:     return if ($sequence eq '');
 9101:     my $navmap = Apache::lonnavmaps::navmap->new();
 9102:     unless (ref($navmap)) {
 9103:         return;
 9104:     }
 9105:     my $needs_hand_bubbles;
 9106:     my $map=$navmap->getResourceByUrl($sequence);
 9107:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9108:     foreach my $res (@resources) {
 9109:         if (ref($res)) {
 9110:             if ($res->is_problem()) {
 9111:                 my $partlist = $res->parts();
 9112:                 foreach my $part (@{ $partlist }) {
 9113:                     my @types = $res->responseType($part);
 9114:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 9115:                         $needs_hand_bubbles = 1;
 9116:                         last;
 9117:                     }
 9118:                 }
 9119:             }
 9120:         }
 9121:     }
 9122:     if ($needs_hand_bubbles) {
 9123:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9124:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9125:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 9126:                &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 />').
 9127:                '<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;'.
 9128:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 9129:     }
 9130:     return;
 9131: }
 9132: 
 9133: sub scantron_process_students {
 9134:     my ($r,$symb) = @_;
 9135: 
 9136:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 9137:     if (!$symb) {
 9138: 	return '';
 9139:     }
 9140:     my $default_form_data=&defaultFormData($symb);
 9141: 
 9142:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9143:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 9144:     my ($scanlines,$scan_data)=&scantron_getfile();
 9145:     my $classlist=&Apache::loncoursedata::get_classlist();
 9146:     my %idmap=&username_to_idmap($classlist);
 9147:     my $navmap=Apache::lonnavmaps::navmap->new();
 9148:     unless (ref($navmap)) {
 9149:         $r->print(&navmap_errormsg());
 9150:         return '';
 9151:     }
 9152:     my $map=$navmap->getResourceByUrl($sequence);
 9153:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9154:         %grader_randomlists_by_symb,%symb_for_examcode);
 9155:     if (ref($map)) {
 9156:         $randomorder = $map->randomorder();
 9157:         $randompick = $map->randompick();
 9158:         unless ($randomorder || $randompick) {
 9159:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9160:                 if ($res->randomorder()) {
 9161:                     $randomorder = 1;
 9162:                 }
 9163:                 if ($res->randompick()) {
 9164:                     $randompick = 1;
 9165:                 }
 9166:                 last if ($randomorder || $randompick);
 9167:             }
 9168:         }
 9169:     } else {
 9170:         $r->print(&navmap_errormsg());
 9171:         return '';
 9172:     }
 9173:     my $nav_error;
 9174:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9175:     if ($randomorder || $randompick) {
 9176:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
 9177:         if ($nav_error) {
 9178:             $r->print(&navmap_errormsg());
 9179:             return '';
 9180:         }
 9181:     }
 9182:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9183:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9184: 
 9185:     my ($uname,$udom);
 9186:     my $result= <<SCANTRONFORM;
 9187: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9188:   <input type="hidden" name="command" value="scantron_configphase" />
 9189:   $default_form_data
 9190: SCANTRONFORM
 9191:     $r->print($result);
 9192: 
 9193:     my ($checksec,@possibles)=&gradable_sections();
 9194:     my @delayqueue;
 9195:     my (%completedstudents,%scandata);
 9196: 
 9197:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9198:     my $count=&get_todo_count($scanlines,$scan_data);
 9199:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9200:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9201:     $r->print('<br />');
 9202:     my $start=&Time::HiRes::time();
 9203:     my $i=-1;
 9204:     my $started;
 9205: 
 9206:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9207:     if ($nav_error) {
 9208:         $r->print(&navmap_errormsg());
 9209:         return '';
 9210:     }
 9211: 
 9212:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9213:     # the user and return.
 9214: 
 9215:     if ($ssi_error) {
 9216: 	$r->print("</form>");
 9217: 	&ssi_print_error($r);
 9218:         &Apache::lonnet::remove_lock($lock);
 9219: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9220:     }
 9221: 
 9222:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9223:     my $numletts = scalar(keys(%lettdig));
 9224:     my %orderedforcode;
 9225: 
 9226:     while ($i<$scanlines->{'count'}) {
 9227:  	($uname,$udom)=('','');
 9228:  	$i++;
 9229:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9230:  	if ($line=~/^[\s\cz]*$/) { next; }
 9231: 	if ($started) {
 9232: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9233: 	}
 9234: 	$started=1;
 9235:         my %respnumlookup = ();
 9236:         my %startline = ();
 9237:         my $total;
 9238:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9239:                                                  $scan_data,undef,\%idmap,$randomorder,
 9240:                                                  $randompick,$sequence,\@master_seq,
 9241:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9242:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9243:                                                  \$total);
 9244:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9245:  					      \%idmap,$i)) {
 9246:   	    &scantron_add_delay(\@delayqueue,$line,
 9247:  				'Unable to find a student that matches',1);
 9248:  	    next;
 9249:   	}
 9250:  	if (exists $completedstudents{$uname}) {
 9251:  	    &scantron_add_delay(\@delayqueue,$line,
 9252:  				'Student '.$uname.' has multiple sheets',2);
 9253:  	    next;
 9254:  	}
 9255:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9256:         if (($checksec ne '') && ($checksec ne $usec)) {
 9257:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9258:                 &scantron_add_delay(\@delayqueue,$line,
 9259:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9260:                 next;
 9261:             }
 9262:         }
 9263:         my $user = $uname.':'.$usec;
 9264:   	($uname,$udom)=split(/:/,$uname);
 9265: 
 9266:         my $scancode;
 9267:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9268:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9269:             $scancode = $scan_record->{'scantron.CODE'};
 9270:         } else {
 9271:             $scancode = '';
 9272:         }
 9273: 
 9274:         my @mapresources = @resources;
 9275:         if ($randomorder || $randompick) {
 9276:             @mapresources = 
 9277:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9278:                              \%orderedforcode);
 9279:         }
 9280:         my (%partids_by_symb,$res_error);
 9281:         foreach my $resource (@mapresources) {
 9282:             my $ressymb;
 9283:             if (ref($resource)) {
 9284:                 $ressymb = $resource->symb();
 9285:             } else {
 9286:                 $res_error = 1;
 9287:                 last;
 9288:             }
 9289:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9290:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9291:                 my $currcode;
 9292:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9293:                     $currcode = $scancode;
 9294:                 }
 9295:                 my ($analysis,$parts) =
 9296:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9297:                                               $uname,$udom,undef,$bubbles_per_row,
 9298:                                               $currcode);
 9299:                 $partids_by_symb{$ressymb} = $parts;
 9300:             } else {
 9301:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9302:             }
 9303:         }
 9304: 
 9305:         if ($res_error) {
 9306:             &scantron_add_delay(\@delayqueue,$line,
 9307:                                 'An error occurred while grading student '.$uname,2);
 9308:             next;
 9309:         }
 9310: 
 9311: 	&Apache::lonxml::clear_problem_counter();
 9312:   	&Apache::lonnet::appenv($scan_record);
 9313: 
 9314: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9315: 	    &scantron_putfile($scanlines,$scan_data);
 9316: 	}
 9317: 	
 9318:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9319:                                    \@mapresources,\%partids_by_symb,
 9320:                                    $bubbles_per_row,$randomorder,$randompick,
 9321:                                    \%respnumlookup,\%startline) 
 9322:             eq 'ssi_error') {
 9323:             $ssi_error = 0; # So end of handler error message does not trigger.
 9324:             $r->print("</form>");
 9325:             &ssi_print_error($r);
 9326:             &Apache::lonnet::remove_lock($lock);
 9327:             return '';      # Why return ''?  Beats me.
 9328:         }
 9329: 
 9330:         if (($scancode) && ($randomorder || $randompick)) {
 9331:             foreach my $key (keys(%symb_for_examcode)) {
 9332:                 my $symb_in_map = $symb_for_examcode{$key};
 9333:                 if ($symb_in_map ne '') {
 9334:                     my $parmresult =
 9335:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
 9336:                                                                '0_examcode',2,$scancode,
 9337:                                                                'string_examcode',$uname,
 9338:                                                                $udom);
 9339:                 }
 9340:             }
 9341:         }
 9342: 	$completedstudents{$uname}={'line'=>$line};
 9343:         if ($env{'form.verifyrecord'}) {
 9344:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9345:             if ($randompick) {
 9346:                 if ($total) {
 9347:                     $lastpos = $total*$scantron_config{'Qlength'};
 9348:                 }
 9349:             }
 9350: 
 9351:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9352:             chomp($studentdata);
 9353:             $studentdata =~ s/\r$//;
 9354:             my $studentrecord = '';
 9355:             my $counter = -1;
 9356:             foreach my $resource (@mapresources) {
 9357:                 my $ressymb = $resource->symb();
 9358:                 ($counter,my $recording) =
 9359:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9360:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9361:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9362:                                              $randompick,\%respnumlookup,\%startline);
 9363:                 $studentrecord .= $recording;
 9364:             }
 9365:             if ($studentrecord ne $studentdata) {
 9366:                 &Apache::lonxml::clear_problem_counter();
 9367:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9368:                                            \@mapresources,\%partids_by_symb,
 9369:                                            $bubbles_per_row,$randomorder,$randompick,
 9370:                                            \%respnumlookup,\%startline) 
 9371:                     eq 'ssi_error') {
 9372:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9373:                     $r->print("</form>");
 9374:                     &ssi_print_error($r);
 9375:                     &Apache::lonnet::remove_lock($lock);
 9376:                     delete($completedstudents{$uname});
 9377:                     return '';
 9378:                 }
 9379:                 $counter = -1;
 9380:                 $studentrecord = '';
 9381:                 foreach my $resource (@mapresources) {
 9382:                     my $ressymb = $resource->symb();
 9383:                     ($counter,my $recording) =
 9384:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9385:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9386:                                                  \%scantron_config,\%lettdig,$numletts,
 9387:                                                  $randomorder,$randompick,\%respnumlookup,
 9388:                                                  \%startline);
 9389:                     $studentrecord .= $recording;
 9390:                 }
 9391:                 if ($studentrecord ne $studentdata) {
 9392:                     $r->print('<p><span class="LC_warning">');
 9393:                     if ($scancode eq '') {
 9394:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9395:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9396:                     } else {
 9397:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9398:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9399:                     }
 9400:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9401:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9402:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9403:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9404:                               &Apache::loncommon::start_data_table_row().
 9405:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9406:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9407:                               &Apache::loncommon::end_data_table_row().
 9408:                               &Apache::loncommon::start_data_table_row().
 9409:                               '<td>'.&mt('Stored submissions').'</td>'.
 9410:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9411:                               &Apache::loncommon::end_data_table_row().
 9412:                               &Apache::loncommon::end_data_table().'</p>');
 9413:                 } else {
 9414:                     $r->print('<br /><span class="LC_warning">'.
 9415:                              &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 />'.
 9416:                              &mt("As a consequence, this user's submission history records two tries.").
 9417:                                  '</span><br />');
 9418:                 }
 9419:             }
 9420:         }
 9421:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9422:     } continue {
 9423: 	&Apache::lonxml::clear_problem_counter();
 9424: 	&Apache::lonnet::delenv('scantron.');
 9425:     }
 9426:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9427:     &Apache::lonnet::remove_lock($lock);
 9428: #    my $lasttime = &Time::HiRes::time()-$start;
 9429: #    $r->print("<p>took $lasttime</p>");
 9430: 
 9431:     $r->print("</form>");
 9432:     return '';
 9433: }
 9434: 
 9435: sub graders_resources_pass {
 9436:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9437:         $bubbles_per_row) = @_;
 9438:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9439:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9440:         foreach my $resource (@{$resources}) {
 9441:             my $ressymb = $resource->symb();
 9442:             my ($analysis,$parts) =
 9443:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9444:                                           $env{'user.name'},$env{'user.domain'},
 9445:                                           1,$bubbles_per_row);
 9446:             $grader_partids_by_symb->{$ressymb} = $parts;
 9447:             if (ref($analysis) eq 'HASH') {
 9448:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9449:                     $grader_randomlists_by_symb->{$ressymb} =
 9450:                         $analysis->{'parts_withrandomlist'};
 9451:                 }
 9452:             }
 9453:         }
 9454:     }
 9455:     return;
 9456: }
 9457: 
 9458: =pod
 9459: 
 9460: =item users_order
 9461: 
 9462:   Returns array of resources in current map, ordered based on either CODE,
 9463:   if this is a CODEd exam, or based on student's identity if this is a 
 9464:   "NAMEd" exam.
 9465: 
 9466:   Should be used when randomorder and/or randompick applied when the 
 9467:   corresponding exam was printed, prior to students completing bubblesheets 
 9468:   for the version of the exam the student received.
 9469: 
 9470: =cut
 9471: 
 9472: sub users_order  {
 9473:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9474:     my @mapresources;
 9475:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9476:         return @mapresources;
 9477:     }
 9478:     if ($scancode) {
 9479:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9480:             @mapresources = @{$orderedforcode->{$scancode}};
 9481:         } else {
 9482:             $env{'form.CODE'} = $scancode;
 9483:             my $actual_seq =
 9484:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9485:                                                                $master_seq,
 9486:                                                                $user,$scancode,1);
 9487:             if (ref($actual_seq) eq 'ARRAY') {
 9488:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9489:                 if (ref($orderedforcode) eq 'HASH') {
 9490:                     if (@mapresources > 0) { 
 9491:                         $orderedforcode->{$scancode} = \@mapresources;
 9492:                     }
 9493:                 }
 9494:             }
 9495:             delete($env{'form.CODE'});
 9496:         }
 9497:     } else {
 9498:         my $actual_seq =
 9499:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9500:                                                            $master_seq,
 9501:                                                            $user,undef,1);
 9502:         if (ref($actual_seq) eq 'ARRAY') {
 9503:             @mapresources = 
 9504:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9505:         }
 9506:     }
 9507:     return @mapresources;
 9508: }
 9509: 
 9510: sub grade_student_bubbles {
 9511:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9512:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9513:     my $uselookup = 0;
 9514:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9515:         (ref($startline) eq 'HASH')) {
 9516:         $uselookup = 1;
 9517:     }
 9518: 
 9519:     if (ref($resources) eq 'ARRAY') {
 9520:         my $count = 0;
 9521:         foreach my $resource (@{$resources}) {
 9522:             my $ressymb = $resource->symb();
 9523:             my %form = ('submitted'      => 'scantron',
 9524:                         'grade_target'   => 'grade',
 9525:                         'grade_username' => $uname,
 9526:                         'grade_domain'   => $udom,
 9527:                         'grade_courseid' => $env{'request.course.id'},
 9528:                         'grade_symb'     => $ressymb,
 9529:                         'CODE'           => $scancode
 9530:                        );
 9531:             if ($bubbles_per_row ne '') {
 9532:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9533:             }
 9534:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9535:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9536:             }
 9537:             if (ref($parts) eq 'HASH') {
 9538:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9539:                     foreach my $part (@{$parts->{$ressymb}}) {
 9540:                         if ($uselookup) {
 9541:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9542:                         } else {
 9543:                             $form{'scantron_questnum_start.'.$part} =
 9544:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9545:                         }
 9546:                         $count++;
 9547:                     }
 9548:                 }
 9549:             }
 9550:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9551:             return 'ssi_error' if ($ssi_error);
 9552:             last if (&Apache::loncommon::connection_aborted($r));
 9553:         }
 9554:     }
 9555:     return;
 9556: }
 9557: 
 9558: sub scantron_upload_scantron_data {
 9559:     my ($r,$symb) = @_;
 9560:     my $dom = $env{'request.role.domain'};
 9561:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9562:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9563:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9564:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9565: 							  'domainid',
 9566: 							  'coursename',$dom);
 9567:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9568:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9569:     my $default_form_data=&defaultFormData($symb);
 9570:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9571:     &js_escape(\$nofile_alert);
 9572:     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.");
 9573:     &js_escape(\$nocourseid_alert);
 9574:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9575:     function checkUpload(formname) {
 9576: 	if (formname.upfile.value == "") {
 9577: 	    alert("'.$nofile_alert.'");
 9578: 	    return false;
 9579: 	}
 9580:         if (formname.courseid.value == "") {
 9581:             alert("'.$nocourseid_alert.'");
 9582:             return false;
 9583:         }
 9584: 	formname.submit();
 9585:     }
 9586: 
 9587:     function ToSyllabus() {
 9588:         var cdom = '."'$dom'".';
 9589:         var cnum = document.rules.courseid.value;
 9590:         if (cdom == "" || cdom == null) {
 9591:             return;
 9592:         }
 9593:         if (cnum == "" || cnum == null) {
 9594:            return;
 9595:         }
 9596:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9597:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9598:         return;
 9599:     }
 9600: 
 9601:     '.$formatjs.'
 9602: '));
 9603:     $r->print('
 9604: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9605: 
 9606: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9607: '.$default_form_data.
 9608:   &Apache::lonhtmlcommon::start_pick_box().
 9609:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9610:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9611:   &Apache::lonhtmlcommon::row_closure().
 9612:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9613:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9614:   &Apache::lonhtmlcommon::row_closure().
 9615:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9616:   '<input name="domainid" type="hidden" />'.$domdesc.
 9617:   &Apache::lonhtmlcommon::row_closure());
 9618:     if ($formatoptions) {
 9619:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9620:                   &Apache::lonhtmlcommon::row_closure());
 9621:     }
 9622:     $r->print(
 9623:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9624:   '<input type="file" name="upfile" size="50" />'.
 9625:   &Apache::lonhtmlcommon::row_closure(1).
 9626:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9627: 
 9628: <input name="command" value="scantronupload_save" type="hidden" />
 9629: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9630: </form>
 9631: ');
 9632:     return '';
 9633: }
 9634: 
 9635: sub scantron_upload_dataformat {
 9636:     my ($dom) = @_;
 9637:     my ($formatoptions,$formattitle,$formatjs);
 9638:     $formatjs = <<'END';
 9639: function toggleScantab(form) {
 9640:    return;
 9641: }
 9642: END
 9643:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9644:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9645:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9646:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9647:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9648:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9649:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9650:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9651:                             my ($onclick,$formatextra,$singleline);
 9652:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9653:                             my $count = 0;
 9654:                             foreach my $line (@lines) {
 9655:                                 next if (($line =~ /^\#/) || ($line eq ''));
 9656:                                 $singleline = $line;
 9657:                                 $count ++;
 9658:                             }
 9659:                             if ($count > 1) {
 9660:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9661:                                                '<span class="LC_nobreak">'.
 9662:                                                &mt('Bubblesheet type').':&nbsp;'.
 9663:                                                &scantron_scantab().'</span></div>';
 9664:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9665:                                 $formatjs = <<"END";
 9666: function toggleScantab(form) {
 9667:     var divid = 'bubbletype';
 9668:     if (document.getElementById(divid)) {
 9669:         var radioname = 'fileformat';
 9670:         var num = form.elements[radioname].length;
 9671:         if (num) {
 9672:             for (var i=0; i<num; i++) {
 9673:                 if (form.elements[radioname][i].checked) {
 9674:                     var chosen = form.elements[radioname][i].value;
 9675:                     if (chosen == 'dat') {
 9676:                         document.getElementById(divid).style.display = 'none';
 9677:                     } else if (chosen == 'csv') {
 9678:                         document.getElementById(divid).style.display = 'block';
 9679:                     }
 9680:                 }
 9681:             }
 9682:         }
 9683:     }
 9684:     return;
 9685: }
 9686: 
 9687: END
 9688:                             } elsif ($count == 1) {
 9689:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9690:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9691:                             }
 9692:                             $formattitle = &mt('File format');
 9693:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9694:                                              &mt('Plain Text (no delimiters)').
 9695:                                              '</label>'.('&nbsp;'x2).
 9696:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9697:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9698:                         }
 9699:                     }
 9700:                 }
 9701:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9702:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9703:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9704:                         $formattitle = &mt('Bubblesheet type');
 9705:                         $formatoptions = &scantron_scantab();
 9706:                     }
 9707:                 }
 9708:             }
 9709:         }
 9710:     }
 9711:     return ($formatoptions,$formattitle,$formatjs);
 9712: }
 9713: 
 9714: sub scantron_upload_scantron_data_save {
 9715:     my ($r,$symb) = @_;
 9716:     my $doanotherupload=
 9717: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9718: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9719: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9720: 	'</form>'."\n";
 9721:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9722: 	!&Apache::lonnet::allowed('usc',
 9723: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9724:         !&Apache::lonnet::allowed('usc',
 9725:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9726: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9727: 	unless ($symb) {
 9728: 	    $r->print($doanotherupload);
 9729: 	}
 9730: 	return '';
 9731:     }
 9732:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9733:     my $uploadedfile;
 9734:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9735:     if (length($env{'form.upfile'}) < 2) {
 9736:         $r->print(
 9737:             &Apache::lonhtmlcommon::confirm_success(
 9738:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9739:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9740:     } else {
 9741:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9742:         my $parser;
 9743:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9744:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9745:                 my $is_csv;
 9746:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9747:                 if (@possibles > 1) {
 9748:                     if ($env{'form.fileformat'} eq 'csv') {
 9749:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9750:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9751:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9752:                                     $is_csv = 1;
 9753:                                 }
 9754:                             }
 9755:                         }
 9756:                     }
 9757:                 } elsif (@possibles == 1) {
 9758:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9759:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9760:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9761:                                 $is_csv = 1;
 9762:                             }
 9763:                         }
 9764:                     }
 9765:                 }
 9766:                 if ($is_csv) {
 9767:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9768:                 }
 9769:             }
 9770:         }
 9771:         my $result =
 9772:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9773:                                             $env{'form.courseid'},$env{'form.domainid'});
 9774:         if ($result =~ m{^/uploaded/}) {
 9775:             $r->print(
 9776:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9777:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9778:                         (length($env{'form.upfile'})-1),
 9779:                         '<span class="LC_filename">'.$result.'</span>'));
 9780:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9781:             if ($uploadedfile =~ /^scantron_orig_/) {
 9782:                 my $logname = $uploadedfile;
 9783:                 $logname =~ s/^scantron_orig_//;
 9784:                 if ($logname ne '') {
 9785:                     my $now = time;
 9786:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9787:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9788:                 }
 9789:             }
 9790:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9791:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9792:         } else {
 9793:             $r->print(
 9794:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9795:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9796:                           $result,
 9797: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9798: 	}
 9799:     }
 9800:     if ($symb) {
 9801: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9802:     } else {
 9803: 	$r->print($doanotherupload);
 9804:     }
 9805:     return '';
 9806: }
 9807: 
 9808: sub validate_uploaded_scantron_file {
 9809:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9810: 
 9811:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9812:     my @lines;
 9813:     if ($scanlines ne '-1') {
 9814:         @lines=split("\n",$scanlines,-1);
 9815:     }
 9816:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9817:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9818:     if ($context eq 'download') {
 9819:         $priv = 'mgr';
 9820:     } else {
 9821:         $priv = 'usc';
 9822:     }
 9823:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9824:             (($env{'request.course.id'}) &&
 9825:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9826:         if ($env{'request.course.sec'} ne '') {
 9827:             unless (&Apache::lonnet::allowed($priv,
 9828:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9829:                 unless ($context eq 'download') {
 9830:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9831:                 }
 9832:                 return $output;
 9833:             }
 9834:             ($checksec,@possibles)=&gradable_sections();
 9835:         }
 9836:     }
 9837:     if (@lines) {
 9838:         my (%counts,$max_match_format);
 9839:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9840:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9841:         my %idmap = &username_to_idmap($classlist);
 9842:         foreach my $key (keys(%idmap)) {
 9843:             my $lckey = lc($key);
 9844:             $idmap{$lckey} = $idmap{$key};
 9845:         }
 9846:         my %unique_formats;
 9847:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9848:         foreach my $line (@formatlines) {
 9849:             next if (($line =~ /^\#/) || ($line eq ''));
 9850:             my @config = split(/:/,$line);
 9851:             my $idstart = $config[5];
 9852:             my $idlength = $config[6];
 9853:             if (($idstart ne '') && ($idlength > 0)) {
 9854:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9855:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9856:                 } else {
 9857:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9858:                 }
 9859:             }
 9860:         }
 9861:         foreach my $key (keys(%unique_formats)) {
 9862:             my ($idstart,$idlength) = split(':',$key);
 9863:             %{$counts{$key}} = (
 9864:                                'found'   => 0,
 9865:                                'total'   => 0,
 9866:                                'totalanysec' => 0,
 9867:                                'othersec' => 0,
 9868:                               );
 9869:             foreach my $line (@lines) {
 9870:                 next if ($line =~ /^#/);
 9871:                 next if ($line =~ /^[\s\cz]*$/);
 9872:                 my $id = substr($line,$idstart-1,$idlength);
 9873:                 $id = lc($id);
 9874:                 if (exists($idmap{$id})) {
 9875:                     if ($checksec ne '') {
 9876:                         $counts{$key}{'totalanysec'} ++;
 9877:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9878:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9879:                             if ($stusec ne $checksec) {
 9880:                                 if (@possibles) {
 9881:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9882:                                         $counts{$key}{'othersec'} ++;
 9883:                                         next;
 9884:                                     }
 9885:                                 } else {
 9886:                                     $counts{$key}{'othersec'} ++;
 9887:                                     next;
 9888:                                 }
 9889:                             }
 9890:                         }
 9891:                     }
 9892:                     $counts{$key}{'found'} ++;
 9893:                 }
 9894:                 $counts{$key}{'total'} ++;
 9895:             }
 9896:             if ($counts{$key}{'total'}) {
 9897:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9898:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9899:                     $max_match_pct = $percent_match;
 9900:                     $max_match_format = $key;
 9901:                     $found_match_count = $counts{$key}{'found'};
 9902:                     $max_match_count = $counts{$key}{'total'};
 9903:                 }
 9904:             }
 9905:         }
 9906:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9907:             my $format_descs;
 9908:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9909:             for (my $i=0; $i<$numwithformat; $i++) {
 9910:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9911:                 if ($i<$numwithformat-2) {
 9912:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9913:                 } elsif ($i==$numwithformat-2) {
 9914:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9915:                 } elsif ($i==$numwithformat-1) {
 9916:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9917:                 }
 9918:             }
 9919:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9920:             $output .= '<br />';
 9921:             if ($found_match_count == $max_match_count) {
 9922:                 # 100% matching entries
 9923:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9924:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9925:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9926:                 &mt('Comparison of student IDs in the uploaded file with'.
 9927:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9928:                     ' in the file (for the format defined for [_3]).',
 9929:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9930:             } else {
 9931:                 # Not all entries matching? -> Show warning and additional info
 9932:                 $output .=
 9933:                     &Apache::lonhtmlcommon::confirm_success(
 9934:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9935:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9936:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9937:                     &mt('Comparison of student IDs in the uploaded file with'.
 9938:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9939:                         ' in the file (for the format defined for [_3]).',
 9940:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9941:                     '<p class="LC_info">'.
 9942:                     &mt('A low percentage of matches results from one of the following:').
 9943:                     '</p><ul>'.
 9944:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9945:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9946:                                '<i>'.$cdom.'</i>').'</li>'.
 9947:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9948:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9949:                     '</ul>';
 9950:             }
 9951:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9952:                 if ($counts{$max_match_format}{'othersec'}) {
 9953:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9954:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9955:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9956:                     &js_escape(\$confirmdel);
 9957:                     $output .= '<p class="LC_warning">'.
 9958:                                &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',
 9959:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9960:                                '<br />'.
 9961:                                &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>').
 9962:                                '</p><p>'.
 9963:                                &mt('If you prefer to delete the file now, use: [_1]').
 9964:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9965:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9966:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9967:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9968:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9969:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9970:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9971:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9972:                                '</form></p>';
 9973:                 }
 9974:             }
 9975:         }
 9976:         if (($context eq 'download') && ($checksec ne '')) {
 9977:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9978:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9979:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9980:             }
 9981:         } 
 9982:     } elsif ($context ne 'download') {
 9983:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9984:     }
 9985:     return $output;
 9986: }
 9987: 
 9988: sub gradable_sections {
 9989:     my $checksec = $env{'request.course.sec'};
 9990:     my @oksecs;
 9991:     if ($checksec) {
 9992:         my %availablesecs = &sections_grade_privs();
 9993:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9994:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9995:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9996:                     push(@oksecs,$sec);
 9997:                 }
 9998:             }
 9999:             if (grep(/^all$/,@oksecs)) {
10000:                 undef($checksec);
10001:             }
10002:         }
10003:     }
10004:     return($checksec,@oksecs);
10005: }
10006: 
10007: sub sections_grade_privs {
10008:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10009:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10010:     my %availablesecs = (
10011:                           mgr => [],
10012:                           vgr => [],
10013:                           usc => [],
10014:                         );
10015:     my $ccrole = 'cc';
10016:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
10017:         $ccrole = 'co';
10018:     }
10019:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
10020:                                                      'userroles',['active'],
10021:                                                      [$ccrole,'in','cr'],$cdom,1);
10022:     my $crsid = $cnum.':'.$cdom;
10023:     foreach my $item (keys(%crsroleshash)) {
10024:         next unless ($item =~ /^$crsid\:/);
10025:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
10026:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
10027:         if ($sec ne '') {
10028:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
10029:         }
10030:         if (($role eq $ccrole) || ($role eq 'in')) {
10031:             foreach my $priv ('mgr','vgr','usc') { 
10032:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
10033:                     if ($sec eq '') {
10034:                         $availablesecs{$priv} = ['all'];
10035:                     } elsif ($sec ne $env{'request.course.sec'}) {
10036:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
10037:                             push(@{$availablesecs{$priv}},$sec);
10038:                         }
10039:                     }
10040:                 }
10041:             }
10042:         } elsif ($role =~ m{^cr/}) {
10043:             foreach my $priv ('mgr','vgr','usc') {
10044:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
10045:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
10046:                         if ($sec eq '') {
10047:                             $availablesecs{$priv} = ['all'];
10048:                         } elsif ($sec ne $env{'request.course.sec'}) {
10049:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
10050:                                 push(@{$availablesecs{$priv}},$sec);
10051:                             }
10052:                         }
10053:                     }
10054:                 }
10055:             }
10056:         }
10057:     }
10058:     return %availablesecs;
10059: }
10060: 
10061: sub scantron_upload_delete {
10062:     my ($r,$symb) = @_;
10063:     my $filename = $env{'form.uploadedfile'};
10064:     if ($filename =~ /^scantron_orig_/) {
10065:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
10066:             &Apache::lonnet::allowed('usc',
10067:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
10068:             &Apache::lonnet::allowed('usc',
10069:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
10070:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
10071:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
10072:             if ($retrieval eq '-1') {
10073:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10074:                           &mt('File requested for deletion not found.'));
10075:             } else {
10076:                 $filename =~ s/^scantron_orig_//;
10077:                 if ($filename ne '') {
10078:                     my ($is_valid,$numleft);
10079:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
10080:                     if (keys(%info)) {
10081:                         if (ref($info{$filename}) eq 'HASH') {
10082:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
10083:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10084:                                     $is_valid = 1;
10085:                                     delete($info{$filename}{$timestamp}); 
10086:                                 }
10087:                             }
10088:                             $numleft = scalar(keys(%{$info{$filename}}));
10089:                         }
10090:                     }
10091:                     if ($is_valid) {
10092:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
10093:                         if ($result eq 'ok') {
10094:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
10095:                             if ($numleft) {
10096:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
10097:                             } else {
10098:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
10099:                             }
10100:                         } else {
10101:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10102:                                       &mt('Result was [_1]',$result));
10103:                         }
10104:                     } else {
10105:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10106:                                   &mt('File requested for deletion was uploaded by a different user.'));
10107:                     }
10108:                 } else {
10109:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10110:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10111:                 }
10112:             }
10113:         } else {
10114:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
10115:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
10116:         }
10117:     } else {
10118:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10119:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10120:     }
10121:     return;
10122: }
10123: 
10124: sub valid_file {
10125:     my ($requested_file)=@_;
10126:     foreach my $filename (sort(&scantron_filenames())) {
10127: 	if ($requested_file eq $filename) { return 1; }
10128:     }
10129:     return 0;
10130: }
10131: 
10132: sub scantron_download_scantron_data {
10133:     my ($r,$symb) = @_;
10134:     my $default_form_data=&defaultFormData($symb);
10135:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10136:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10137:     my $file=$env{'form.scantron_selectfile'};
10138:     if (! &valid_file($file)) {
10139: 	$r->print('
10140: 	<p>
10141: 	    '.&mt('The requested filename was invalid.').'
10142:         </p>
10143: ');
10144: 	return;
10145:     }
10146:     my (%uploader,$is_owner,%counts,$percent);
10147:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
10148:     if (ref($uploader{$file}) eq 'HASH') {
10149:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
10150:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10151:                 $is_owner = 1;
10152:                 last;
10153:             }
10154:         }
10155:     }
10156:     unless ($is_owner) {
10157:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
10158:         if ($counts{'totalanysec'}) {
10159:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
10160:             if ($percent_othersec >= 10) {
10161:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
10162:                 $r->print('<p class="LC_warning">'.
10163:                           &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).
10164:                           '</p>');
10165:                 return;
10166:             }
10167:         }
10168:     }
10169:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
10170:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
10171:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
10172:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
10173:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
10174:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
10175:     $r->print('
10176:     <p>
10177: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
10178: 	      '<a href="'.$orig.'">','</a>').'
10179:     </p>
10180:     <p>
10181: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
10182: 	      '<a href="'.$corrected.'">','</a>').'
10183:     </p>
10184:     <p>
10185: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
10186: 	      '<a href="'.$skipped.'">','</a>').'
10187:     </p>
10188: ');
10189:     return '';
10190: }
10191: 
10192: sub checkscantron_results {
10193:     my ($r,$symb) = @_;
10194:     if (!$symb) {return '';}
10195:     my $cid = $env{'request.course.id'};
10196:     my %lettdig = &Apache::lonnet::letter_to_digits();
10197:     my $numletts = scalar(keys(%lettdig));
10198:     my $cnum = $env{'course.'.$cid.'.num'};
10199:     my $cdom = $env{'course.'.$cid.'.domain'};
10200:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10201:     my %record;
10202:     my %scantron_config =
10203:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10204:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10205:     my ($scanlines,$scan_data)=&scantron_getfile();
10206:     my $classlist=&Apache::loncoursedata::get_classlist();
10207:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10208:     my $navmap=Apache::lonnavmaps::navmap->new();
10209:     unless (ref($navmap)) {
10210:         $r->print(&navmap_errormsg());
10211:         return '';
10212:     }
10213:     my $map=$navmap->getResourceByUrl($sequence);
10214:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10215:         %grader_randomlists_by_symb,%orderedforcode);
10216:     if (ref($map)) { 
10217:         $randomorder=$map->randomorder();
10218:         $randompick=$map->randompick();
10219:         unless ($randomorder || $randompick) {
10220:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
10221:                 if ($res->randomorder()) {
10222:                     $randomorder = 1;
10223:                 }
10224:                 if ($res->randompick()) {
10225:                     $randompick = 1;
10226:                 }
10227:                 last if ($randomorder || $randompick);
10228:             }
10229:         }
10230:     }
10231:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10232:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10233:     if ($nav_error) {
10234:         $r->print(&navmap_errormsg());
10235:         return '';
10236:     }
10237:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10238:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10239:     my ($uname,$udom);
10240:     my (%scandata,%lastname,%bylast);
10241:     $r->print('
10242: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10243: 
10244:     my @delayqueue;
10245:     my %completedstudents;
10246: 
10247:     my $count=&get_todo_count($scanlines,$scan_data);
10248:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10249:     my ($username,$domain,$started);
10250:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10251:     if ($nav_error) {
10252:         $r->print(&navmap_errormsg());
10253:         return '';
10254:     }
10255: 
10256:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10257:     my $start=&Time::HiRes::time();
10258:     my $i=-1;
10259: 
10260:     while ($i<$scanlines->{'count'}) {
10261:         ($username,$domain,$uname)=('','','');
10262:         $i++;
10263:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10264:         if ($line=~/^[\s\cz]*$/) { next; }
10265:         if ($started) {
10266:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10267:         }
10268:         $started=1;
10269:         my $scan_record=
10270:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10271:                                                      $scan_data);
10272:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10273:                                               \%idmap,$i)) {
10274:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10275:                                 'Unable to find a student that matches',1);
10276:             next;
10277:         }
10278:         if (exists $completedstudents{$uname}) {
10279:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10280:                                 'Student '.$uname.' has multiple sheets',2);
10281:             next;
10282:         }
10283:         my $pid = $scan_record->{'scantron.ID'};
10284:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10285:         push(@{$bylast{$lastname{$pid}}},$pid);
10286:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10287:         my $user = $uname.':'.$usec;
10288:         ($username,$domain)=split(/:/,$uname);
10289: 
10290:         my $scancode;
10291:         if ((exists($scan_record->{'scantron.CODE'})) &&
10292:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10293:             $scancode = $scan_record->{'scantron.CODE'};
10294:         } else {
10295:             $scancode = '';
10296:         }
10297: 
10298:         my @mapresources = @resources;
10299:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10300:         my %respnumlookup=();
10301:         my %startline=();
10302:         if ($randomorder || $randompick) {
10303:             @mapresources =
10304:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10305:                              \%orderedforcode);
10306:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10307:                                              $scan_record,\@master_seq,\%symb_to_resource,
10308:                                              \%grader_partids_by_symb,\%orderedforcode,
10309:                                              \%respnumlookup,\%startline);
10310:             if ($randompick && $total) {
10311:                 $lastpos = $total*$scantron_config{'Qlength'};
10312:             }
10313:         }
10314:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10315:         chomp($scandata{$pid});
10316:         $scandata{$pid} =~ s/\r$//;
10317: 
10318:         my $counter = -1;
10319:         foreach my $resource (@mapresources) {
10320:             my $parts;
10321:             my $ressymb = $resource->symb();
10322:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10323:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10324:                 my $currcode;
10325:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10326:                     $currcode = $scancode;
10327:                 }
10328:                 (my $analysis,$parts) =
10329:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10330:                                               $username,$domain,undef,
10331:                                               $bubbles_per_row,$currcode);
10332:             } else {
10333:                 $parts = $grader_partids_by_symb{$ressymb};
10334:             }
10335:             ($counter,my $recording) =
10336:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10337:                                          $scandata{$pid},$parts,
10338:                                          \%scantron_config,\%lettdig,$numletts,
10339:                                          $randomorder,$randompick,
10340:                                          \%respnumlookup,\%startline);
10341:             $record{$pid} .= $recording;
10342:         }
10343:     }
10344:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10345:     $r->print('<br />');
10346:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10347:     $passed = 0;
10348:     $failed = 0;
10349:     $numstudents = 0;
10350:     foreach my $last (sort(keys(%bylast))) {
10351:         if (ref($bylast{$last}) eq 'ARRAY') {
10352:             foreach my $pid (sort(@{$bylast{$last}})) {
10353:                 my $showscandata = $scandata{$pid};
10354:                 my $showrecord = $record{$pid};
10355:                 $showscandata =~ s/\s/&nbsp;/g;
10356:                 $showrecord =~ s/\s/&nbsp;/g;
10357:                 if ($scandata{$pid} eq $record{$pid}) {
10358:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10359:                     $okstudents .= '<tr class="'.$css_class.'">'.
10360: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10361: '</tr>'."\n".
10362: '<tr class="'.$css_class.'">'."\n".
10363: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10364:                     $passed ++;
10365:                 } else {
10366:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10367:                     $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".
10368: '</tr>'."\n".
10369: '<tr class="'.$css_class.'">'."\n".
10370: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10371: '</tr>'."\n";
10372:                     $failed ++;
10373:                 }
10374:                 $numstudents ++;
10375:             }
10376:         }
10377:     }
10378:     $r->print(
10379:         '<p>'
10380:        .&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).',
10381:             '<b>',
10382:             $numstudents,
10383:             '</b>',
10384:             $env{'form.scantron_maxbubble'})
10385:        .'</p>'
10386:     );
10387:     $r->print('<p>'
10388:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10389:              .'<br />'
10390:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10391:              .'</p>'
10392:     );
10393:     if ($passed) {
10394:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10395:         $r->print(&Apache::loncommon::start_data_table()."\n".
10396:                  &Apache::loncommon::start_data_table_header_row()."\n".
10397:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10398:                  &Apache::loncommon::end_data_table_header_row()."\n".
10399:                  $okstudents."\n".
10400:                  &Apache::loncommon::end_data_table().'<br />');
10401:     }
10402:     if ($failed) {
10403:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10404:         $r->print(&Apache::loncommon::start_data_table()."\n".
10405:                  &Apache::loncommon::start_data_table_header_row()."\n".
10406:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10407:                  &Apache::loncommon::end_data_table_header_row()."\n".
10408:                  $badstudents."\n".
10409:                  &Apache::loncommon::end_data_table()).'<br />'.
10410:                  &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.');  
10411:     }
10412:     $r->print('</form><br />');
10413:     return;
10414: }
10415: 
10416: sub verify_scantron_grading {
10417:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10418:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10419:         $respnumlookup,$startline) = @_;
10420:     my ($record,%expected,%startpos);
10421:     return ($counter,$record) if (!ref($resource));
10422:     return ($counter,$record) if (!$resource->is_problem());
10423:     my $symb = $resource->symb();
10424:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10425:     foreach my $part_id (@{$partids}) {
10426:         $counter ++;
10427:         $expected{$part_id} = 0;
10428:         my $respnum = $counter;
10429:         if ($randomorder || $randompick) {
10430:             $respnum = $respnumlookup->{$counter};
10431:             $startpos{$part_id} = $startline->{$counter} + 1;
10432:         } else {
10433:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10434:         }
10435:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10436:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10437:             foreach my $item (@sub_lines) {
10438:                 $expected{$part_id} += $item;
10439:             }
10440:         } else {
10441:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10442:         }
10443:     }
10444:     if ($symb) {
10445:         my %recorded;
10446:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10447:         if ($returnhash{'version'}) {
10448:             my %lasthash=();
10449:             my $version;
10450:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10451:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10452:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10453:                 }
10454:             }
10455:             foreach my $key (keys(%lasthash)) {
10456:                 if ($key =~ /\.scantron$/) {
10457:                     my $value = &unescape($lasthash{$key});
10458:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10459:                     if ($value eq '') {
10460:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10461:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10462:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10463:                             }
10464:                         }
10465:                     } else {
10466:                         my @tocheck;
10467:                         my @items = split(//,$value);
10468:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10469:                             ($scantron_config->{'Qon'} eq 'number')) {
10470:                             if (@items < $expected{$part_id}) {
10471:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10472:                                 my @singles = split(//,$fragment);
10473:                                 foreach my $pos (@singles) {
10474:                                     if ($pos eq ' ') {
10475:                                         push(@tocheck,$pos);
10476:                                     } else {
10477:                                         my $next = shift(@items);
10478:                                         push(@tocheck,$next);
10479:                                     }
10480:                                 }
10481:                             } else {
10482:                                 @tocheck = @items;
10483:                             }
10484:                             foreach my $letter (@tocheck) {
10485:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10486:                                     if ($letter !~ /^[A-J]$/) {
10487:                                         $letter = $scantron_config->{'Qoff'};
10488:                                     }
10489:                                     $recorded{$part_id} .= $letter;
10490:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10491:                                     my $digit;
10492:                                     if ($letter !~ /^[A-J]$/) {
10493:                                         $digit = $scantron_config->{'Qoff'};
10494:                                     } else {
10495:                                         $digit = $lettdig->{$letter};
10496:                                     }
10497:                                     $recorded{$part_id} .= $digit;
10498:                                 }
10499:                             }
10500:                         } else {
10501:                             @tocheck = @items;
10502:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10503:                                 my $curr_sub = shift(@tocheck);
10504:                                 my $digit;
10505:                                 if ($curr_sub =~ /^[A-J]$/) {
10506:                                     $digit = $lettdig->{$curr_sub}-1;
10507:                                 }
10508:                                 if ($curr_sub eq 'J') {
10509:                                     $digit += scalar($numletts);
10510:                                 }
10511:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10512:                                     if ($j == $digit) {
10513:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10514:                                     } else {
10515:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10516:                                     }
10517:                                 }
10518:                             }
10519:                         }
10520:                     }
10521:                 }
10522:             }
10523:         }
10524:         foreach my $part_id (@{$partids}) {
10525:             if ($recorded{$part_id} eq '') {
10526:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10527:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10528:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10529:                     }
10530:                 }
10531:             }
10532:             $record .= $recorded{$part_id};
10533:         }
10534:     }
10535:     return ($counter,$record);
10536: }
10537: 
10538: #-------- end of section for handling grading scantron forms -------
10539: #
10540: #-------------------------------------------------------------------
10541: 
10542: #-------------------------- Menu interface -------------------------
10543: #
10544: #--- Href with symb and command ---
10545: 
10546: sub href_symb_cmd {
10547:     my ($symb,$cmd)=@_;
10548:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10549: }
10550: 
10551: sub grading_menu {
10552:     my ($request,$symb) = @_;
10553:     if (!$symb) {return '';}
10554: 
10555:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10556:                   'command'=>'individual');
10557:     
10558:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10559: 
10560:     $fields{'command'}='ungraded';
10561:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10562: 
10563:     $fields{'command'}='table';
10564:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10565: 
10566:     $fields{'command'}='all_for_one';
10567:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10568: 
10569:     $fields{'command'}='downloadfilesselect';
10570:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10571: 
10572:     $fields{'command'} = 'csvform';
10573:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10574:     
10575:     $fields{'command'} = 'processclicker';
10576:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10577:     
10578:     $fields{'command'} = 'scantron_selectphase';
10579:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10580: 
10581:     $fields{'command'} = 'initialverifyreceipt';
10582:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10583: 
10584:     my %permissions;
10585:     if ($perm{'mgr'}) {
10586:         $permissions{'either'} = 'F';
10587:         $permissions{'mgr'} = 'F';
10588:     }
10589:     if ($perm{'vgr'}) {
10590:         $permissions{'either'} = 'F';
10591:         $permissions{'vgr'} = 'F';
10592:     }
10593: 
10594:     my @menu = ({	categorytitle=>'Hand Grading',
10595:             items =>[
10596:                         {	linktext => 'Select individual students to grade',
10597:                     		url => $url1a,
10598:                     		permission => $permissions{'either'},
10599:                     		icon => 'grade_students.png',
10600:                     		linktitle => 'Grade current resource for a selection of students.'
10601:                         }, 
10602:                         {       linktext => 'Grade ungraded submissions',
10603:                                 url => $url1b,
10604:                                 permission => $permissions{'either'},
10605:                                 icon => 'ungrade_sub.png',
10606:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10607:                         },
10608: 
10609:                         {       linktext => 'Grading table',
10610:                                 url => $url1c,
10611:                                 permission => $permissions{'either'},
10612:                                 icon => 'grading_table.png',
10613:                                 linktitle => 'Grade current resource for all students.'
10614:                         },
10615:                         {       linktext => 'Grade page/folder for one student',
10616:                                 url => $url1d,
10617:                                 permission => $permissions{'either'},
10618:                                 icon => 'grade_PageFolder.png',
10619:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10620:                         },
10621:                         {       linktext => 'Download submissions',
10622:                                 url => $url1e,
10623:                                 permission => $permissions{'either'},
10624:                                 icon => 'download_sub.png',
10625:                                 linktitle => 'Download all students submissions.'
10626:                         }]},
10627:                          { categorytitle=>'Automated Grading',
10628:                items =>[
10629: 
10630:                 	    {	linktext => 'Upload Scores',
10631:                     		url => $url2,
10632:                     		permission => $permissions{'mgr'},
10633:                     		icon => 'uploadscores.png',
10634:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10635:                 	    },
10636:                 	    {	linktext => 'Process Clicker',
10637:                     		url => $url3,
10638:                     		permission => $permissions{'mgr'},
10639:                     		icon => 'addClickerInfoFile.png',
10640:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10641:                 	    },
10642:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10643:                     		url => $url4,
10644:                     		permission => $permissions{'mgr'},
10645:                     		icon => 'bubblesheet.png',
10646:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10647:                 	    },
10648:                             {   linktext => 'Verify Receipt Number',
10649:                                 url => $url5,
10650:                                 permission => $permissions{'either'},
10651:                                 icon => 'receipt_number.png',
10652:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10653:                             }
10654: 
10655:                     ]
10656:             });
10657: 
10658:     # Create the menu
10659:     my $Str;
10660:     $Str .= '<form method="post" action="" name="gradingMenu">';
10661:     $Str .= '<input type="hidden" name="command" value="" />'.
10662:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10663: 
10664:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10665:     return $Str;    
10666: }
10667: 
10668: sub ungraded {
10669:     my ($request)=@_;
10670:     &submit_options($request);
10671: }
10672: 
10673: sub submit_options_sequence {
10674:     my ($request,$symb) = @_;
10675:     if (!$symb) {return '';}
10676:     &commonJSfunctions($request);
10677:     my $result;
10678: 
10679:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10680:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10681:     $result.=&selectfield(0).
10682:             '<input type="hidden" name="command" value="pickStudentPage" />
10683:             <div>
10684:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10685:             </div>
10686:         </div>
10687:   </form>';
10688:     return $result;
10689: }
10690: 
10691: sub submit_options_table {
10692:     my ($request,$symb) = @_;
10693:     if (!$symb) {return '';}
10694:     &commonJSfunctions($request);
10695:     my $is_tool = ($symb =~ /ext\.tool$/);
10696:     my $result;
10697: 
10698:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10699:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10700: 
10701:     $result.=&selectfield(1,$is_tool).
10702:             '<input type="hidden" name="command" value="viewgrades" />
10703:             <div>
10704:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10705:             </div>
10706:         </div>
10707:   </form>';
10708:     return $result;
10709: }
10710: 
10711: sub submit_options_download {
10712:     my ($request,$symb) = @_;
10713:     if (!$symb) {return '';}
10714: 
10715:     my $res_error;
10716:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10717:         &response_type($symb,\$res_error);
10718:     if ($res_error) {
10719:         $request->print(&mt('An error occurred retrieving response types'));
10720:         return;
10721:     }
10722:     unless ($numessay) {
10723:         $request->print(&mt('No essayresponse items found'));
10724:         return;
10725:     }
10726:     my $table;
10727:     if (ref($partlist) eq 'ARRAY') {
10728:         if (scalar(@$partlist) > 1 ) {
10729:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10730:         }
10731:     }
10732: 
10733:     my $is_tool = ($symb =~ /ext\.tool$/);
10734:     &commonJSfunctions($request);
10735: 
10736:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10737:                $table."\n".
10738:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10739:     $result.='
10740: <h2>
10741:   '.&mt('Select Students for whom to Download Submissions').'
10742: </h2>'.&selectfield(1,$is_tool).'
10743:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10744:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10745:             </div>
10746:           </div>
10747: 
10748: 
10749:   </form>';
10750:     return $result;
10751: }
10752: 
10753: #--- Displays the submissions first page -------
10754: sub submit_options {
10755:     my ($request,$symb) = @_;
10756:     if (!$symb) {return '';}
10757: 
10758:     my $is_tool = ($symb =~ /ext\.tool$/);
10759:     &commonJSfunctions($request);
10760:     my $result;
10761: 
10762:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10763: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10764:     $result.=&selectfield(1,$is_tool).'
10765:                 <input type="hidden" name="command" value="submission" /> 
10766: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10767:             </div>
10768:           </div>
10769:   </form>';
10770:     return $result;
10771: }
10772: 
10773: sub selectfield {
10774:    my ($full,$is_tool)=@_;
10775:    my %options;
10776:    if ($is_tool) {
10777:        %options =
10778:            (&transtatus_options,
10779:             'select_form_order' => ['yes','incorrect','all']);
10780:    } else {
10781:        %options = 
10782:            (&substatus_options,
10783:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10784:    }
10785: 
10786:   #
10787:   # PrepareClasslist() needs to be called to avoid getting a sections list
10788:   # for a different course from the @Sections global in lonstatistics.pm, 
10789:   # populated by an earlier request.
10790:   #
10791:    &Apache::lonstatistics::PrepareClasslist();
10792: 
10793:    my $result='<div class="LC_columnSection">
10794:   
10795:     <fieldset>
10796:       <legend>
10797:        '.&mt('Sections').'
10798:       </legend>
10799:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10800:     </fieldset>
10801:   
10802:     <fieldset>
10803:       <legend>
10804:         '.&mt('Groups').'
10805:       </legend>
10806:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10807:     </fieldset>
10808:   
10809:     <fieldset>
10810:       <legend>
10811:         '.&mt('Access Status').'
10812:       </legend>
10813:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10814:     </fieldset>';
10815:     if ($full) {
10816:         my $heading = &mt('Submission Status');
10817:         if ($is_tool) {
10818:             $heading = &mt('Transaction Status');
10819:         }
10820:         $result.='
10821:     <fieldset>
10822:       <legend>
10823:         '.$heading.'
10824:       </legend>'.
10825:        &Apache::loncommon::select_form('all','submitonly',\%options).
10826:    '</fieldset>';
10827:     }
10828:     $result.='</div><br />';
10829:     return $result;
10830: }
10831: 
10832: sub substatus_options {
10833:     return &Apache::lonlocal::texthash(
10834:                                       'yes'       => 'with submissions',
10835:                                       'queued'    => 'in grading queue',
10836:                                       'graded'    => 'with ungraded submissions',
10837:                                       'incorrect' => 'with incorrect submissions',
10838:                                       'all'       => 'with any status',
10839:                                       );
10840: }
10841: 
10842: sub transtatus_options {
10843:     return &Apache::lonlocal::texthash(
10844:                                        'yes'       => 'with score transactions',
10845:                                        'incorrect' => 'with less than full credit',
10846:                                        'all'       => 'with any status',
10847:                                       );
10848: }
10849: 
10850: sub reset_perm {
10851:     undef(%perm);
10852: }
10853: 
10854: sub init_perm {
10855:     &reset_perm();
10856:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10857: 
10858: 	my $scope = $env{'request.course.id'};
10859: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10860: 
10861: 	    $scope .= '/'.$env{'request.course.sec'};
10862: 	    if ( $perm{$test_perm}=
10863: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10864: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10865: 	    } else {
10866: 		delete($perm{$test_perm});
10867: 	    }
10868: 	}
10869:     }
10870: }
10871: 
10872: sub init_old_essays {
10873:     my ($symb,$apath,$adom,$aname) = @_;
10874:     if ($symb ne '') {
10875:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10876:         if (keys(%essays) > 0) {
10877:             $old_essays{$symb} = \%essays;
10878:         }
10879:     }
10880:     return;
10881: }
10882: 
10883: sub reset_old_essays {
10884:     undef(%old_essays);
10885: }
10886: 
10887: sub gather_clicker_ids {
10888:     my %clicker_ids;
10889: 
10890:     my $classlist = &Apache::loncoursedata::get_classlist();
10891: 
10892:     # Set up a couple variables.
10893:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10894:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10895:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10896: 
10897:     foreach my $student (keys(%$classlist)) {
10898:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10899:         my $username = $classlist->{$student}->[$username_idx];
10900:         my $domain   = $classlist->{$student}->[$domain_idx];
10901:         my $clickers =
10902: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10903:         foreach my $id (split(/\,/,$clickers)) {
10904:             $id=~s/^[\#0]+//;
10905:             $id=~s/[\-\:]//g;
10906:             if (exists($clicker_ids{$id})) {
10907: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10908:             } else {
10909: 		$clicker_ids{$id}=$username.':'.$domain;
10910:             }
10911:         }
10912:     }
10913:     return %clicker_ids;
10914: }
10915: 
10916: sub gather_adv_clicker_ids {
10917:     my %clicker_ids;
10918:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10919:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10920:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10921:     foreach my $element (sort(keys(%coursepersonnel))) {
10922:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10923:             my ($puname,$pudom)=split(/\:/,$person);
10924:             my $clickers =
10925: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10926:             foreach my $id (split(/\,/,$clickers)) {
10927: 		$id=~s/^[\#0]+//;
10928:                 $id=~s/[\-\:]//g;
10929: 		if (exists($clicker_ids{$id})) {
10930: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10931: 		} else {
10932: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10933: 		}
10934:             }
10935:         }
10936:     }
10937:     return %clicker_ids;
10938: }
10939: 
10940: sub clicker_grading_parameters {
10941:     return ('gradingmechanism' => 'scalar',
10942:             'upfiletype' => 'scalar',
10943:             'specificid' => 'scalar',
10944:             'pcorrect' => 'scalar',
10945:             'pincorrect' => 'scalar');
10946: }
10947: 
10948: sub process_clicker {
10949:     my ($r,$symb)=@_;
10950:     if (!$symb) {return '';}
10951:     my $result=&checkforfile_js();
10952:     $result.=&Apache::loncommon::start_data_table().
10953:              &Apache::loncommon::start_data_table_header_row().
10954:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10955:              &Apache::loncommon::end_data_table_header_row().
10956:              &Apache::loncommon::start_data_table_row()."<td>\n";
10957: # Attempt to restore parameters from last session, set defaults if not present
10958:     my %Saveable_Parameters=&clicker_grading_parameters();
10959:     &Apache::loncommon::restore_course_settings('grades_clicker',
10960:                                                  \%Saveable_Parameters);
10961:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10962:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10963:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10964:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10965: 
10966:     my %checked;
10967:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10968:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10969:           $checked{$gradingmechanism}=' checked="checked"';
10970:        }
10971:     }
10972: 
10973:     my $upload=&mt("Evaluate File");
10974:     my $type=&mt("Type");
10975:     my $attendance=&mt("Award points just for participation");
10976:     my $personnel=&mt("Correctness determined from response by course personnel");
10977:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10978:     my $given=&mt("Correctness determined from given list of answers").' '.
10979:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10980:     my $pcorrect=&mt("Percentage points for correct solution");
10981:     my $pincorrect=&mt("Percentage points for incorrect solution");
10982:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10983: 						   {'iclicker' => 'i>clicker',
10984:                                                     'interwrite' => 'interwrite PRS',
10985:                                                     'turning' => 'Turning Technologies'});
10986:     $symb = &Apache::lonenc::check_encrypt($symb);
10987:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10988: function sanitycheck() {
10989: // Accept only integer percentages
10990:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10991:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10992: // Find out grading choice
10993:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10994:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10995:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10996:       }
10997:    }
10998: // By default, new choice equals user selection
10999:    newgradingchoice=gradingchoice;
11000: // Not good to give more points for false answers than correct ones
11001:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
11002:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
11003:    }
11004: // If new choice is attendance only, and old choice was correctness-based, restore defaults
11005:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
11006:       document.forms.gradesupload.pcorrect.value=100;
11007:       document.forms.gradesupload.pincorrect.value=100;
11008:    }
11009: // If the values are different, cannot be attendance only
11010:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
11011:        (gradingchoice=='attendance')) {
11012:        newgradingchoice='personnel';
11013:    }
11014: // Change grading choice to new one
11015:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
11016:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
11017:          document.forms.gradesupload.gradingmechanism[i].checked=true;
11018:       } else {
11019:          document.forms.gradesupload.gradingmechanism[i].checked=false;
11020:       }
11021:    }
11022: // Remember the old state
11023:    document.forms.gradesupload.waschecked.value=newgradingchoice;
11024: }
11025: ENDUPFORM
11026:     $result.= <<ENDUPFORM;
11027: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
11028: <input type="hidden" name="symb" value="$symb" />
11029: <input type="hidden" name="command" value="processclickerfile" />
11030: <input type="file" name="upfile" size="50" />
11031: <br /><label>$type: $selectform</label>
11032: ENDUPFORM
11033:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
11034:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
11035:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
11036: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
11037: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
11038: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
11039: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
11040: <br />&nbsp;&nbsp;&nbsp;
11041: <input type="text" name="givenanswer" size="50" />
11042: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
11043: ENDGRADINGFORM
11044:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
11045:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
11046:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
11047: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
11048: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
11049: </form>
11050: ENDPERCFORM
11051:     $result.='</td>'.
11052:              &Apache::loncommon::end_data_table_row().
11053:              &Apache::loncommon::end_data_table();
11054:     return $result;
11055: }
11056: 
11057: sub process_clicker_file {
11058:     my ($r,$symb) = @_;
11059:     if (!$symb) {return '';}
11060: 
11061:     my %Saveable_Parameters=&clicker_grading_parameters();
11062:     &Apache::loncommon::store_course_settings('grades_clicker',
11063:                                               \%Saveable_Parameters);
11064:     my $result='';
11065:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
11066: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
11067: 	return $result;
11068:     }
11069:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
11070:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
11071:         return $result;
11072:     }
11073:     my $foundgiven=0;
11074:     if ($env{'form.gradingmechanism'} eq 'given') {
11075:         $env{'form.givenanswer'}=~s/^\s*//gs;
11076:         $env{'form.givenanswer'}=~s/\s*$//gs;
11077:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
11078:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
11079:         my @answers=split(/\,/,$env{'form.givenanswer'});
11080:         $foundgiven=$#answers+1;
11081:     }
11082:     my %clicker_ids=&gather_clicker_ids();
11083:     my %correct_ids;
11084:     if ($env{'form.gradingmechanism'} eq 'personnel') {
11085: 	%correct_ids=&gather_adv_clicker_ids();
11086:     }
11087:     if ($env{'form.gradingmechanism'} eq 'specific') {
11088: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
11089: 	   $correct_id=~tr/a-z/A-Z/;
11090: 	   $correct_id=~s/\s//gs;
11091: 	   $correct_id=~s/^[\#0]+//;
11092:            $correct_id=~s/[\-\:]//g;
11093:            if ($correct_id) {
11094: 	      $correct_ids{$correct_id}='specified';
11095:            }
11096:         }
11097:     }
11098:     if ($env{'form.gradingmechanism'} eq 'attendance') {
11099: 	$result.=&mt('Score based on attendance only');
11100:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
11101:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
11102:     } else {
11103: 	my $number=0;
11104: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
11105: 	foreach my $id (sort(keys(%correct_ids))) {
11106: 	    $result.='<br /><tt>'.$id.'</tt> - ';
11107: 	    if ($correct_ids{$id} eq 'specified') {
11108: 		$result.=&mt('specified');
11109: 	    } else {
11110: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
11111: 		$result.=&Apache::loncommon::plainname($uname,$udom);
11112: 	    }
11113: 	    $number++;
11114: 	}
11115:         $result.="</p>\n";
11116:         if ($number==0) {
11117:             $result .=
11118:                  &Apache::lonhtmlcommon::confirm_success(
11119:                      &mt('No IDs found to determine correct answer'),1);
11120:             return $result;
11121:         }
11122:     }
11123:     if (length($env{'form.upfile'}) < 2) {
11124:         $result .=
11125:             &Apache::lonhtmlcommon::confirm_success(
11126:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
11127:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
11128:         return $result;
11129:     }
11130:     my $mimetype;
11131:     if ($env{'form.upfiletype'} eq 'iclicker') {
11132:         my $mm = new File::MMagic;
11133:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
11134:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
11135:             $result.= '<p>'.
11136:                 &Apache::lonhtmlcommon::confirm_success(
11137:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
11138:             return $result;
11139:         }
11140:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
11141:         $result .= '<p>'.
11142:             &Apache::lonhtmlcommon::confirm_success(
11143:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
11144:         return $result;
11145:     }
11146: 
11147: # Were able to get all the info needed, now analyze the file
11148: 
11149:     $result.=&Apache::loncommon::studentbrowser_javascript();
11150:     $symb = &Apache::lonenc::check_encrypt($symb);
11151:     $result.=&Apache::loncommon::start_data_table().
11152:              &Apache::loncommon::start_data_table_header_row().
11153:              '<th>'.&mt('Evaluate clicker file').'</th>'.
11154:              &Apache::loncommon::end_data_table_header_row().
11155:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
11156: <td>
11157: <form method="post" action="/adm/grades" name="clickeranalysis">
11158: <input type="hidden" name="symb" value="$symb" />
11159: <input type="hidden" name="command" value="assignclickergrades" />
11160: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
11161: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
11162: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
11163: ENDHEADER
11164:     if ($env{'form.gradingmechanism'} eq 'given') {
11165:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
11166:     } 
11167:     my %responses;
11168:     my @questiontitles;
11169:     my $errormsg='';
11170:     my $number=0;
11171:     if ($env{'form.upfiletype'} eq 'iclicker') {
11172:         if ($mimetype eq 'text/plain') {
11173:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
11174:         } elsif ($mimetype eq 'text/html') {
11175:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
11176:         }
11177:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
11178:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
11179:     } elsif ($env{'form.upfiletype'} eq 'turning') {
11180:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
11181:     }
11182:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
11183:              '<input type="hidden" name="number" value="'.$number.'" />'.
11184:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
11185:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
11186:              '<br />';
11187:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
11188:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
11189:        return $result;
11190:     } 
11191: # Remember Question Titles
11192: # FIXME: Possibly need delimiter other than ":"
11193:     for (my $i=0;$i<$number;$i++) {
11194:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
11195:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
11196:     }
11197:     my $correct_count=0;
11198:     my $student_count=0;
11199:     my $unknown_count=0;
11200: # Match answers with usernames
11201: # FIXME: Possibly need delimiter other than ":"
11202:     foreach my $id (keys(%responses)) {
11203:        if ($correct_ids{$id}) {
11204:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
11205:           $correct_count++;
11206:        } elsif ($clicker_ids{$id}) {
11207:           if ($clicker_ids{$id}=~/\,/) {
11208: # More than one user with the same clicker!
11209:              $result.="</td>".&Apache::loncommon::end_data_table_row().
11210:                            &Apache::loncommon::start_data_table_row()."<td>".
11211:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
11212:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11213:                            "<select name='multi".$id."'>";
11214:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
11215:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
11216:              }
11217:              $result.='</select>';
11218:              $unknown_count++;
11219:           } else {
11220: # Good: found one and only one user with the right clicker
11221:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
11222:              $student_count++;
11223:           }
11224:        } else {
11225:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11226:                            &Apache::loncommon::start_data_table_row()."<td>".
11227:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11228:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11229:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11230:                    "\n".&mt("Domain").": ".
11231:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11232:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11233:           $unknown_count++;
11234:        }
11235:     }
11236:     $result.='<hr />'.
11237:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11238:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11239:        if ($correct_count==0) {
11240:           $errormsg.="Found no correct answers for grading!";
11241:        } elsif ($correct_count>1) {
11242:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11243:        }
11244:     }
11245:     if ($number<1) {
11246:        $errormsg.="Found no questions.";
11247:     }
11248:     if ($errormsg) {
11249:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11250:     } else {
11251:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11252:     }
11253:     $result.='</form></td>'.
11254:              &Apache::loncommon::end_data_table_row().
11255:              &Apache::loncommon::end_data_table();
11256:     return $result;
11257: }
11258: 
11259: sub iclicker_eval {
11260:     my ($questiontitles,$responses)=@_;
11261:     my $number=0;
11262:     my $errormsg='';
11263:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11264:         my %components=&Apache::loncommon::record_sep($line);
11265:         my @entries=map {$components{$_}} (sort(keys(%components)));
11266: 	if ($entries[0] eq 'Question') {
11267: 	    for (my $i=3;$i<$#entries;$i+=6) {
11268: 		$$questiontitles[$number]=$entries[$i];
11269: 		$number++;
11270: 	    }
11271: 	}
11272: 	if ($entries[0]=~/^\#/) {
11273: 	    my $id=$entries[0];
11274: 	    my @idresponses;
11275: 	    $id=~s/^[\#0]+//;
11276: 	    for (my $i=0;$i<$number;$i++) {
11277: 		my $idx=3+$i*6;
11278:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11279: 		push(@idresponses,$entries[$idx]);
11280: 	    }
11281: 	    $$responses{$id}=join(',',@idresponses);
11282: 	}
11283:     }
11284:     return ($errormsg,$number);
11285: }
11286: 
11287: sub iclickerxml_eval {
11288:     my ($questiontitles,$responses)=@_;
11289:     my $number=0;
11290:     my $errormsg='';
11291:     my @state;
11292:     my %respbyid;
11293:     my $p = HTML::Parser->new
11294:     (
11295:         xml_mode => 1,
11296:         start_h =>
11297:             [sub {
11298:                  my ($tagname,$attr) = @_;
11299:                  push(@state,$tagname);
11300:                  if ("@state" eq "ssn p") {
11301:                      my $title = $attr->{qn};
11302:                      $title =~ s/(^\s+|\s+$)//g;
11303:                      $questiontitles->[$number]=$title;
11304:                  } elsif ("@state" eq "ssn p v") {
11305:                      my $id = $attr->{id};
11306:                      my $entry = $attr->{ans};
11307:                      $id=~s/^[\#0]+//;
11308:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11309:                      $respbyid{$id}[$number] = $entry;
11310:                  }
11311:             }, "tagname, attr"],
11312:          end_h =>
11313:                [sub {
11314:                    my ($tagname) = @_;
11315:                    if ("@state" eq "ssn p") {
11316:                        $number++;
11317:                    }
11318:                    pop(@state);
11319:                 }, "tagname"],
11320:     );
11321: 
11322:     $p->parse($env{'form.upfile'});
11323:     $p->eof;
11324:     foreach my $id (keys(%respbyid)) {
11325:         $responses->{$id}=join(',',@{$respbyid{$id}});
11326:     }
11327:     return ($errormsg,$number);
11328: }
11329: 
11330: sub interwrite_eval {
11331:     my ($questiontitles,$responses)=@_;
11332:     my $number=0;
11333:     my $errormsg='';
11334:     my $skipline=1;
11335:     my $questionnumber=0;
11336:     my %idresponses=();
11337:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11338:         my %components=&Apache::loncommon::record_sep($line);
11339:         my @entries=map {$components{$_}} (sort(keys(%components)));
11340:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11341:         if ($entries[1] eq 'Response') { $skipline=1; }
11342:         next if $skipline;
11343:         if ($entries[0]!=$questionnumber) {
11344:            $questionnumber=$entries[0];
11345:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11346:            $number++;
11347:         }
11348:         my $id=$entries[4];
11349:         $id=~s/^[\#0]+//;
11350:         $id=~s/^v\d*\://i;
11351:         $id=~s/[\-\:]//g;
11352:         $idresponses{$id}[$number]=$entries[6];
11353:     }
11354:     foreach my $id (keys(%idresponses)) {
11355:        $$responses{$id}=join(',',@{$idresponses{$id}});
11356:        $$responses{$id}=~s/^\s*\,//;
11357:     }
11358:     return ($errormsg,$number);
11359: }
11360: 
11361: sub turning_eval {
11362:     my ($questiontitles,$responses)=@_;
11363:     my $number=0;
11364:     my $errormsg='';
11365:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11366:         my %components=&Apache::loncommon::record_sep($line);
11367:         my @entries=map {$components{$_}} (sort(keys(%components)));
11368:         if ($#entries>$number) { $number=$#entries; }
11369:         my $id=$entries[0];
11370:         my @idresponses;
11371:         $id=~s/^[\#0]+//;
11372:         unless ($id) { next; }
11373:         for (my $idx=1;$idx<=$#entries;$idx++) {
11374:             $entries[$idx]=~s/\,/\;/g;
11375:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11376:             push(@idresponses,$entries[$idx]);
11377:         }
11378:         $$responses{$id}=join(',',@idresponses);
11379:     }
11380:     for (my $i=1; $i<=$number; $i++) {
11381:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11382:     }
11383:     return ($errormsg,$number);
11384: }
11385: 
11386: 
11387: sub assign_clicker_grades {
11388:     my ($r,$symb) = @_;
11389:     if (!$symb) {return '';}
11390: # See which part we are saving to
11391:     my $res_error;
11392:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11393:     if ($res_error) {
11394:         return &navmap_errormsg();
11395:     }
11396: # FIXME: This should probably look for the first handgradeable part
11397:     my $part=$$partlist[0];
11398: # Start screen output
11399:     my $result = &Apache::loncommon::start_data_table().
11400:                  &Apache::loncommon::start_data_table_header_row().
11401:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11402:                  &Apache::loncommon::end_data_table_header_row().
11403:                  &Apache::loncommon::start_data_table_row().'<td>';
11404: # Get correct result
11405: # FIXME: Possibly need delimiter other than ":"
11406:     my @correct=();
11407:     my $gradingmechanism=$env{'form.gradingmechanism'};
11408:     my $number=$env{'form.number'};
11409:     if ($gradingmechanism ne 'attendance') {
11410:        foreach my $key (keys(%env)) {
11411:           if ($key=~/^form\.correct\:/) {
11412:              my @input=split(/\,/,$env{$key});
11413:              for (my $i=0;$i<=$#input;$i++) {
11414:                  if (($correct[$i]) && ($input[$i]) &&
11415:                      ($correct[$i] ne $input[$i])) {
11416:                     $result.='<br /><span class="LC_warning">'.
11417:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11418:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11419:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11420:                     $correct[$i]=$input[$i];
11421:                  }
11422:              }
11423:           }
11424:        }
11425:        for (my $i=0;$i<$number;$i++) {
11426:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11427:              $result.='<br /><span class="LC_error">'.
11428:                       &mt('No correct result given for question "[_1]"!',
11429:                           $env{'form.question:'.$i}).'</span>';
11430:           }
11431:        }
11432:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11433:     }
11434: # Start grading
11435:     my $pcorrect=$env{'form.pcorrect'};
11436:     my $pincorrect=$env{'form.pincorrect'};
11437:     my $storecount=0;
11438:     my %users=();
11439:     foreach my $key (keys(%env)) {
11440:        my $user='';
11441:        if ($key=~/^form\.student\:(.*)$/) {
11442:           $user=$1;
11443:        }
11444:        if ($key=~/^form\.unknown\:(.*)$/) {
11445:           my $id=$1;
11446:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11447:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11448:           } elsif ($env{'form.multi'.$id}) {
11449:              $user=$env{'form.multi'.$id};
11450:           }
11451:        }
11452:        if ($user) {
11453:           if ($users{$user}) {
11454:              $result.='<br /><span class="LC_warning">'.
11455:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11456:                       '</span><br />';
11457:           }
11458:           $users{$user}=1; 
11459:           my @answer=split(/\,/,$env{$key});
11460:           my $sum=0;
11461:           my $realnumber=$number;
11462:           for (my $i=0;$i<$number;$i++) {
11463:              if  ($correct[$i] eq '-') {
11464:                 $realnumber--;
11465:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11466:                 if ($gradingmechanism eq 'attendance') {
11467:                    $sum+=$pcorrect;
11468:                 } elsif ($correct[$i] eq '*') {
11469:                    $sum+=$pcorrect;
11470:                 } else {
11471: # We actually grade if correct or not
11472:                    my $increment=$pincorrect;
11473: # Special case: numerical answer "0"
11474:                    if ($correct[$i] eq '0') {
11475:                       if ($answer[$i]=~/^[0\.]+$/) {
11476:                          $increment=$pcorrect;
11477:                       }
11478: # General numerical answer, both evaluate to something non-zero
11479:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11480:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11481:                          $increment=$pcorrect;
11482:                       }
11483: # Must be just alphanumeric
11484:                    } elsif ($answer[$i] eq $correct[$i]) {
11485:                       $increment=$pcorrect;
11486:                    }
11487:                    $sum+=$increment;
11488:                 }
11489:              }
11490:           }
11491:           my $ave=$sum/(100*$realnumber);
11492: # Store
11493:           my ($username,$domain)=split(/\:/,$user);
11494:           my %grades=();
11495:           $grades{"resource.$part.solved"}='correct_by_override';
11496:           $grades{"resource.$part.awarded"}=$ave;
11497:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11498:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11499:                                                  $env{'request.course.id'},
11500:                                                  $domain,$username);
11501:           if ($returncode ne 'ok') {
11502:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11503:           } else {
11504:              $storecount++;
11505:           }
11506:        }
11507:     }
11508: # We are done
11509:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11510:              '</td>'.
11511:              &Apache::loncommon::end_data_table_row().
11512:              &Apache::loncommon::end_data_table();
11513:     return $result;
11514: }
11515: 
11516: sub navmap_errormsg {
11517:     return '<div class="LC_error">'.
11518:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11519:            &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>').
11520:            '</div>';
11521: }
11522: 
11523: sub startpage {
11524:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11525:     my %args;
11526:     if ($onload) {
11527:          my %loaditems = (
11528:                         'onload' => $onload,
11529:                       );
11530:          $args{'add_entries'} = \%loaditems;
11531:     }
11532:     if ($nomenu) {
11533:         $args{'only_body'} = 1; 
11534:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11535:     } else {
11536:         if ($env{'request.course.id'}) { 
11537:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11538:         }
11539:         $args{'bread_crumbs'} = $crumbs;
11540:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11541:         if ($env{'request.course.id'}) {
11542:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11543:         }
11544:     }
11545:     unless ($nodisplayflag) {
11546:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11547:     }
11548: }
11549: 
11550: sub select_problem {
11551:     my ($r)=@_;
11552:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11553:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11554:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11555:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11556: }
11557: 
11558: sub handler {
11559:     my $request=$_[0];
11560:     &reset_caches();
11561:     if ($request->header_only) {
11562:         &Apache::loncommon::content_type($request,'text/html');
11563:         $request->send_http_header;
11564:         return OK;
11565:     }
11566:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11567: 
11568: # see what command we need to execute
11569: 
11570:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11571:     my $command=$commands[0];
11572: 
11573:     &init_perm();
11574:     if (!$env{'request.course.id'}) {
11575:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11576:                 ($command =~ /^scantronupload/)) {
11577:             # Not in a course.
11578:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11579:             return HTTP_NOT_ACCEPTABLE;
11580:         }
11581:     } elsif (!%perm) {
11582:         $request->internal_redirect('/adm/quickgrades');
11583:         return OK;
11584:     }
11585:     &Apache::loncommon::content_type($request,'text/html');
11586:     $request->send_http_header;
11587: 
11588:     if ($#commands > 0) {
11589: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11590:     }
11591: 
11592: # see what the symb is
11593: 
11594:     my $symb=$env{'form.symb'};
11595:     unless ($symb) {
11596:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11597:        $symb=&Apache::lonnet::symbread($url);
11598:     }
11599:     &Apache::lonenc::check_decrypt(\$symb);
11600: 
11601:     $ssi_error = 0;
11602:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11603: #
11604: # Not called from a resource, but inside a course
11605: #    
11606:         &startpage($request,undef,[],1,1);
11607:         &select_problem($request);
11608:     } else {
11609: 	if ($command eq 'submission' && $perm{'vgr'}) {
11610:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11611:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11612:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11613:                     &choose_task_version_form($symb,$env{'form.student'},
11614:                                               $env{'form.userdom'});
11615:             }
11616:             my $divforres;
11617:             if ($env{'form.student'} eq '') {
11618:                 $js .= &part_selector_js();
11619:                 $onload = "toggleParts('gradesub');";
11620:             } else {
11621:                 $divforres = 1;
11622:             }
11623:             my $head_extra = $js;
11624:             unless ($env{'form.vProb'} eq 'no') {
11625:                 my $csslinks = &Apache::loncommon::css_links($symb);
11626:                 if ($csslinks) {
11627:                     $head_extra .= "\n$csslinks";
11628:                 }
11629:             }
11630:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11631:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11632:             if ($versionform) {
11633:                 if ($divforres) {
11634:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11635:                 }
11636:                 $request->print($versionform);
11637:             }
11638: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11639:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11640:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11641:                 &choose_task_version_form($symb,$env{'form.student'},
11642:                                           $env{'form.userdom'},
11643:                                           $env{'form.inhibitmenu'});
11644:             my $head_extra = $js;
11645:             unless ($env{'form.vProb'} eq 'no') {
11646:                 my $csslinks = &Apache::loncommon::css_links($symb);
11647:                 if ($csslinks) {
11648:                     $head_extra .= "\n$csslinks";
11649:                 }
11650:             }
11651:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11652:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11653:             if ($versionform) {
11654:                 $request->print($versionform);
11655:             }
11656:             $request->print('<br clear="all" />');
11657:             $request->print(&show_previous_task_version($request,$symb));
11658: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11659:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11660:                                        {href=>'',text=>'Select student'}],1,1);
11661: 	    &pickStudentPage($request,$symb);
11662: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11663:             my $csslinks;
11664:             unless ($env{'form.vProb'} eq 'no') {
11665:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11666:             }
11667:             &startpage($request,$symb,
11668:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11669:                                        {href=>'',text=>'Select student'},
11670:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11671: 	    &displayPage($request,$symb);
11672: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11673:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11674:                                        {href=>'',text=>'Select student'},
11675:                                        {href=>'',text=>'Grade student'},
11676:                                        {href=>'',text=>'Store grades'}],1,1);
11677: 	    &updateGradeByPage($request,$symb);
11678: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11679:             my $csslinks;
11680:             unless ($env{'form.vProb'} eq 'no') {
11681:                 $csslinks = &Apache::loncommon::css_links($symb);
11682:             }
11683:             &startpage($request,$symb,[{href=>'',text=>'...'},
11684:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11685: 	    &processGroup($request,$symb);
11686: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11687:             &startpage($request,$symb);
11688: 	    $request->print(&grading_menu($request,$symb));
11689: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11690:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11691: 	    $request->print(&submit_options($request,$symb));
11692:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11693:             my $js = &part_selector_js();
11694:             my $onload = "toggleParts('gradesub');";
11695:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11696:                        undef,undef,undef,undef,undef,$js,$onload);
11697:             $request->print(&listStudents($request,$symb,'graded'));
11698:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11699:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11700:             $request->print(&submit_options_table($request,$symb));
11701:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11702:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11703:             $request->print(&submit_options_sequence($request,$symb));
11704: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11705:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11706: 	    $request->print(&viewgrades($request,$symb));
11707: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11708:             &startpage($request,$symb,[{href=>'',text=>'...'},
11709:                                        {href=>'',text=>'Store grades'}]);
11710: 	    $request->print(&processHandGrade($request,$symb));
11711: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11712:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11713:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11714:                                                                              text=>"Modify grades"},
11715:                                        {href=>'', text=>"Store grades"}]);
11716: 	    $request->print(&editgrades($request,$symb));
11717:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11718:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11719:             $request->print(&initialverifyreceipt($request,$symb));
11720: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11721:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11722:                                        {href=>'',text=>'Verification Result'}]);
11723: 	    $request->print(&verifyreceipt($request,$symb));
11724:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11725:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11726:             $request->print(&process_clicker($request,$symb));
11727:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11728:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11729:                                        {href=>'', text=>'Process clicker file'}]);
11730:             $request->print(&process_clicker_file($request,$symb));
11731:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11732:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11733:                                        {href=>'', text=>'Process clicker file'},
11734:                                        {href=>'', text=>'Store grades'}]);
11735:             $request->print(&assign_clicker_grades($request,$symb));
11736: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11737:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11738: 	    $request->print(&upcsvScores_form($request,$symb));
11739: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11740:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11741: 	    $request->print(&csvupload($request,$symb));
11742: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11743:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11744: 	    $request->print(&csvuploadmap($request,$symb));
11745: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11746: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11747:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11748: 		$request->print(&csvuploadoptions($request,$symb));
11749: 	    } else {
11750: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11751: 		    $env{'form.upfile_associate'} = 'reverse';
11752: 		} else {
11753: 		    $env{'form.upfile_associate'} = 'forward';
11754: 		}
11755:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11756: 		$request->print(&csvuploadmap($request,$symb));
11757: 	    }
11758: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11759:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11760: 	    $request->print(&csvuploadassign($request,$symb));
11761: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11762:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11763:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11764: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11765:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11766:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11767:  	    $request->print(&scantron_do_warning($request,$symb));
11768: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11769:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11770: 	    $request->print(&scantron_validate_file($request,$symb));
11771: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11772:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11773: 	    $request->print(&scantron_process_students($request,$symb));
11774:  	} elsif ($command eq 'scantronupload' && 
11775:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11776:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11777:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11778:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11779:  	} elsif ($command eq 'scantronupload_save' &&
11780:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11781:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11782:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11783:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11784:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11785:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11786:         } elsif ($command eq 'scantronupload_delete' &&
11787:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11788:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11789:             &scantron_upload_delete($request,$symb);
11790:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11791:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11792:             $request->print(&checkscantron_results($request,$symb));
11793:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11794:             my $js = &part_selector_js();
11795:             my $onload = "toggleParts('gradingMenu');";
11796:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11797:                        undef,undef,undef,undef,undef,$js,$onload);
11798:             $request->print(&submit_options_download($request,$symb));
11799:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11800:             &startpage($request,$symb,
11801:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11802:     {href=>'', text=>'Download submitted files'}],
11803:                undef,undef,undef,undef,undef,undef,undef,1);
11804:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11805:             &submit_download_link($request,$symb);
11806: 	} elsif ($command) {
11807:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11808: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11809: 	}
11810:     }
11811:     if ($ssi_error) {
11812: 	&ssi_print_error($request);
11813:     }
11814:     if ($env{'form.inhibitmenu'}) {
11815:         $request->print(&Apache::loncommon::end_page());
11816:     } elsif ($env{'request.course.id'}) {
11817:         &Apache::lonquickgrades::endGradeScreen($request);
11818:     }
11819:     &reset_caches();
11820:     return OK;
11821: }
11822: 
11823: 1;
11824: 
11825: __END__;
11826: 
11827: 
11828: =head1 NAME
11829: 
11830: Apache::grades
11831: 
11832: =head1 SYNOPSIS
11833: 
11834: Handles the viewing of grades.
11835: 
11836: This is part of the LearningOnline Network with CAPA project
11837: described at http://www.lon-capa.org.
11838: 
11839: =head1 OVERVIEW
11840: 
11841: Do an ssi with retries:
11842: While I'd love to factor out this with the version in lonprintout,
11843: 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
11844: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11845: 
11846: At least the logic that drives this has been pulled out into loncommon.
11847: 
11848: 
11849: 
11850: ssi_with_retries - Does the server side include of a resource.
11851:                      if the ssi call returns an error we'll retry it up to
11852:                      the number of times requested by the caller.
11853:                      If we still have a problem, no text is appended to the
11854:                      output and we set some global variables.
11855:                      to indicate to the caller an SSI error occurred.  
11856:                      All of this is supposed to deal with the issues described
11857:                      in LON-CAPA BZ 5631 see:
11858:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11859:                      by informing the user that this happened.
11860: 
11861: Parameters:
11862:   resource   - The resource to include.  This is passed directly, without
11863:                interpretation to lonnet::ssi.
11864:   form       - The form hash parameters that guide the interpretation of the resource
11865:                
11866:   retries    - Number of retries allowed before giving up completely.
11867: Returns:
11868:   On success, returns the rendered resource identified by the resource parameter.
11869: Side Effects:
11870:   The following global variables can be set:
11871:    ssi_error                - If an unrecoverable error occurred this becomes true.
11872:                               It is up to the caller to initialize this to false
11873:                               if desired.
11874:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11875:                               of the resource that could not be rendered by the ssi
11876:                               call.
11877:    ssi_error_message   - The error string fetched from the ssi response
11878:                               in the event of an error.
11879: 
11880: 
11881: =head1 HANDLER SUBROUTINE
11882: 
11883: ssi_with_retries()
11884: 
11885: =head1 SUBROUTINES
11886: 
11887: =over
11888: 
11889: =head1 Routines to display previous version of a Task for a specific student
11890: 
11891: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11892: can receive another opportunity. Access to tasks is slot-based. If a slot
11893: requires a proctor to check-in the student, a new version of the Task will
11894: be created when the student is checked in to the new opportunity.
11895: 
11896: If a particular student has tried two or more versions of a particular task,
11897: the submission screen provides a user with vgr privileges (e.g., a Course
11898: Coordinator) the ability to display a previous version worked on by the
11899: student.  By default, the current version is displayed. If a previous version
11900: has been selected for display, submission data are only shown that pertain
11901: to that particular version, and the interface to submit grades is not shown.
11902: 
11903: =over 4
11904: 
11905: =item show_previous_task_version()
11906: 
11907: Displays a specified version of a student's Task, as the student sees it.
11908: 
11909: Inputs: 2
11910:         request - request object
11911:         symb    - unique symb for current instance of resource
11912: 
11913: Output: None.
11914: 
11915: Side Effects: calls &show_problem() to print version of Task, with
11916:               version contained in form item: $env{'form.previousversion'}
11917: 
11918: =item choose_task_version_form()
11919: 
11920: Displays a web form used to select which version of a student's view of a
11921: Task should be displayed.  Either launches a pop-up window, or replaces
11922: content in existing pop-up, or replaces page in main window.
11923: 
11924: Inputs: 4
11925:         symb    - unique symb for current instance of resource
11926:         uname   - username of student
11927:         udom    - domain of student
11928:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11929:                   breadcrumbs etc., are displayed
11930: 
11931: Output: 4
11932:         current   - student's current version
11933:         displayed - student's version being displayed
11934:         result    - scalar containing HTML for web form used to switch to
11935:                     a different version (or a link to close window, if pop-up).
11936:         js        - javascript for processing selection in versions web form
11937: 
11938: Side Effects: None.
11939: 
11940: =item previous_display_javascript()
11941: 
11942: Inputs: 2
11943:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11944:                   breadcrumbs etc., are displayed.
11945:         current - student's current version number.
11946: 
11947: Output: 1
11948:         js      - javascript for processing selection in versions web form.
11949: 
11950: Side Effects: None.
11951: 
11952: =back
11953: 
11954: =head1 Routines to process bubblesheet data.
11955: 
11956: =over 4
11957: 
11958: =item scantron_get_correction() : 
11959: 
11960:    Builds the interface screen to interact with the operator to fix a
11961:    specific error condition in a specific scanline
11962: 
11963:  Arguments:
11964:     $r           - Apache request object
11965:     $i           - number of the current scanline
11966:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11967:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11968:     $line        - full contents of the current scanline
11969:     $error       - error condition, valid values are
11970:                    'incorrectCODE', 'duplicateCODE',
11971:                    'doublebubble', 'missingbubble',
11972:                    'duplicateID', 'incorrectID'
11973:     $arg         - extra information needed
11974:        For errors:
11975:          - duplicateID   - paper number that this studentID was seen before on
11976:          - duplicateCODE - array ref of the paper numbers this CODE was
11977:                            seen on before
11978:          - incorrectCODE - current incorrect CODE 
11979:          - doublebubble  - array ref of the bubble lines that have double
11980:                            bubble errors
11981:          - missingbubble - array ref of the bubble lines that have missing
11982:                            bubble errors
11983: 
11984:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
11985:    $randompick  - True if exam folder (or a sub-folder) has randompick set
11986:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11987:                      for current line to question number used for same question
11988:                      in "Master Seqence" (as seen by Course Coordinator).
11989:    $startline   - Reference to hash where key is question number (0 is first)
11990:                   and value is number of first bubble line for current student
11991:                   or code-based randompick and/or randomorder.
11992: 
11993: 
11994: 
11995: =item  scantron_get_maxbubble() : 
11996: 
11997:    Arguments:
11998:        $nav_error  - Reference to scalar which is a flag to indicate a
11999:                       failure to retrieve a navmap object.
12000:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
12001:        calling routine should trap the error condition and display the warning
12002:        found in &navmap_errormsg().
12003: 
12004:        $scantron_config - Reference to bubblesheet format configuration hash.
12005: 
12006:    Returns the maximum number of bubble lines that are expected to
12007:    occur. Does this by walking the selected sequence rendering the
12008:    resource and then checking &Apache::lonxml::get_problem_counter()
12009:    for what the current value of the problem counter is.
12010: 
12011:    Caches the results to $env{'form.scantron_maxbubble'},
12012:    $env{'form.scantron.bubble_lines.n'}, 
12013:    $env{'form.scantron.first_bubble_line.n'} and
12014:    $env{"form.scantron.sub_bubblelines.n"}
12015:    which are the total number of bubble lines, the number of bubble
12016:    lines for response n and number of the first bubble line for response n,
12017:    and a comma separated list of numbers of bubble lines for sub-questions
12018:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
12019: 
12020: 
12021: =item  scantron_validate_missingbubbles() : 
12022: 
12023:    Validates all scanlines in the selected file to not have any
12024:     answers that don't have bubbles that have not been verified
12025:     to be bubble free.
12026: 
12027: =item  scantron_process_students() : 
12028: 
12029:    Routine that does the actual grading of the bubblesheet information.
12030: 
12031:    The parsed scanline hash is added to %env 
12032: 
12033:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
12034:    foreach resource , with the form data of
12035: 
12036: 	'submitted'     =>'scantron' 
12037: 	'grade_target'  =>'grade',
12038: 	'grade_username'=> username of student
12039: 	'grade_domain'  => domain of student
12040: 	'grade_courseid'=> of course
12041: 	'grade_symb'    => symb of resource to grade
12042: 
12043:     This triggers a grading pass. The problem grading code takes care
12044:     of converting the bubbled letter information (now in %env) into a
12045:     valid submission.
12046: 
12047: =item  scantron_upload_scantron_data() :
12048: 
12049:     Creates the screen for adding a new bubblesheet data file to a course.
12050: 
12051: =item  scantron_upload_scantron_data_save() : 
12052: 
12053:    Adds a provided bubble information data file to the course if user
12054:    has the correct privileges to do so.
12055: 
12056: = item scantron_upload_delete() :
12057: 
12058:    Deletes a previously uploaded bubble information data file, if user
12059:    was the one who uploaded the file, and has the privileges to do so.
12060: 
12061: =item  valid_file() :
12062: 
12063:    Validates that the requested bubble data file exists in the course.
12064: 
12065: =item  scantron_download_scantron_data() : 
12066: 
12067:    Shows a list of the three internal files (original, corrected,
12068:    skipped) for a specific bubblesheet data file that exists in the
12069:    course.
12070: 
12071: =item  scantron_validate_ID() : 
12072: 
12073:    Validates all scanlines in the selected file to not have any
12074:    invalid or underspecified student/employee IDs
12075: 
12076: =item navmap_errormsg() :
12077: 
12078:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
12079:    Should be called whenever the request to instantiate a navmap object fails.
12080: 
12081: =back
12082: 
12083: =back
12084: 
12085: =cut

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