File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.60.2.4: download - view: text, annotated - select for diffs
Wed Jul 5 23:49:18 2023 UTC (11 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.596.2.12.2.60: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.745, 1.746, 1.747, 1.749, 1.793 (part)

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.60.2.4 2023/07/05 23:49:18 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::bridgetask();
   48: use Apache::lontexconvert();
   49: use String::Similarity;
   50: use HTML::Parser();
   51: use File::MMagic;
   52: use LONCAPA;
   53: 
   54: use POSIX qw(floor);
   55: 
   56: 
   57: 
   58: my %perm=();
   59: my %old_essays=();
   60: 
   61: #  These variables are used to recover from ssi errors
   62: 
   63: my $ssi_retries = 5;
   64: my $ssi_error;
   65: my $ssi_error_resource;
   66: my $ssi_error_message;
   67: 
   68: 
   69: sub ssi_with_retries {
   70:     my ($resource, $retries, %form) = @_;
   71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   72:     if ($response->is_error) {
   73: 	$ssi_error          = 1;
   74: 	$ssi_error_resource = $resource;
   75: 	$ssi_error_message  = $response->code . " " . $response->message;
   76:     }
   77: 
   78:     return $content;
   79: 
   80: }
   81: #
   82: #  Prodcuces an ssi retry failure error message to the user:
   83: #
   84: 
   85: sub ssi_print_error {
   86:     my ($r) = @_;
   87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   88:     $r->print('
   89: <br />
   90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   91: <p>
   92: '.&mt('Unable to retrieve a resource from a server:').'<br />
   93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   94: '.&mt('Error:').' '.$ssi_error_message.'
   95: </p>
   96: <p>'.
   97: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   99: '</p>');
  100:     return;
  101: }
  102: 
  103: #
  104: # --- Retrieve the parts from the metadata file.---
  105: # Returns an array of everything that the resources stores away
  106: #
  107: 
  108: sub getpartlist {
  109:     my ($symb,$errorref) = @_;
  110: 
  111:     my $navmap   = Apache::lonnavmaps::navmap->new();
  112:     unless (ref($navmap)) {
  113:         if (ref($errorref)) { 
  114:             $$errorref = 'navmap';
  115:             return;
  116:         }
  117:     }
  118:     my $res      = $navmap->getBySymb($symb);
  119:     my $partlist = $res->parts();
  120:     my $url      = $res->src();
  121:     my $toolsymb;
  122:     if ($url =~ /ext\.tool$/) {
  123:         $toolsymb = $symb;
  124:     }
  125:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  126: 
  127:     my @stores;
  128:     foreach my $part (@{ $partlist }) {
  129: 	foreach my $key (@metakeys) {
  130: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  131: 	}
  132:     }
  133:     return @stores;
  134: }
  135: 
  136: #--- Format fullname, username:domain if different for display
  137: #--- Use anywhere where the student names are listed
  138: sub nameUserString {
  139:     my ($type,$fullname,$uname,$udom) = @_;
  140:     if ($type eq 'header') {
  141: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  142:     } else {
  143: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  144: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  145:     }
  146: }
  147: 
  148: #--- Get the partlist and the response type for a given problem. ---
  149: #--- Indicate if a response type is coded handgraded or not. ---
  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("<\\/td><\\/tr><\\/table>&nbsp;");
 1803:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1804:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1805:     pDoc.write("<\\/form>");
 1806:     pDoc.write('$end_page_msg_central');
 1807:     pDoc.close();
 1808: }
 1809: 
 1810: SUBJAVASCRIPT
 1811: }
 1812: 
 1813: #--- javascript for essay type problem --
 1814: sub sub_page_kw_js {
 1815:     my $request = shift;
 1816: 
 1817:     unless ($env{'form.compmsg'}) {
 1818:         &commonJSfunctions($request);
 1819:     }
 1820: 
 1821:     my $inner_js_highlight_central= (<<INNERJS);
 1822: <script type="text/javascript">
 1823:     function updateChoice(flag) {
 1824:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1825:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1826:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1827:       opener.document.SCORE.refresh.value = "on";
 1828:       if (opener.document.SCORE.keywords.value!=""){
 1829:          opener.document.SCORE.submit();
 1830:       }
 1831:       self.close()
 1832:     }
 1833: </script>
 1834: INNERJS
 1835: 
 1836:     my $start_page_highlight_central =
 1837:         &Apache::loncommon::start_page('Highlight Central',
 1838:                                        $inner_js_highlight_central,
 1839:                                        {'js_ready'  => 1,
 1840:                                         'only_body' => 1,
 1841:                                         'bgcolor'   =>'#FFFFFF',});
 1842:     my $end_page_highlight_central =
 1843:         &Apache::loncommon::end_page({'js_ready' => 1});
 1844: 
 1845:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1846:     $docopen=~s/^document\.//;
 1847: 
 1848:     my %js_lt = &Apache::lonlocal::texthash(
 1849:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1850:                 plse => 'Please select a word or group of words from document and then click this link.',
 1851:                 adds => 'Add selection to keyword list? Edit if desired.',
 1852:                 col1 => 'red',
 1853:                 col2 => 'green',
 1854:                 col3 => 'blue',
 1855:                 siz1 => 'normal',
 1856:                 siz2 => '+1',
 1857:                 siz3 => '+2',
 1858:                 sty1 => 'normal',
 1859:                 sty2 => 'italic',
 1860:                 sty3 => 'bold',
 1861:              );
 1862:     my %html_js_lt = &Apache::lonlocal::texthash(
 1863:                 save => 'Save',
 1864:                 canc => 'Cancel',
 1865:                 kehi => 'Keyword Highlight Options',
 1866:                 txtc => 'Text Color',
 1867:                 font => 'Font Size',
 1868:                 fnst => 'Font Style',
 1869:              );
 1870:     &js_escape(\%js_lt);
 1871:     &html_escape(\%html_js_lt);
 1872:     &js_escape(\%html_js_lt);
 1873:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1874: 
 1875: //===================== Show list of keywords ====================
 1876:   function keywords(formname) {
 1877:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1878:     if (nret==null) return;
 1879:     formname.keywords.value = nret;
 1880: 
 1881:     if (formname.keywords.value != "") {
 1882:         formname.refresh.value = "on";
 1883:         formname.submit();
 1884:     }
 1885:     return;
 1886:   }
 1887: 
 1888: //===================== Script to add keyword(s) ==================
 1889:   function getSel() {
 1890:     if (document.getSelection) txt = document.getSelection();
 1891:     else if (document.selection) txt = document.selection.createRange().text;
 1892:     else return;
 1893:     if (typeof(txt) != 'string') {
 1894:         txt = String(txt);
 1895:     }
 1896:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1897:     if (cleantxt=="") {
 1898:         alert("$js_lt{'plse'}");
 1899:         return;
 1900:     }
 1901:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1902:     if (nret==null) return;
 1903:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1904:     if (document.SCORE.keywords.value != "") {
 1905:         document.SCORE.refresh.value = "on";
 1906:         document.SCORE.submit();
 1907:     }
 1908:     return;
 1909:   }
 1910: 
 1911: //====================== Script for keyword highlight options ==============
 1912:   function kwhighlight() {
 1913:     var kwclr    = document.SCORE.kwclr.value;
 1914:     var kwsize   = document.SCORE.kwsize.value;
 1915:     var kwstyle  = document.SCORE.kwstyle.value;
 1916:     var redsel = "";
 1917:     var grnsel = "";
 1918:     var blusel = "";
 1919:     var txtcol1 = "$js_lt{'col1'}";
 1920:     var txtcol2 = "$js_lt{'col2'}";
 1921:     var txtcol3 = "$js_lt{'col3'}";
 1922:     var txtsiz1 = "$js_lt{'siz1'}";
 1923:     var txtsiz2 = "$js_lt{'siz2'}";
 1924:     var txtsiz3 = "$js_lt{'siz3'}";
 1925:     var txtsty1 = "$js_lt{'sty1'}";
 1926:     var txtsty2 = "$js_lt{'sty2'}";
 1927:     var txtsty3 = "$js_lt{'sty3'}";
 1928:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1929:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1930:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1931:     var sznsel = "";
 1932:     var sz1sel = "";
 1933:     var sz2sel = "";
 1934:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1935:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1936:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1937:     var synsel = "";
 1938:     var syisel = "";
 1939:     var sybsel = "";
 1940:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1941:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1942:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1943:     highlightCentral();
 1944:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1945:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1946:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1947:     highlightend();
 1948:     return;
 1949:   }
 1950: 
 1951:   function highlightCentral() {
 1952: //    if (window.hwdWin) window.hwdWin.close();
 1953:     var xpos = (screen.width-400)/2;
 1954:     xpos = (xpos < 0) ? '0' : xpos;
 1955:     var ypos = (screen.height-330)/2-30;
 1956:     ypos = (ypos < 0) ? '0' : ypos;
 1957: 
 1958:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1959:     hwdWin.focus();
 1960:     var hDoc = hwdWin.document;
 1961:     hDoc.$docopen;
 1962:     hDoc.write('$start_page_highlight_central');
 1963:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1964:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1965: 
 1966:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1967:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1968:   }
 1969: 
 1970:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1971:     var hDoc = hwdWin.document;
 1972:     hDoc.write("<tr>");
 1973:     hDoc.write("<td align=\\"left\\">");
 1974:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1975:     hDoc.write("<td align=\\"left\\">");
 1976:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1977:     hDoc.write("<td align=\\"left\\">");
 1978:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1979:     hDoc.write("<\\/tr>");
 1980:   }
 1981: 
 1982:   function highlightend() { 
 1983:     var hDoc = hwdWin.document;
 1984:     hDoc.write("<\\/table><br \\/>");
 1985:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1986:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1987:     hDoc.write("<\\/form>");
 1988:     hDoc.write('$end_page_highlight_central');
 1989:     hDoc.close();
 1990:   }
 1991: 
 1992: SUBJAVASCRIPT
 1993: }
 1994: 
 1995: sub get_increment {
 1996:     my $increment = $env{'form.increment'};
 1997:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1998:         $increment != .1) {
 1999:         $increment = 1;
 2000:     }
 2001:     return $increment;
 2002: }
 2003: 
 2004: sub gradeBox_start {
 2005:     return (
 2006:         &Apache::loncommon::start_data_table()
 2007:        .&Apache::loncommon::start_data_table_header_row()
 2008:        .'<th>'.&mt('Part').'</th>'
 2009:        .'<th>'.&mt('Points').'</th>'
 2010:        .'<th>&nbsp;</th>'
 2011:        .'<th>'.&mt('Assign Grade').'</th>'
 2012:        .'<th>'.&mt('Weight').'</th>'
 2013:        .'<th>'.&mt('Grade Status').'</th>'
 2014:        .&Apache::loncommon::end_data_table_header_row()
 2015:     );
 2016: }
 2017: 
 2018: sub gradeBox_end {
 2019:     return (
 2020:         &Apache::loncommon::end_data_table()
 2021:     );
 2022: }
 2023: #--- displays the grading box, used in essay type problem and grading by page/sequence
 2024: sub gradeBox {
 2025:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 2026:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2027: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2028:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2029:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2030:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2031:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2032:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2033: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2034:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2035:     my $display_part= &get_display_part($partid,$symb);
 2036:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2037: 				       [$partid]);
 2038:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2039:     if ($last_resets{$partid}) {
 2040:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2041:     }
 2042:     my $result=&Apache::loncommon::start_data_table_row();
 2043:     my $ctr = 0;
 2044:     my $thisweight = 0;
 2045:     my $increment = &get_increment();
 2046: 
 2047:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2048:     while ($thisweight<=$wgt) {
 2049: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2050:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2051: 	    $thisweight.')" value="'.$thisweight.'" '.
 2052: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2053: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2054:         $thisweight += $increment;
 2055: 	$ctr++;
 2056:     }
 2057:     $radio.='</tr></table>';
 2058: 
 2059:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2060: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2061: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2062: 	$wgt.')" /></td>'."\n";
 2063:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2064: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2065: 	' </td>'."\n";
 2066:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2067: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2068:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2069: 	$line.='<option></option>'.
 2070: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2071:     } else {
 2072: 	$line.='<option selected="selected"></option>'.
 2073: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2074:     }
 2075:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2076: 
 2077: 
 2078:     $result .= 
 2079: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2080:     $result.=&Apache::loncommon::end_data_table_row();
 2081:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2082:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2083: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2084: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2085: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2086:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2087:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2088:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2089:         $aggtries.'" />'."\n";
 2090:     my $res_error;
 2091:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2092:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2093:     if ($res_error) {
 2094:         return &navmap_errormsg();
 2095:     }
 2096:     return $result;
 2097: }
 2098: 
 2099: sub handback_box {
 2100:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2101:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2102:     return unless ($numessay);
 2103:     my (@respids);
 2104:     my @part_response_id = &flatten_responseType($responseType);
 2105:     foreach my $part_response_id (@part_response_id) {
 2106:     	my ($part,$resp) = @{ $part_response_id };
 2107:         if ($part eq $partid) {
 2108:             push(@respids,$resp);
 2109:         }
 2110:     }
 2111:     my $result;
 2112:     foreach my $respid (@respids) {
 2113: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2114: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2115: 	next if (!@$files);
 2116: 	my $file_counter = 0;
 2117: 	foreach my $file (@$files) {
 2118: 	    if ($file =~ /\/portfolio\//) {
 2119:                 $file_counter++;
 2120:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2121:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 2122:     	        $file_disp = "$name.$ext";
 2123:     	        $file = $file_path.$file_disp;
 2124:     	        $result.=&mt('Return commented version of [_1] to student.',
 2125:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2126:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2127:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2128: 	    }
 2129: 	}
 2130:         if ($file_counter) {
 2131:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2132:                        '<span class="LC_info">'.
 2133:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2134:         }
 2135:     }
 2136:     return $result;    
 2137: }
 2138: 
 2139: sub show_problem {
 2140:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2141:     my $rendered;
 2142:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2143:     &Apache::lonxml::remember_problem_counter();
 2144:     if ($mode eq 'both' or $mode eq 'text') {
 2145: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2146: 						       $env{'request.course.id'},
 2147: 						       undef,\%form);
 2148:     }
 2149:     if ($removeform) {
 2150: 	$rendered=~s|<form(.*?)>||g;
 2151: 	$rendered=~s|</form>||g;
 2152: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2153:     }
 2154:     my $companswer;
 2155:     if ($mode eq 'both' or $mode eq 'answer') {
 2156: 	&Apache::lonxml::restore_problem_counter();
 2157: 	$companswer=
 2158: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2159: 						    $env{'request.course.id'},
 2160: 						    %form);
 2161:     }
 2162:     if ($removeform) {
 2163: 	$companswer=~s|<form(.*?)>||g;
 2164: 	$companswer=~s|</form>||g;
 2165: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2166:     }
 2167:     my $renderheading = &mt('View of the problem');
 2168:     my $answerheading = &mt('Correct answer');
 2169:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2170:         my $stu_fullname = $env{'form.fullname'};
 2171:         if ($stu_fullname eq '') {
 2172:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2173:         }
 2174:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2175:         if ($forwhom ne '') {
 2176:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2177:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2178:         }
 2179:     }
 2180:     $rendered=
 2181:         '<div class="LC_Box">'
 2182:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2183:        .$rendered
 2184:        .'</div>';
 2185:     $companswer=
 2186:         '<div class="LC_Box">'
 2187:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2188:        .$companswer
 2189:        .'</div>';
 2190:     my $result;
 2191:     if ($mode eq 'both') {
 2192:         $result=$rendered.$companswer;
 2193:     } elsif ($mode eq 'text') {
 2194:         $result=$rendered;
 2195:     } elsif ($mode eq 'answer') {
 2196:         $result=$companswer;
 2197:     }
 2198:     return $result;
 2199: }
 2200: 
 2201: sub files_exist {
 2202:     my ($r, $symb) = @_;
 2203:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2204:     foreach my $student (@students) {
 2205:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2206:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2207: 					      $udom,$uname);
 2208:         my ($string)= &get_last_submission(\%record);
 2209:         foreach my $submission (@$string) {
 2210:             my ($partid,$respid) =
 2211: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2212:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2213: 					   \%record);
 2214:             return 1 if (@$files);
 2215:         }
 2216:     }
 2217:     return 0;
 2218: }
 2219: 
 2220: sub download_all_link {
 2221:     my ($r,$symb) = @_;
 2222:     unless (&files_exist($r, $symb)) {
 2223:         $r->print(&mt('There are currently no submitted documents.'));
 2224:         return;
 2225:     }
 2226:     my $all_students = 
 2227: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2228: 
 2229:     my $parts =
 2230: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2231: 
 2232:     my $identifier = &Apache::loncommon::get_cgi_id();
 2233:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2234:                              'cgi.'.$identifier.'.symb' => $symb,
 2235:                              'cgi.'.$identifier.'.parts' => $parts,});
 2236:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2237: 	      &mt('Download All Submitted Documents').'</a>');
 2238:     return;
 2239: }
 2240: 
 2241: sub submit_download_link {
 2242:     my ($request,$symb) = @_;
 2243:     if (!$symb) { return ''; }
 2244:     my $res_error;
 2245:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2246:         &response_type($symb,\$res_error);
 2247:     if ($res_error) {
 2248:         $request->print(&mt('An error occurred retrieving response types'));
 2249:         return;
 2250:     }
 2251:     unless ($numessay) {
 2252:         $request->print(&mt('No essayresponse items found'));
 2253:         return;
 2254:     }
 2255:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2256:     if (@chosenparts) {
 2257:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2258:                                           undef,undef,1));
 2259:     }
 2260:     if ($numessay) {
 2261:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2262:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2263:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2264:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2265:         if (ref($fullname) eq 'HASH') {
 2266:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2267:             if (@students) {
 2268:                 @{$env{'form.stuinfo'}} = @students;
 2269:                 if ($numdropbox) {
 2270:                     &download_all_link($request,$symb);
 2271:                 } else {
 2272:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2273:                 }
 2274: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2275: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2276:             } else {
 2277:                 $request->print(&mt('No students match the criteria you selected'));
 2278:             }
 2279:         } else {
 2280:             $request->print(&mt('Could not retrieve student information'));
 2281:         }
 2282:     } else {
 2283:         $request->print(&mt('No essayresponse items found'));
 2284:     }
 2285:     return;
 2286: }
 2287: 
 2288: sub build_section_inputs {
 2289:     my $section_inputs;
 2290:     if ($env{'form.section'} eq '') {
 2291:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2292:     } else {
 2293:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2294:         foreach my $section (@sections) {
 2295:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2296:         }
 2297:     }
 2298:     return $section_inputs;
 2299: }
 2300: 
 2301: # --------------------------- show submissions of a student, option to grade 
 2302: sub submission {
 2303:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2304:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2305:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2306:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2307:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2308: 
 2309:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2310:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2311:     my $is_tool = ($symb =~ /ext\.tool$/);
 2312:     my ($essayurl,%coursedesc_by_cid);
 2313: 
 2314:     if (!&canview($usec)) {
 2315:         $request->print(
 2316:             '<span class="LC_warning">'.
 2317:             &mt('Unable to view requested student.').
 2318:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2319:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2320:             '</span>');
 2321: 	return;
 2322:     }
 2323: 
 2324:     my $res_error;
 2325:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2326:         &response_type($symb,\$res_error);
 2327:     if ($res_error) {
 2328:         $request->print(&navmap_errormsg());
 2329:         return;
 2330:     }
 2331: 
 2332:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2333:     unless ($is_tool) {
 2334:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2335:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2336:     }
 2337:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2338:         $env{'form.compmsg'} = 1;
 2339:     }
 2340:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2341:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2342: 	'" src="'.$request->dir_config('lonIconsURL').
 2343: 	'/check.gif" height="16" border="0" />';
 2344: 
 2345:     # header info
 2346:     if ($counter == 0) {
 2347:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2348:         if (@chosenparts) {
 2349:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2350:         } elsif ($divforres) {
 2351:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2352:         } else {
 2353:             $request->print('<br clear="all" />');
 2354:         }
 2355: 	&sub_page_js($request);
 2356:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2357: 	&sub_page_kw_js($request) if ($numessay);
 2358: 
 2359: 	# option to display problem, only once else it cause problems 
 2360:         # with the form later since the problem has a form.
 2361: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2362: 	    my $mode;
 2363: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2364: 		$mode='both';
 2365: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2366: 		$mode='text';
 2367: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2368: 		$mode='answer';
 2369: 	    }
 2370: 	    &Apache::lonxml::clear_problem_counter();
 2371: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2372: 	}
 2373: 
 2374: 	my %keyhash = ();
 2375: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2376: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2377: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2378: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2379: 	}
 2380: 	# kwclr is the only variable that is guaranteed not to be blank
 2381: 	# if this subroutine has been called once.
 2382: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2383: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2384: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2385: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2386: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2387: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2388: 	}
 2389: 	if ($env{'form.compmsg'}) {
 2390: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2391: 		$keyhash{$symb.'_subject'} : $probtitle;
 2392: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2393: 	}
 2394: 
 2395: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2396: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2397: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2398: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2399: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2400: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2401: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2402: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2403: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2404: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2405: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2406: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2407: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2408: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2409: 			&build_section_inputs().
 2410: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2411: 			'<input type="hidden" name="NCT"'.
 2412: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2413: 	if ($env{'form.compmsg'}) {
 2414: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2415: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2416: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2417: 	}
 2418: 	if ($numessay) {
 2419: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2420: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2421: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2422: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2423: 	}
 2424: 
 2425: 	my ($cts,$prnmsg) = (1,'');
 2426: 	while ($cts <= $env{'form.savemsgN'}) {
 2427: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2428: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2429: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2430: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2431: 		'" />'."\n".
 2432: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2433: 	    $cts++;
 2434: 	}
 2435: 	$request->print($prnmsg);
 2436: 
 2437: 	if ($numessay) {
 2438: 
 2439:             my %lt = &Apache::lonlocal::texthash(
 2440:                           keyh => 'Keyword Highlighting for Essays',
 2441:                           keyw => 'Keyword Options',
 2442:                           list => 'List',
 2443:                           past => 'Paste Selection to List',
 2444:                           high => 'Highlight Attribute',
 2445:                      );
 2446: #
 2447: # Print out the keyword options line
 2448: #
 2449: 	    $request->print(
 2450:                 '<div class="LC_columnSection">'
 2451:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2452:                .&Apache::lonhtmlcommon::funclist_from_array(
 2453:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2454:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2455:  class="page">'.$lt{'past'}.'</a>',
 2456:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2457:                     {legend => $lt{'keyw'}})
 2458:                .'</fieldset></div>'
 2459:             );
 2460: 
 2461: #
 2462: # Load the other essays for similarity check
 2463: #
 2464:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2465:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2466:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2467:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2468:                 if ($cdom ne '' && $cnum ne '') {
 2469:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2470:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2471:                         my $apath = $1.'_'.$id;
 2472:                         $apath=~s/\W/\_/gs;
 2473:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2474:                     }
 2475:                 }
 2476:             } else {
 2477: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2478: 	        $apath=&escape($apath);
 2479: 	        $apath=~s/\W/\_/gs;
 2480:                 &init_old_essays($symb,$apath,$adom,$aname);
 2481:             }
 2482:         }
 2483:     }
 2484: 
 2485: # This is where output for one specific student would start
 2486:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2487:     $request->print(
 2488:         "\n\n"
 2489:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2490:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2491:        ."\n"
 2492:     );
 2493: 
 2494:     # Show additional functions if allowed
 2495:     if ($perm{'vgr'}) {
 2496:         $request->print(
 2497:             &Apache::loncommon::track_student_link(
 2498:                 'View recent activity',
 2499:                 $uname,$udom,'check')
 2500:            .' '
 2501:         );
 2502:     }
 2503:     if ($perm{'opa'}) {
 2504:         $request->print(
 2505:             &Apache::loncommon::pprmlink(
 2506:                 &mt('Set/Change parameters'),
 2507:                 $uname,$udom,$symb,'check'));
 2508:     }
 2509: 
 2510:     # Show Problem
 2511:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2512: 	my $mode;
 2513: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2514: 	    $mode='both';
 2515: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2516: 	    $mode='text';
 2517: 	} elsif ($env{'form.vAns'} eq 'all') {
 2518: 	    $mode='answer';
 2519: 	}
 2520: 	&Apache::lonxml::clear_problem_counter();
 2521: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2522:     }
 2523: 
 2524:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2525: 
 2526:     # Display student info
 2527:     $request->print(($counter == 0 ? '' : '<br />'));
 2528: 
 2529:     my $boxtitle = &mt('Submissions');
 2530:     if ($is_tool) {
 2531:         $boxtitle = &mt('Transactions')
 2532:     }
 2533:     my $result='<div class="LC_Box">'
 2534:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2535:     $result.='<input type="hidden" name="name'.$counter.
 2536:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2537:     if (($numresp > $numessay) && !$is_tool) {
 2538:         $result.='<p class="LC_info">'
 2539:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2540:                 ."</p>\n";
 2541:     }
 2542: 
 2543:     # If any part of the problem is an essayresponse, then check for collaborators
 2544:     my $fullname;
 2545:     my $col_fullnames = [];
 2546:     if ($numessay) {
 2547: 	(my $sub_result,$fullname,$col_fullnames)=
 2548: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2549: 				 $counter);
 2550: 	$result.=$sub_result;
 2551:     }
 2552:     $request->print($result."\n");
 2553: 
 2554:     # print student answer/submission
 2555:     # Options are (1) Last submission only
 2556:     #             (2) Last submission (with detailed information for that submission)
 2557:     #             (3) All transactions (by date)
 2558:     #             (4) The whole record (with detailed information for all transactions)
 2559: 
 2560:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) = &get_last_submission(\%record,$is_tool);
 2561: 
 2562:     my $lastsubonly;
 2563: 
 2564:     if ($timestamp eq '') {
 2565:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>'; 
 2566:     } else {
 2567:         my ($shownsubmdate,$showngradedate);
 2568:         if ($lastsubmittime && $lastgradetime) {
 2569:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
 2570:             if ($lastgradetime > $lastsubmittime) {
 2571:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
 2572:              }
 2573:         } else {
 2574:             $shownsubmdate = $timestamp;
 2575:         }
 2576:         $lastsubonly =
 2577:             '<div class="LC_grade_submissions_body">'
 2578:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
 2579:         if ($showngradedate) {
 2580:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
 2581:         }
 2582: 
 2583: 	my %seenparts;
 2584: 	my @part_response_id = &flatten_responseType($responseType);
 2585: 	foreach my $part (@part_response_id) {
 2586: 	    my ($partid,$respid) = @{ $part };
 2587: 	    my $display_part=&get_display_part($partid,$symb);
 2588: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2589: 		if (exists($seenparts{$partid})) { next; }
 2590: 		$seenparts{$partid}=1;
 2591:                 $request->print(
 2592:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2593:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2594:                                '<a href="javascript:viewSubmitter(\''.
 2595:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2596:                                '\');" target="_self">'.
 2597:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2598:                     '<br />');
 2599: 		next;
 2600: 	    }
 2601: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2602: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2603:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2604:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2605:                     ' <span class="LC_internal_info">'.
 2606:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2607:                     '</span>&nbsp; &nbsp;'.
 2608: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2609: 		next;
 2610: 	    }
 2611: 	    foreach my $submission (@$string) {
 2612: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2613: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2614: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2615: 		# Similarity check
 2616:                 my $similar='';
 2617:                 my ($type,$trial,$rndseed);
 2618:                 if ($hide eq 'rand') {
 2619:                     $type = 'randomizetry';
 2620:                     $trial = $record{"resource.$partid.tries"};
 2621:                     $rndseed = $record{"resource.$partid.rndseed"};
 2622:                 }
 2623: 		if ($env{'form.checkPlag'}) {
 2624: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2625: 		        &most_similar($uname,$udom,$symb,$subval);
 2626: 		    if ($osim) {
 2627: 		        $osim=int($osim*100.0);
 2628:                         if ($hide eq 'anon') {
 2629:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2630:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2631:                         } else {
 2632: 			    $similar='<hr />';
 2633:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2634:                                 $similar .= '<h3><span class="LC_warning">'.
 2635:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2636:                                                 $osim,
 2637:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2638:                                             '</span></h3>';
 2639:                             } elsif ($ocrsid ne '') {
 2640:                                 my %old_course_desc;
 2641:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2642:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2643:                                 } else {
 2644:                                     my $args;
 2645:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2646:                                         $args = {'one_time' => 1};
 2647:                                     }
 2648:                                     %old_course_desc =
 2649:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2650:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2651:                                 }
 2652:                                 $similar .=
 2653:                                     '<h3><span class="LC_warning">'.
 2654: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2655: 				        $osim,
 2656: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2657: 				        $old_course_desc{'description'},
 2658: 				        $old_course_desc{'num'},
 2659: 				        $old_course_desc{'domain'}).
 2660: 				    '</span></h3>';
 2661:                             } else {
 2662:                                 $similar .=
 2663:                                     '<h3><span class="LC_warning">'.
 2664:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2665:                                         $osim,
 2666:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2667:                                     '</span></h3>';
 2668:                             }
 2669:                             $similar .= '<blockquote><i>'.
 2670:                                         &keywords_highlight($oessay).
 2671:                                         '</i></blockquote><hr />';
 2672: 		        }
 2673:                     }
 2674:                 }
 2675: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2676:                                      undef,$type,$trial,$rndseed);
 2677:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2678:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2679:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2680: 		    my $display_part=&get_display_part($partid,$symb);
 2681:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2682:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2683:                         ' <span class="LC_internal_info">'.
 2684:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2685:                         '</span>&nbsp; &nbsp;';
 2686: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2687: 		    if (@$files) {
 2688:                         if ($hide eq 'anon') {
 2689:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2690:                         } else {
 2691:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2692:                                          .'<br /><span class="LC_warning">';
 2693:                             if(@$files == 1) {
 2694:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2695:                             } else {
 2696:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2697:                             }
 2698:                             $lastsubonly .= '</span>';
 2699:                             foreach my $file (@$files) {
 2700:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2701:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2702:                             }
 2703:                         }
 2704: 			$lastsubonly.='<br />';
 2705: 		    }
 2706:                     if ($hide eq 'anon') {
 2707:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2708:                     } else {
 2709:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2710:                         if ($draft) {
 2711:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2712:                         }
 2713:                         $subval =
 2714: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2715: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2716:                         if ($responsetype eq 'essay') {
 2717:                             $subval =~ s{\n}{<br />}g;
 2718:                         }
 2719:                         $lastsubonly.=$subval."\n";
 2720:                     }
 2721:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2722: 		    $lastsubonly.='</div>';
 2723: 		}
 2724: 	    }
 2725: 	}
 2726: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2727:     }
 2728:     $request->print($lastsubonly);
 2729:     if ($env{'form.lastSub'} eq 'datesub') {
 2730:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2731: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2732:     }
 2733:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2734:         my $identifier = (&canmodify($usec)? $counter : '');
 2735: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2736: 								 $env{'request.course.id'},
 2737: 								 $last,'.submission',
 2738: 								 'Apache::grades::keywords_highlight',
 2739:                                                                  $usec,$identifier));
 2740:     }
 2741:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2742: 	.$udom.'" />'."\n");
 2743:     # return if view submission with no grading option
 2744:     if (!&canmodify($usec)) {
 2745:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2746:         return;
 2747:     } else {
 2748: 	$request->print('</div>'."\n");
 2749:     }
 2750: 
 2751:     # grading message center
 2752: 
 2753:     if ($env{'form.compmsg'}) {
 2754:         my $result='<div class="LC_Box">'.
 2755:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2756:                    '<div class="LC_grade_message_center_body">';
 2757:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2758:         my $msgfor = $givenn.' '.$lastname;
 2759:         if (scalar(@$col_fullnames) > 0) {
 2760:             my $lastone = pop(@$col_fullnames);
 2761:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2762:         }
 2763:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2764:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2765:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2766: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2767:                  ',\''.$msgfor.'\');" target="_self">'.
 2768:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2769:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2770:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2771:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2772:                  '<br />&nbsp;('.
 2773:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2774: 	         '</div></div>';
 2775:         $request->print($result);
 2776:     }
 2777: 
 2778:     my %seen = ();
 2779:     my @partlist;
 2780:     my @gradePartRespid;
 2781:     my @part_response_id;
 2782:     if ($is_tool) {
 2783:         @part_response_id = ([0,'']);
 2784:     } else {
 2785:         @part_response_id = &flatten_responseType($responseType);
 2786:     }
 2787:     $request->print(
 2788:         '<div class="LC_Box">'
 2789:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2790:     );
 2791:     $request->print(&gradeBox_start());
 2792:     foreach my $part_response_id (@part_response_id) {
 2793:     	my ($partid,$respid) = @{ $part_response_id };
 2794: 	my $part_resp = join('_',@{ $part_response_id });
 2795: 	next if ($seen{$partid} > 0);
 2796: 	$seen{$partid}++;
 2797: 	push(@partlist,$partid);
 2798: 	push(@gradePartRespid,$partid.'.'.$respid);
 2799: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2800:     }
 2801:     $request->print(&gradeBox_end()); # </div>
 2802:     $request->print('</div>');
 2803: 
 2804:     $request->print('<div class="LC_grade_info_links">');
 2805:     $request->print('</div>');
 2806: 
 2807:     $result='<input type="hidden" name="partlist'.$counter.
 2808: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2809:     $result.='<input type="hidden" name="gradePartRespid'.
 2810: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2811:     my $ctr = 0;
 2812:     while ($ctr < scalar(@partlist)) {
 2813: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2814: 	    $partlist[$ctr].'" />'."\n";
 2815: 	$ctr++;
 2816:     }
 2817:     $request->print($result.''."\n");
 2818: 
 2819: # Done with printing info for one student
 2820: 
 2821:     $request->print('</div>');#LC_grade_show_user
 2822: 
 2823: 
 2824:     # print end of form
 2825:     if ($counter == $total) {
 2826:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2827: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2828: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2829: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2830: 	my $ntstu ='<select name="NTSTU">'.
 2831: 	    '<option>1</option><option>2</option>'.
 2832: 	    '<option>3</option><option>5</option>'.
 2833: 	    '<option>7</option><option>10</option></select>'."\n";
 2834: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2835: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2836:         $endform.=&mt('[_1]student(s)',$ntstu);
 2837: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2838: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2839: 	    '<input type="button" value="'.&mt('Next').'" '.
 2840: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2841:         $endform.='<span class="LC_warning">'.
 2842:                   &mt('(Next and Previous (student) do not save the scores.)').
 2843:                   '</span>'."\n" ;
 2844:         $endform.="<input type='hidden' value='".&get_increment().
 2845:             "' name='increment' />";
 2846: 	$endform.='</td></tr></table></form>';
 2847: 	$request->print($endform);
 2848:     }
 2849:     return '';
 2850: }
 2851: 
 2852: sub check_collaborators {
 2853:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2854:     my ($result,@col_fullnames);
 2855:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2856:     foreach my $part (keys(%$handgrade)) {
 2857: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2858: 					'.maxcollaborators',
 2859: 					$symb,$udom,$uname);
 2860: 	next if ($ncol <= 0);
 2861: 	$part =~ s/\_/\./g;
 2862: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2863: 	my (@good_collaborators, @bad_collaborators);
 2864: 	foreach my $possible_collaborator
 2865: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2866: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2867: 	    next if ($possible_collaborator eq '');
 2868: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2869: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2870: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2871: 	    # Doing this grep allows 'fuzzy' specification
 2872: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2873: 			       keys(%$classlist));
 2874: 	    if (! scalar(@matches)) {
 2875: 		push(@bad_collaborators, $possible_collaborator);
 2876: 	    } else {
 2877: 		push(@good_collaborators, @matches);
 2878: 	    }
 2879: 	}
 2880: 	if (scalar(@good_collaborators) != 0) {
 2881: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2882: 	    foreach my $name (@good_collaborators) {
 2883: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2884: 		push(@col_fullnames, $givenn.' '.$lastname);
 2885: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2886: 	    }
 2887: 	    $result.='</ol><br />'."\n";
 2888: 	    my ($part)=split(/\./,$part);
 2889: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2890: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2891: 		"\n";
 2892: 	}
 2893: 	if (scalar(@bad_collaborators) > 0) {
 2894: 	    $result.='<div class="LC_warning">';
 2895: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2896: 	    $result .= '</div>';
 2897: 	}         
 2898: 	if (scalar(@bad_collaborators > $ncol)) {
 2899: 	    $result .= '<div class="LC_warning">';
 2900: 	    $result .= &mt('This student has submitted too many '.
 2901: 		'collaborators.  Maximum is [_1].',$ncol);
 2902: 	    $result .= '</div>';
 2903: 	}
 2904:     }
 2905:     return ($result,$fullname,\@col_fullnames);
 2906: }
 2907: 
 2908: #--- Retrieve the last submission for all the parts
 2909: sub get_last_submission {
 2910:     my ($returnhash,$is_tool)=@_;
 2911:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
 2912:     if ($$returnhash{'version'}) {
 2913: 	my %lasthash=();
 2914:         my %prevsolved=();
 2915:         my %solved=();
 2916: 	my $version;
 2917: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2918:             my %handgraded = ();
 2919: 	    foreach my $key (sort(split(/\:/,
 2920: 					$$returnhash{$version.':keys'}))) {
 2921: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2922:                 if ($key =~ /\.([^.]+)\.regrader$/) {
 2923:                     $handgraded{$1} = 1;
 2924:                 } elsif ($key =~ /\.portfiles$/) {
 2925:                     if (($$returnhash{$version.':'.$key} ne '') &&
 2926:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
 2927:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2928:                     }
 2929:                 } elsif ($key =~ /\.submission$/) {
 2930:                     if ($$returnhash{$version.':'.$key} ne '') {
 2931:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2932:                     }
 2933:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
 2934:                     $prevsolved{$1} = $solved{$1};
 2935:                     $solved{$1} = $lasthash{$key};
 2936:                 }
 2937:             }
 2938:             foreach my $partid (keys(%handgraded)) {
 2939:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
 2940:                     (($solved{$partid} eq 'incorrect_by_override') ||
 2941:                      ($solved{$partid} eq 'correct_by_override'))) {
 2942:                     $lastgradetime = $$returnhash{$version.':timestamp'};
 2943:                 }
 2944:                 if ($solved{$partid} ne '') {
 2945:                     $prevsolved{$partid} = $solved{$partid};
 2946:                 }
 2947:             }
 2948: 	    $timestamp = 
 2949: 		&Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2950: 	}
 2951:         my (%typeparts,%randombytry);
 2952:         my $showsurv = 
 2953:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2954:         foreach my $key (sort(keys(%lasthash))) {
 2955:             if ($key =~ /\.type$/) {
 2956:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2957:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2958:                     ($lasthash{$key} eq 'randomizetry')) {
 2959:                     my ($ign,@parts) = split(/\./,$key);
 2960:                     pop(@parts);
 2961:                     my $id = join('.',@parts);
 2962:                     if ($lasthash{$key} eq 'randomizetry') {
 2963:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2964:                     } else {
 2965:                         unless ($showsurv) {
 2966:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2967:                         }
 2968:                     }
 2969:                     delete($lasthash{$key});
 2970:                 }
 2971:             }
 2972:         }
 2973:         my @hidden = keys(%typeparts);
 2974:         my @randomize = keys(%randombytry);
 2975: 	foreach my $key (keys(%lasthash)) {
 2976: 	    next if ($key !~ /\.submission$/);
 2977:             my $hide;
 2978:             if (@hidden) {
 2979:                 foreach my $id (@hidden) {
 2980:                     if ($key =~ /^\Q$id\E/) {
 2981:                         $hide = 'anon';
 2982:                         last;
 2983:                     }
 2984:                 }
 2985:             }
 2986:             unless ($hide) {
 2987:                 if (@randomize) {
 2988:                     foreach my $id (@randomize) {
 2989:                         if ($key =~ /^\Q$id\E/) {
 2990:                             $hide = 'rand';
 2991:                             last;
 2992:                         }
 2993:                     }
 2994:                 }
 2995:             }
 2996: 	    my ($partid,$foo) = split(/submission$/,$key);
 2997: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2998:             push(@string, join(':', $key, $hide, $draft, (
 2999:                 ref($lasthash{$key}) eq 'ARRAY' ?
 3000:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 3001: 	}
 3002:     }
 3003:     if (!@string) {
 3004:         my $msg;
 3005:         if ($is_tool) {
 3006:             $msg = &mt('No grade passed back.');
 3007:         } else {
 3008:             $msg = &mt('Nothing submitted - no attempts.');
 3009:         }
 3010: 	$string[0] =
 3011: 	    '<span class="LC_warning">'.$msg.'</span>';
 3012:     }
 3013:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
 3014: }
 3015: 
 3016: #--- High light keywords, with style choosen by user.
 3017: sub keywords_highlight {
 3018:     my $string    = shift;
 3019:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 3020:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 3021:     (my $styleoff = $styleon) =~ s/\</\<\//;
 3022:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 3023:     foreach my $keyword (@keylist) {
 3024: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 3025:     }
 3026:     return $string;
 3027: }
 3028: 
 3029: # For Tasks provide a mechanism to display previous version for one specific student
 3030: 
 3031: sub show_previous_task_version {
 3032:     my ($request,$symb) = @_;
 3033:     if ($symb eq '') {
 3034:         $request->print(
 3035:             '<span class="LC_error">'.
 3036:             &mt('Unable to handle ambiguous references.').
 3037:             '</span>');
 3038:         return '';
 3039:     }
 3040:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 3041:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 3042:     if (!&canview($usec)) {
 3043:         $request->print('<span class="LC_warning">'.
 3044:                         &mt('Unable to view previous version for requested student.').
 3045:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 3046:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3047:                         '</span>');
 3048:         return;
 3049:     }
 3050:     my $mode = 'both';
 3051:     my $isTask = ($symb =~/\.task$/);
 3052:     if ($isTask) {
 3053:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3054:             if ($env{'form.fullname'} eq '') {
 3055:                 $env{'form.fullname'} =
 3056:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3057:             }
 3058:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3059:             $request->print("\n\n".
 3060:                             '<div class="LC_grade_show_user">'.
 3061:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3062:                             '</h2>'."\n");
 3063:             &Apache::lonxml::clear_problem_counter();
 3064:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3065:                             {'previousversion' => $env{'form.previousversion'} }));
 3066:             $request->print("\n</div>");
 3067:         }
 3068:     }
 3069:     return;
 3070: }
 3071: 
 3072: sub choose_task_version_form {
 3073:     my ($symb,$uname,$udom,$nomenu) = @_;
 3074:     my $isTask = ($symb =~/\.task$/);
 3075:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3076:     if ($isTask) {
 3077:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3078:                                               $udom,$uname);
 3079:         if (($record{'resource.0.version'} eq '') ||
 3080:             ($record{'resource.0.version'} < 2)) {
 3081:             return ($record{'resource.0.version'},
 3082:                     $record{'resource.0.version'},$result,$js);
 3083:         } else {
 3084:             $current = $record{'resource.0.version'};
 3085:         }
 3086:         if ($env{'form.previousversion'}) {
 3087:             $displayed = $env{'form.previousversion'};
 3088:             $rowtitle = &mt('Choose another version:')
 3089:         } else {
 3090:             $displayed = $current;
 3091:             $rowtitle = &mt('Show earlier version:');
 3092:         }
 3093:         $result = '<div class="LC_left_float">';
 3094:         my $list;
 3095:         my $numversions = 0;
 3096:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3097:             if ($i == $current) {
 3098:                 if (!$env{'form.previousversion'} || $nomenu) {
 3099:                     next;
 3100:                 } else {
 3101:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3102:                     $numversions ++;
 3103:                 }
 3104:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3105:                 unless ($i == $env{'form.previousversion'}) {
 3106:                     $numversions ++;
 3107:                 }
 3108:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3109:             }
 3110:         }
 3111:         if ($numversions) {
 3112:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3113:             $result .=
 3114:                 '<form name="getprev" method="post" action=""'.
 3115:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3116:                 &Apache::loncommon::start_data_table().
 3117:                 &Apache::loncommon::start_data_table_row().
 3118:                 '<th align="left">'.$rowtitle.'</th>'.
 3119:                 '<td><select name="version">'.
 3120:                 '<option>'.&mt('Select').'</option>'.
 3121:                 $list.
 3122:                 '</select></td>'.
 3123:                 &Apache::loncommon::end_data_table_row();
 3124:             unless ($nomenu) {
 3125:                 $result .= &Apache::loncommon::start_data_table_row().
 3126:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3127:                 '<td><span class="LC_nobreak">'.
 3128:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3129:                 &mt('Yes').'</label>'.
 3130:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3131:                 '</span></td>'.
 3132:                 &Apache::loncommon::end_data_table_row();
 3133:             }
 3134:             $result .=
 3135:                 &Apache::loncommon::start_data_table_row().
 3136:                 '<th align="left">&nbsp;</th>'.
 3137:                 '<td>'.
 3138:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3139:                 '</td>'.
 3140:                 &Apache::loncommon::end_data_table_row().
 3141:                 &Apache::loncommon::end_data_table().
 3142:                 '</form>';
 3143:             $js = &previous_display_javascript($nomenu,$current);
 3144:         } elsif ($displayed && $nomenu) {
 3145:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3146:         } else {
 3147:             $result .= &mt('No previous versions to show for this student');
 3148:         }
 3149:         $result .= '</div>';
 3150:     }
 3151:     return ($current,$displayed,$result,$js);
 3152: }
 3153: 
 3154: sub previous_display_javascript {
 3155:     my ($nomenu,$current) = @_;
 3156:     my $js = <<"JSONE";
 3157: <script type="text/javascript">
 3158: // <![CDATA[
 3159: function previousVersion(uname,udom,symb) {
 3160:     var current = '$current';
 3161:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3162:     var prevstr = new RegExp("^\\\\d+\$");
 3163:     if (!prevstr.test(version)) {
 3164:         return false;
 3165:     }
 3166:     var url = '';
 3167:     if (version == current) {
 3168:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3169:     } else {
 3170:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3171:     }
 3172: JSONE
 3173:     if ($nomenu) {
 3174:         $js .= <<"JSTWO";
 3175:     document.location.href = url;
 3176: JSTWO
 3177:     } else {
 3178:         $js .= <<"JSTHREE";
 3179:     var newwin = 0;
 3180:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3181:         if (document.getprev.prevwin[i].checked == true) {
 3182:             newwin = document.getprev.prevwin[i].value;
 3183:         }
 3184:     }
 3185:     if (newwin == 1) {
 3186:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3187:         url = url+'&inhibitmenu=yes';
 3188:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3189:             previousWin = window.open(url,'',options,1);
 3190:         } else {
 3191:             previousWin.location.href = url;
 3192:         }
 3193:         previousWin.focus();
 3194:         return false;
 3195:     } else {
 3196:         document.location.href = url;
 3197:         return false;
 3198:     }
 3199: JSTHREE
 3200:     }
 3201:     $js .= <<"ENDJS";
 3202:     return false;
 3203: }
 3204: // ]]>
 3205: </script>
 3206: ENDJS
 3207: 
 3208: }
 3209: 
 3210: #--- Called from submission routine
 3211: sub processHandGrade {
 3212:     my ($request,$symb) = @_;
 3213:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3214:     my $button = $env{'form.gradeOpt'};
 3215:     my $ngrade = $env{'form.NCT'};
 3216:     my $ntstu  = $env{'form.NTSTU'};
 3217:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3218:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3219:     my ($res_error,%queueable);
 3220:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3221:     if ($res_error) {
 3222:         $request->print(&navmap_errormsg());
 3223:         return;
 3224:     } else {
 3225:         foreach my $part (@{$partlist}) {
 3226:             if (ref($responseType->{$part}) eq 'HASH') {
 3227:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3228:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3229:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3230:                         $queueable{$part} = 1;
 3231:                         last;
 3232:                     }
 3233:                 }
 3234:             }
 3235:         }
 3236:     }
 3237: 
 3238:     if ($button eq 'Save & Next') {
 3239: 	my $ctr = 0;
 3240: 	while ($ctr < $ngrade) {
 3241: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3242: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3243:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3244: 	    if ($errorflag eq 'no_score') {
 3245: 		$ctr++;
 3246: 		next;
 3247: 	    }
 3248: 	    if ($errorflag eq 'not_allowed') {
 3249:                 $request->print(
 3250:                     '<span class="LC_error">'
 3251:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3252:                    .'</span>');
 3253: 		$ctr++;
 3254: 		next;
 3255: 	    }
 3256:             if ($numhidden) {
 3257:                 $request->print(
 3258:                     '<span class="LC_info">'
 3259:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3260:                    .'</span><br />');
 3261:             }
 3262: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3263: 	    my ($subject,$message,$msgstatus) = ('','','');
 3264: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3265:             my ($feedurl,$showsymb) =
 3266: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3267: 	    my $messagetail;
 3268: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3269: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3270: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3271: 		$subject.=' ['.$restitle.']';
 3272: 		my (@msgnum) = split(/,/,$includemsg);
 3273: 		foreach (@msgnum) {
 3274: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3275: 		}
 3276: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3277: 		if ($env{'form.withgrades'.$ctr}) {
 3278: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3279: 		    $messagetail = " for <a href=\"".
 3280: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3281: 		}
 3282: 		$msgstatus = 
 3283:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3284: 						     $message.$messagetail,
 3285:                                                      undef,$feedurl,undef,
 3286:                                                      undef,undef,$showsymb,
 3287:                                                      $restitle);
 3288: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3289: 				$msgstatus.'<br />');
 3290: 	    }
 3291: 	    if ($env{'form.collaborator'.$ctr}) {
 3292: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3293: 		foreach my $collabstr (@collabstrs) {
 3294: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3295: 		    foreach my $collaborator (@collaborators) {
 3296: 			my ($errorflag,$pts,$wgt) = 
 3297: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3298: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3299: 			if ($errorflag eq 'not_allowed') {
 3300: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3301: 			    next;
 3302: 			} elsif ($message ne '') {
 3303: 			    my ($baseurl,$showsymb) = 
 3304: 				&get_feedurl_and_symb($symb,$collaborator,
 3305: 						      $udom);
 3306: 			    if ($env{'form.withgrades'.$ctr}) {
 3307: 				$messagetail = " for <a href=\"".
 3308:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3309: 			    }
 3310: 			    $msgstatus = 
 3311: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3312: 			}
 3313: 		    }
 3314: 		}
 3315: 	    }
 3316: 	    $ctr++;
 3317: 	}
 3318:     }
 3319: 
 3320:     my %keyhash = ();
 3321:     if ($numessay) {
 3322: 	# Keywords sorted in alphabatical order
 3323: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3324: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3325: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3326: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3327: 	$env{'form.keywords'} = join(' ',@keywords);
 3328: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3329: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3330: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3331: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3332: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3333:     }
 3334: 
 3335:     if ($env{'form.compmsg'}) {
 3336: 	# message center - Order of message gets changed. Blank line is eliminated.
 3337: 	# New messages are saved in env for the next student.
 3338: 	# All messages are saved in nohist_handgrade.db
 3339: 	my ($ctr,$idx) = (1,1);
 3340: 	while ($ctr <= $env{'form.savemsgN'}) {
 3341: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3342: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3343: 		$idx++;
 3344: 	    }
 3345: 	    $ctr++;
 3346: 	}
 3347: 	$ctr = 0;
 3348: 	while ($ctr < $ngrade) {
 3349: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3350: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3351: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3352: 		$idx++;
 3353: 	    }
 3354: 	    $ctr++;
 3355: 	}
 3356: 	$env{'form.savemsgN'} = --$idx;
 3357: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3358:     }
 3359:     if (($numessay) || ($env{'form.compmsg'})) {
 3360: 	my $putresult = &Apache::lonnet::put
 3361: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3362:     }
 3363: 
 3364:     # Called by Save & Refresh from Highlight Attribute Window
 3365:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3366:     if ($env{'form.refresh'} eq 'on') {
 3367: 	my ($ctr,$total) = (0,0);
 3368: 	while ($ctr < $ngrade) {
 3369: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3370: 	    $ctr++;
 3371: 	}
 3372: 	$env{'form.NTSTU'}=$ngrade;
 3373: 	$ctr = 0;
 3374: 	while ($ctr < $total) {
 3375: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3376: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3377: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3378: 	    &submission($request,$ctr,$total-1,$symb);
 3379: 	    $ctr++;
 3380: 	}
 3381: 	return '';
 3382:     }
 3383: 
 3384:     # Get the next/previous one or group of students
 3385:     my $firststu = $env{'form.unamedom0'};
 3386:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3387:     my $ctr = 2;
 3388:     while ($laststu eq '') {
 3389: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3390: 	$ctr++;
 3391: 	$laststu = $firststu if ($ctr > $ngrade);
 3392:     }
 3393: 
 3394:     my (@parsedlist,@nextlist);
 3395:     my ($nextflg) = 0;
 3396:     foreach my $item (sort 
 3397: 	     {
 3398: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3399: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3400: 		 }
 3401: 		 return $a cmp $b;
 3402: 	     } (keys(%$fullname))) {
 3403: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3404: 	    push(@parsedlist,$item);
 3405: 	}
 3406: 	$nextflg = 1 if ($item eq $laststu);
 3407: 	if ($button eq 'Previous') {
 3408: 	    last if ($item eq $firststu);
 3409: 	    push(@parsedlist,$item);
 3410: 	}
 3411:     }
 3412:     $ctr = 0;
 3413:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3414:     foreach my $student (@parsedlist) {
 3415: 	my $submitonly=$env{'form.submitonly'};
 3416: 	my ($uname,$udom) = split(/:/,$student);
 3417: 	
 3418: 	if ($submitonly eq 'queued') {
 3419: 	    my %queue_status = 
 3420: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3421: 							$udom,$uname);
 3422: 	    next if (!defined($queue_status{'gradingqueue'}));
 3423: 	}
 3424: 
 3425: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3426: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3427: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3428: 	    my $submitted = 0;
 3429: 	    my $ungraded = 0;
 3430: 	    my $incorrect = 0;
 3431: 	    foreach my $item (keys(%status)) {
 3432: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3433: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3434: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3435: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3436: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3437: 		    $submitted = 0;
 3438: 		}
 3439: 	    }
 3440: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3441: 				     $submitonly eq 'incorrect' ||
 3442: 				     $submitonly eq 'graded'));
 3443: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3444: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3445: 	}
 3446: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3447: 	last if ($ctr == $ntstu);
 3448: 	$ctr++;
 3449:     }
 3450: 
 3451:     $ctr = 0;
 3452:     my $total = scalar(@nextlist)-1;
 3453: 
 3454:     foreach (sort(@nextlist)) {
 3455: 	my ($uname,$udom,$submitter) = split(/:/);
 3456: 	$env{'form.student'}  = $uname;
 3457: 	$env{'form.userdom'}  = $udom;
 3458: 	$env{'form.fullname'} = $$fullname{$_};
 3459: 	&submission($request,$ctr,$total,$symb);
 3460: 	$ctr++;
 3461:     }
 3462:     if ($total < 0) {
 3463:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3464: 	$request->print($the_end);
 3465:     }
 3466:     return '';
 3467: }
 3468: 
 3469: #---- Save the score and award for each student, if changed
 3470: sub saveHandGrade {
 3471:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3472:     my @version_parts;
 3473:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3474: 					   $env{'request.course.id'});
 3475:     if (!&canmodify($usec)) { return('not_allowed'); }
 3476:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3477:     my @parts_graded;
 3478:     my %newrecord  = ();
 3479:     my ($pts,$wgt,$totchg) = ('','',0);
 3480:     my %aggregate = ();
 3481:     my $aggregateflag = 0;
 3482:     if ($env{'form.HIDE'.$newflg}) {
 3483:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3484:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3485:         $totchg += $numchgs;
 3486:     }
 3487:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3488:     foreach my $new_part (@parts) {
 3489: 	#collaborator ($submi may vary for different parts
 3490: 	if ($submitter && $new_part ne $part) { next; }
 3491: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3492: 	if ($dropMenu eq 'excused') {
 3493: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3494: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3495: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3496: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3497: 		}
 3498: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3499: 	    }
 3500: 	} elsif ($dropMenu eq 'reset status'
 3501: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3502: 	    foreach my $key (keys(%record)) {
 3503: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3504: 	    }
 3505: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3506: 		"$env{'user.name'}:$env{'user.domain'}";
 3507:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3508: 
 3509:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3510: 					       [$new_part]);
 3511:             my $aggtries =$totaltries;
 3512:             if ($last_resets{$new_part}) {
 3513:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3514: 					   $new_part);
 3515:             }
 3516: 
 3517:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3518:             if ($aggtries > 0) {
 3519:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3520:                 $aggregateflag = 1;
 3521:             }
 3522: 	} elsif ($dropMenu eq '') {
 3523: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3524: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3525: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3526: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3527: 		next;
 3528: 	    }
 3529: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3530: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3531: 	    my $partial= $pts/$wgt;
 3532: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3533: 		#do not update score for part if not changed.
 3534:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3535: 		next;
 3536: 	    } else {
 3537: 	        push(@parts_graded,$new_part);
 3538: 	    }
 3539: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3540: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3541: 	    }
 3542: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3543: 	    if ($partial == 0) {
 3544: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3545: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3546: 		}
 3547: 	    } else {
 3548: 		if ($record{$reckey} ne 'correct_by_override') {
 3549: 		    $newrecord{$reckey} = 'correct_by_override';
 3550: 		}
 3551: 	    }	    
 3552: 	    if ($submitter && 
 3553: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3554: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3555: 	    }
 3556: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3557: 		"$env{'user.name'}:$env{'user.domain'}";
 3558: 	}
 3559: 	# unless problem has been graded, set flag to version the submitted files
 3560: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3561: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3562: 	        $dropMenu eq 'reset status')
 3563: 	   {
 3564: 	    push(@version_parts,$new_part);
 3565: 	}
 3566:     }
 3567:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3568:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3569: 
 3570:     if (%newrecord) {
 3571:         if (@version_parts) {
 3572:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3573:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3574: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3575: 	    foreach my $new_part (@version_parts) {
 3576: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3577: 				$new_part,\%newrecord);
 3578: 	    }
 3579:         }
 3580: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3581: 				$env{'request.course.id'},$domain,$stuname);
 3582: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3583: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3584:     }
 3585:     if ($aggregateflag) {
 3586:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3587: 			      $cdom,$cnum);
 3588:     }
 3589:     return ('',$pts,$wgt,$totchg);
 3590: }
 3591: 
 3592: sub makehidden {
 3593:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3594:     return unless (ref($record) eq 'HASH');
 3595:     my %modified;
 3596:     my $numchanged = 0;
 3597:     if (exists($record->{$version.':keys'})) {
 3598:         my $partsregexp = $parts;
 3599:         $partsregexp =~ s/,/|/g;
 3600:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3601:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3602:                  my $item = $1;
 3603:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3604:                      $modified{$key} = $record->{$version.':'.$key};
 3605:                  }
 3606:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3607:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3608:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3609:                 $modified{$key} = $record->{$version.':'.$key};
 3610:             }
 3611:         }
 3612:         if (keys(%modified)) {
 3613:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3614:                                           $domain,$stuname,$tolog) eq 'ok') {
 3615:                 $numchanged ++;
 3616:             }
 3617:         }
 3618:     }
 3619:     return $numchanged;
 3620: }
 3621: 
 3622: sub check_and_remove_from_queue {
 3623:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3624:     my @ungraded_parts;
 3625:     foreach my $part (@{$parts}) {
 3626: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3627: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3628: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3629: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3630: 		) {
 3631:             if ($queueable->{$part}) {
 3632: 	        push(@ungraded_parts, $part);
 3633:             }
 3634: 	}
 3635:     }
 3636:     if ( !@ungraded_parts ) {
 3637: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3638: 					       $cnum,$domain,$stuname);
 3639:     }
 3640: }
 3641: 
 3642: sub handback_files {
 3643:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3644:     my $portfolio_root = '/userfiles/portfolio';
 3645:     my $res_error;
 3646:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3647:     if ($res_error) {
 3648:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3649:         return;
 3650:     }
 3651:     my @handedback;
 3652:     my $file_msg;
 3653:     my @part_response_id = &flatten_responseType($responseType);
 3654:     foreach my $part_response_id (@part_response_id) {
 3655:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3656: 	my $part_resp = join('_',@{ $part_response_id });
 3657:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3658:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3659:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3660: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3661:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3662:                     my ($directory,$answer_file) = 
 3663:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3664:                     my ($answer_name,$answer_ver,$answer_ext) =
 3665: 		        &file_name_version_ext($answer_file);
 3666: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3667:                     my $getpropath = 1;
 3668:                     my ($dir_list,$listerror) =
 3669:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3670:                                                  $domain,$stuname,$getpropath);
 3671: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3672:                     # fix filename
 3673:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3674:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3675:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3676:             	                                $save_file_name);
 3677:                     if ($result !~ m|^/uploaded/|) {
 3678:                         $request->print('<br /><span class="LC_error">'.
 3679:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3680:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3681:                                         '</span>');
 3682:                     } else {
 3683:                         # mark the file as read only
 3684:                         push(@handedback,$save_file_name);
 3685: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3686: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3687: 			}
 3688:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3689: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3690: 
 3691:                     }
 3692:                     $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>'));
 3693:                 }
 3694:             }
 3695:         }
 3696:     }
 3697:     if (@handedback > 0) {
 3698:         $request->print('<br />');
 3699:         my @what = ($symb,$env{'request.course.id'},'handback');
 3700:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3701:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3702:         my ($subject,$message);
 3703:         if (scalar(@handedback) == 1) {
 3704:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3705:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3706:         } else {
 3707:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3708:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3709:         }
 3710:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3711:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3712:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3713:         my ($feedurl,$showsymb) =
 3714:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3715:         my $restitle = &Apache::lonnet::gettitle($symb);
 3716:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3717:         my $msgstatus =
 3718:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3719:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3720:                  $restitle);
 3721:         if ($msgstatus) {
 3722:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3723:         }
 3724:     }
 3725:     return;
 3726: }
 3727: 
 3728: sub get_feedurl_and_symb {
 3729:     my ($symb,$uname,$udom) = @_;
 3730:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3731:     $url = &Apache::lonnet::clutter($url);
 3732:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3733: 					$symb,$udom,$uname);
 3734:     if ($encrypturl =~ /^yes$/i) {
 3735: 	&Apache::lonenc::encrypted(\$url,1);
 3736: 	&Apache::lonenc::encrypted(\$symb,1);
 3737:     }
 3738:     return ($url,$symb);
 3739: }
 3740: 
 3741: sub get_submitted_files {
 3742:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3743:     my @files;
 3744:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3745:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3746:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3747:     	    push(@files,$file_url.$file);
 3748:         }
 3749:     }
 3750:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3751:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3752:     }
 3753:     return (\@files);
 3754: }
 3755: 
 3756: # ----------- Provides number of tries since last reset.
 3757: sub get_num_tries {
 3758:     my ($record,$last_reset,$part) = @_;
 3759:     my $timestamp = '';
 3760:     my $num_tries = 0;
 3761:     if ($$record{'version'}) {
 3762:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3763:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3764:                 $timestamp = $$record{$version.':timestamp'};
 3765:                 if ($timestamp > $last_reset) {
 3766:                     $num_tries ++;
 3767:                 } else {
 3768:                     last;
 3769:                 }
 3770:             }
 3771:         }
 3772:     }
 3773:     return $num_tries;
 3774: }
 3775: 
 3776: # ----------- Determine decrements required in aggregate totals 
 3777: sub decrement_aggs {
 3778:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3779:     my %decrement = (
 3780:                         attempts => 0,
 3781:                         users => 0,
 3782:                         correct => 0
 3783:                     );
 3784:     $decrement{'attempts'} = $aggtries;
 3785:     if ($solvedstatus =~ /^correct/) {
 3786:         $decrement{'correct'} = 1;
 3787:     }
 3788:     if ($aggtries == $totaltries) {
 3789:         $decrement{'users'} = 1;
 3790:     }
 3791:     foreach my $type (keys(%decrement)) {
 3792:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3793:     }
 3794:     return;
 3795: }
 3796: 
 3797: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3798: sub get_last_resets {
 3799:     my ($symb,$courseid,$partids) =@_;
 3800:     my %last_resets;
 3801:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3802:     my $cname = $env{'course.'.$courseid.'.num'};
 3803:     my @keys;
 3804:     foreach my $part (@{$partids}) {
 3805: 	push(@keys,"$symb\0$part\0resettime");
 3806:     }
 3807:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3808: 				     $cdom,$cname);
 3809:     foreach my $part (@{$partids}) {
 3810: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3811:     }
 3812:     return %last_resets;
 3813: }
 3814: 
 3815: # ----------- Handles creating versions for portfolio files as answers
 3816: sub version_portfiles {
 3817:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3818:     my $version_parts = join('|',@$v_flag);
 3819:     my @returned_keys;
 3820:     my $parts = join('|', @$parts_graded);
 3821:     my $portfolio_root = '/userfiles/portfolio';
 3822:     foreach my $key (keys(%$record)) {
 3823:         my $new_portfiles;
 3824:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3825:             my @versioned_portfiles;
 3826:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3827:             foreach my $file (@portfiles) {
 3828:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3829:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3830: 		my ($answer_name,$answer_ver,$answer_ext) =
 3831: 		    &file_name_version_ext($answer_file);
 3832:                 my $getpropath = 1;
 3833:                 my ($dir_list,$listerror) =
 3834:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3835:                                              $stu_name,$getpropath);
 3836:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3837:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3838:                 if ($new_answer ne 'problem getting file') {
 3839:                     push(@versioned_portfiles, $directory.$new_answer);
 3840:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3841:                         [$directory.$new_answer],
 3842:                         [$symb,$env{'request.course.id'},'graded']);
 3843:                 }
 3844:             }
 3845:             $$record{$key} = join(',',@versioned_portfiles);
 3846:             push(@returned_keys,$key);
 3847:         }
 3848:     } 
 3849:     return (@returned_keys);   
 3850: }
 3851: 
 3852: sub get_next_version {
 3853:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3854:     my $version;
 3855:     if (ref($dir_list) eq 'ARRAY') {
 3856:         foreach my $row (@{$dir_list}) {
 3857:             my ($file) = split(/\&/,$row,2);
 3858:             my ($file_name,$file_version,$file_ext) =
 3859: 	        &file_name_version_ext($file);
 3860:             if (($file_name eq $answer_name) && 
 3861: 	        ($file_ext eq $answer_ext)) {
 3862:                 # gets here if filename and extension match, 
 3863:                 # regardless of version
 3864:                 if ($file_version ne '') {
 3865:                     # a versioned file is found  so save it for later
 3866:                     if ($file_version > $version) {
 3867: 		        $version = $file_version;
 3868:                     }
 3869: 	        }
 3870:             }
 3871:         }
 3872:     }
 3873:     $version ++;
 3874:     return($version);
 3875: }
 3876: 
 3877: sub version_selected_portfile {
 3878:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3879:     my ($answer_name,$answer_ver,$answer_ext) =
 3880:         &file_name_version_ext($file_name);
 3881:     my $new_answer;
 3882:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3883:     if($env{'form.copy'} eq '-1') {
 3884:         $new_answer = 'problem getting file';
 3885:     } else {
 3886:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3887:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3888:                             $stu_name,$domain,'copy',
 3889: 		        '/portfolio'.$directory.$new_answer);
 3890:     }    
 3891:     return ($new_answer);
 3892: }
 3893: 
 3894: sub file_name_version_ext {
 3895:     my ($file)=@_;
 3896:     my @file_parts = split(/\./, $file);
 3897:     my ($name,$version,$ext);
 3898:     if (@file_parts > 1) {
 3899: 	$ext=pop(@file_parts);
 3900: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3901: 	    $version=pop(@file_parts);
 3902: 	}
 3903: 	$name=join('.',@file_parts);
 3904:     } else {
 3905: 	$name=join('.',@file_parts);
 3906:     }
 3907:     return($name,$version,$ext);
 3908: }
 3909: 
 3910: #--------------------------------------------------------------------------------------
 3911: #
 3912: #-------------------------- Next few routines handles grading by section or whole class
 3913: #
 3914: #--- Javascript to handle grading by section or whole class
 3915: sub viewgrades_js {
 3916:     my ($request) = shift;
 3917: 
 3918:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3919:     &js_escape(\$alertmsg);
 3920:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3921:    function writePoint(partid,weight,point) {
 3922: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3923: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3924: 	if (point == "textval") {
 3925: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3926: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3927: 		alert("$alertmsg"+parseFloat(point));
 3928: 		var resetbox = false;
 3929: 		for (var i=0; i<radioButton.length; i++) {
 3930: 		    if (radioButton[i].checked) {
 3931: 			textbox.value = i;
 3932: 			resetbox = true;
 3933: 		    }
 3934: 		}
 3935: 		if (!resetbox) {
 3936: 		    textbox.value = "";
 3937: 		}
 3938: 		return;
 3939: 	    }
 3940: 	    if (parseFloat(point) > parseFloat(weight)) {
 3941: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3942: 				   ") greater than the weight for the part. Accept?");
 3943: 		if (resp == false) {
 3944: 		    textbox.value = "";
 3945: 		    return;
 3946: 		}
 3947: 	    }
 3948: 	    for (var i=0; i<radioButton.length; i++) {
 3949: 		radioButton[i].checked=false;
 3950: 		if (parseFloat(point) == i) {
 3951: 		    radioButton[i].checked=true;
 3952: 		}
 3953: 	    }
 3954: 
 3955: 	} else {
 3956: 	    textbox.value = parseFloat(point);
 3957: 	}
 3958: 	for (i=0;i<document.classgrade.total.value;i++) {
 3959: 	    var user = document.classgrade["ctr"+i].value;
 3960: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3961: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3962: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3963: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3964: 	    if (saveval != "correct") {
 3965: 		scorename.value = point;
 3966: 		if (selname[0].selected != true) {
 3967: 		    selname[0].selected = true;
 3968: 		}
 3969: 	    }
 3970: 	}
 3971: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3972:     }
 3973: 
 3974:     function writeRadText(partid,weight) {
 3975: 	var selval   = document.classgrade["SELVAL_"+partid];
 3976: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3977:         var override = document.classgrade["FORCE_"+partid].checked;
 3978: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3979: 	if (selval[1].selected || selval[2].selected) {
 3980: 	    for (var i=0; i<radioButton.length; i++) {
 3981: 		radioButton[i].checked=false;
 3982: 
 3983: 	    }
 3984: 	    textbox.value = "";
 3985: 
 3986: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3987: 		var user = document.classgrade["ctr"+i].value;
 3988: 		user = user.replace(new RegExp(':', 'g'),"_");
 3989: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3990: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3991: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3992: 		if ((saveval != "correct") || override) {
 3993: 		    scorename.value = "";
 3994: 		    if (selval[1].selected) {
 3995: 			selname[1].selected = true;
 3996: 		    } else {
 3997: 			selname[2].selected = true;
 3998: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3999: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 4000: 		    }
 4001: 		}
 4002: 	    }
 4003: 	} else {
 4004: 	    for (i=0;i<document.classgrade.total.value;i++) {
 4005: 		var user = document.classgrade["ctr"+i].value;
 4006: 		user = user.replace(new RegExp(':', 'g'),"_");
 4007: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 4008: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 4009: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 4010: 		if ((saveval != "correct") || override) {
 4011: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 4012: 		    selname[0].selected = true;
 4013: 		}
 4014: 	    }
 4015: 	}	    
 4016:     }
 4017: 
 4018:     function changeSelect(partid,user) {
 4019: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 4020: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 4021: 	var point  = textbox.value;
 4022: 	var weight = document.classgrade["weight_"+partid].value;
 4023: 
 4024: 	if (isNaN(point) || parseFloat(point) < 0) {
 4025: 	    alert("$alertmsg"+parseFloat(point));
 4026: 	    textbox.value = "";
 4027: 	    return;
 4028: 	}
 4029: 	if (parseFloat(point) > parseFloat(weight)) {
 4030: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 4031: 			       ") greater than the weight of the part. Accept?");
 4032: 	    if (resp == false) {
 4033: 		textbox.value = "";
 4034: 		return;
 4035: 	    }
 4036: 	}
 4037: 	selval[0].selected = true;
 4038:     }
 4039: 
 4040:     function changeOneScore(partid,user) {
 4041: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 4042: 	if (selval[1].selected || selval[2].selected) {
 4043: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 4044: 	    if (selval[2].selected) {
 4045: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 4046: 	    }
 4047:         }
 4048:     }
 4049: 
 4050:     function resetEntry(numpart) {
 4051: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 4052: 	    var partid = document.classgrade["partid_"+ctpart].value;
 4053: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 4054: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 4055: 	    var selval  = document.classgrade["SELVAL_"+partid];
 4056: 	    for (var i=0; i<radioButton.length; i++) {
 4057: 		radioButton[i].checked=false;
 4058: 
 4059: 	    }
 4060: 	    textbox.value = "";
 4061: 	    selval[0].selected = true;
 4062: 
 4063: 	    for (i=0;i<document.classgrade.total.value;i++) {
 4064: 		var user = document.classgrade["ctr"+i].value;
 4065: 		user = user.replace(new RegExp(':', 'g'),"_");
 4066: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 4067: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 4068: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 4069: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 4070: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 4071: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 4072: 		if (saveselval == "excused") {
 4073: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 4074: 		} else {
 4075: 		    if (selname[0].selected == false) {selname[0].selected = true};
 4076: 		}
 4077: 	    }
 4078: 	}
 4079:     }
 4080: 
 4081: VIEWJAVASCRIPT
 4082: }
 4083: 
 4084: #--- show scores for a section or whole class w/ option to change/update a score
 4085: sub viewgrades {
 4086:     my ($request,$symb) = @_;
 4087:     my ($is_tool,$toolsymb);
 4088:     if ($symb =~ /ext\.tool$/) {
 4089:         $is_tool = 1;
 4090:         $toolsymb = $symb;
 4091:     }
 4092:     &viewgrades_js($request);
 4093: 
 4094:     #need to make sure we have the correct data for later EXT calls, 
 4095:     #thus invalidate the cache
 4096:     &Apache::lonnet::devalidatecourseresdata(
 4097:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4098:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4099:     &Apache::lonnet::clear_EXT_cache_status();
 4100: 
 4101:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 4102: 
 4103:     #view individual student submission form - called using Javascript viewOneStudent
 4104:     $result.=&jscriptNform($symb);
 4105: 
 4106:     #beginning of class grading form
 4107:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4108:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4109: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4110: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4111: 	&build_section_inputs().
 4112: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4113: 
 4114:     #retrieve selected groups
 4115:     my (@groups,$group_display);
 4116:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4117:     if (grep(/^all$/,@groups)) {
 4118:         @groups = ('all');
 4119:     } elsif (grep(/^none$/,@groups)) {
 4120:         @groups = ('none');
 4121:     } elsif (@groups > 0) {
 4122:         $group_display = join(', ',@groups);
 4123:     }
 4124: 
 4125:     my ($common_header,$specific_header,@sections,$section_display);
 4126:     if ($env{'request.course.sec'} ne '') {
 4127:         @sections = ($env{'request.course.sec'});
 4128:     } else {
 4129:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4130:     }
 4131: 
 4132: # Check if Save button should be usable
 4133:     my $disabled = ' disabled="disabled"';
 4134:     if ($perm{'mgr'}) {
 4135:         if (grep(/^all$/,@sections)) {
 4136:             undef($disabled);
 4137:         } else {
 4138:             foreach my $sec (@sections) {
 4139:                 if (&canmodify($sec)) {
 4140:                     undef($disabled);
 4141:                     last;
 4142:                 }
 4143:             }
 4144:         }
 4145:     }
 4146:     if (grep(/^all$/,@sections)) {
 4147:         @sections = ('all');
 4148:         if ($group_display) {
 4149:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4150:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4151:         } elsif (grep(/^none$/,@groups)) {
 4152:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4153:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4154:         } else {
 4155:             $common_header = &mt('Assign Common Grade to Class');
 4156:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4157:         }
 4158:     } elsif (grep(/^none$/,@sections)) {
 4159:         @sections = ('none');
 4160:         if ($group_display) {
 4161:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4162:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4163:         } elsif (grep(/^none$/,@groups)) {
 4164:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4165:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4166:         } else {
 4167:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4168:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4169:         }
 4170:     } else {
 4171:         $section_display = join (", ",@sections);
 4172:         if ($group_display) {
 4173:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4174:                                  $section_display,$group_display);
 4175:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4176:                                    $section_display,$group_display);
 4177:         } elsif (grep(/^none$/,@groups)) {
 4178:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4179:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4180:         } else {
 4181:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4182:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4183:         }
 4184:     }
 4185:     my %submit_types = &substatus_options();
 4186:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4187: 
 4188:     if ($env{'form.submitonly'} eq 'all') {
 4189:         $result.= '<h3>'.$common_header.'</h3>';
 4190:     } else {
 4191:         my $text;
 4192:         if ($is_tool) {
 4193:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4194:         } else {
 4195:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4196:         }
 4197:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4198:     }
 4199:     $result .= &Apache::loncommon::start_data_table();
 4200:     #radio buttons/text box for assigning points for a section or class.
 4201:     #handles different parts of a problem
 4202:     my $res_error;
 4203:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4204:     if ($res_error) {
 4205:         return &navmap_errormsg();
 4206:     }
 4207:     my %weight = ();
 4208:     my $ctsparts = 0;
 4209:     my %seen = ();
 4210:     my @part_response_id;
 4211:     if ($is_tool) {
 4212:         @part_response_id = ([0,'']);
 4213:     } else {
 4214:         @part_response_id = &flatten_responseType($responseType);
 4215:     }
 4216:     foreach my $part_response_id (@part_response_id) {
 4217:     	my ($partid,$respid) = @{ $part_response_id };
 4218: 	my $part_resp = join('_',@{ $part_response_id });
 4219: 	next if $seen{$partid};
 4220: 	$seen{$partid}++;
 4221: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4222: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4223: 
 4224: 	my $display_part=&get_display_part($partid,$symb);
 4225: 	my $radio.='<table border="0"><tr>';  
 4226: 	my $ctr = 0;
 4227: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4228: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4229: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4230: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4231: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4232: 	    $ctr++;
 4233: 	}
 4234: 	$radio.='</tr></table>';
 4235: 	my $line = '<input type="text" name="TEXTVAL_'.
 4236: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4237: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4238: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4239: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4240:                 '<select name="SELVAL_'.$partid.'" '.
 4241: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4242: 		$weight{$partid}.')"> '.
 4243: 	    '<option selected="selected"> </option>'.
 4244: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4245: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4246: 	    '</select></td>'.
 4247:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4248: 	$line.='<input type="hidden" name="partid_'.
 4249: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4250: 	$line.='<input type="hidden" name="weight_'.
 4251: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4252: 
 4253: 	$result.=
 4254: 	    &Apache::loncommon::start_data_table_row()."\n".
 4255: 	    '<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>'.
 4256: 	    &Apache::loncommon::end_data_table_row()."\n";
 4257: 	$ctsparts++;
 4258:     }
 4259:     $result.=&Apache::loncommon::end_data_table()."\n".
 4260: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4261:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4262: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4263: 
 4264:     #table listing all the students in a section/class
 4265:     #header of table
 4266:     if ($env{'form.submitonly'} eq 'all') {
 4267:         $result.= '<h3>'.$specific_header.'</h3>';
 4268:     } else {
 4269:         my $text;
 4270:         if ($is_tool) {
 4271:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4272:         } else {
 4273:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4274:         }
 4275:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4276:     }
 4277:     $result.= &Apache::loncommon::start_data_table().
 4278: 	      &Apache::loncommon::start_data_table_header_row().
 4279: 	      '<th>'.&mt('No.').'</th>'.
 4280: 	      '<th>'.&nameUserString('header')."</th>\n";
 4281:     my $partserror;
 4282:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4283:     if ($partserror) {
 4284:         return &navmap_errormsg();
 4285:     }
 4286:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4287:     my @partids = ();
 4288:     foreach my $part (@parts) {
 4289: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4290:         my $narrowtext = &mt('Tries');
 4291: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4292: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4293: 	my ($partid) = &split_part_type($part);
 4294:         push(@partids,$partid);
 4295: #
 4296: # FIXME: Looks like $display looks at English text
 4297: #
 4298: 	my $display_part=&get_display_part($partid,$symb);
 4299: 	if ($display =~ /^Partial Credit Factor/) {
 4300: 	    $result.='<th>'.
 4301:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4302:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4303: 	    next;
 4304: 	    
 4305: 	} else {
 4306: 	    if ($display =~ /Problem Status/) {
 4307: 		my $grade_status_mt = &mt('Grade Status');
 4308: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4309: 	    }
 4310: 	    my $part_mt = &mt('Part:');
 4311: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4312: 	}
 4313: 
 4314: 	$result.='<th>'.$display.'</th>'."\n";
 4315:     }
 4316:     $result.=&Apache::loncommon::end_data_table_header_row();
 4317: 
 4318:     my %last_resets = 
 4319: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4320: 
 4321:     #get info for each student
 4322:     #list all the students - with points and grade status
 4323:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4324:     my $ctr = 0;
 4325:     foreach (sort 
 4326: 	     {
 4327: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4328: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4329: 		 }
 4330: 		 return $a cmp $b;
 4331: 	     } (keys(%$fullname))) {
 4332: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4333: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4334:     }
 4335:     $result.=&Apache::loncommon::end_data_table();
 4336:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4337:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4338: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4339:     if ($ctr == 0) {
 4340:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4341:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4342:                 '<span class="LC_warning">';
 4343:         if ($env{'form.submitonly'} eq 'all') {
 4344:             if (grep(/^all$/,@sections)) {
 4345:                 if (grep(/^all$/,@groups)) {
 4346:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4347:                                    $stu_status);
 4348:                 } elsif (grep(/^none$/,@groups)) {
 4349:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4350:                                    $stu_status);
 4351:                 } else {
 4352:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4353:                                    $group_display,$stu_status);
 4354:                 }
 4355:             } elsif (grep(/^none$/,@sections)) {
 4356:                 if (grep(/^all$/,@groups)) {
 4357:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4358:                                    $stu_status);
 4359:                 } elsif (grep(/^none$/,@groups)) {
 4360:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4361:                                    $stu_status);
 4362:                 } else {
 4363:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4364:                                    $group_display,$stu_status);
 4365:                 }
 4366:             } else {
 4367:                 if (grep(/^all$/,@groups)) {
 4368:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4369:                                    $section_display,$stu_status);
 4370:                 } elsif (grep(/^none$/,@groups)) {
 4371:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4372:                                    $section_display,$stu_status);
 4373:                 } else {
 4374:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4375:                                    $section_display,$group_display,$stu_status);
 4376:                 }
 4377:             }
 4378:         } else {
 4379:             if (grep(/^all$/,@sections)) {
 4380:                 if (grep(/^all$/,@groups)) {
 4381:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4382:                                    $stu_status,$submission_status);
 4383:                 } elsif (grep(/^none$/,@groups)) {
 4384:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4385:                                    $stu_status,$submission_status);
 4386:                 } else {
 4387:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4388:                                    $group_display,$stu_status,$submission_status);
 4389:                 }
 4390:             } elsif (grep(/^none$/,@sections)) {
 4391:                 if (grep(/^all$/,@groups)) {
 4392:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4393:                                    $stu_status,$submission_status);
 4394:                 } elsif (grep(/^none$/,@groups)) {
 4395:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4396:                                    $stu_status,$submission_status);
 4397:                 } else {
 4398:                     $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.',
 4399:                                    $group_display,$stu_status,$submission_status);
 4400:                 }
 4401:             } else {
 4402:                 if (grep(/^all$/,@groups)) {
 4403:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4404:                                    $section_display,$stu_status,$submission_status);
 4405:                 } elsif (grep(/^none$/,@groups)) {
 4406:                     $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.',
 4407:                                    $section_display,$stu_status,$submission_status);
 4408:                 } else {
 4409:                     $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.',
 4410:                                    $section_display,$group_display,$stu_status,$submission_status);
 4411:                 }
 4412:             }
 4413: 	}
 4414: 	$result .= '</span><br />';
 4415:     }
 4416:     return $result;
 4417: }
 4418: 
 4419: #--- call by previous routine to display each student who satisfies submission filter.
 4420: sub viewstudentgrade {
 4421:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4422:     my ($uname,$udom) = split(/:/,$student);
 4423:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4424:     my $submitonly = $env{'form.submitonly'};
 4425:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4426:         my %partstatus = ();
 4427:         if (ref($parts) eq 'ARRAY') {
 4428:             foreach my $apart (@{$parts}) {
 4429:                 my ($part,$type) = &split_part_type($apart);
 4430:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4431:                 $status = 'nothing' if ($status eq '');
 4432:                 $partstatus{$part}      = $status;
 4433:                 my $subkey = "resource.$part.submitted_by";
 4434:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4435:             }
 4436:             my $submitted = 0;
 4437:             my $graded = 0;
 4438:             my $incorrect = 0;
 4439:             foreach my $key (keys(%partstatus)) {
 4440:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4441:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4442:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4443: 
 4444:                 my $partid = (split(/\./,$key))[1];
 4445:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4446:                     $submitted = 0;
 4447:                 }
 4448:             }
 4449:             return if (!$submitted && ($submitonly eq 'yes' ||
 4450:                                        $submitonly eq 'incorrect' ||
 4451:                                        $submitonly eq 'graded'));
 4452:             return if (!$graded && ($submitonly eq 'graded'));
 4453:             return if (!$incorrect && $submitonly eq 'incorrect');
 4454:         }
 4455:     }
 4456:     if ($submitonly eq 'queued') {
 4457:         my ($cdom,$cnum) = split(/_/,$courseid);
 4458:         my %queue_status =
 4459:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4460:                                                     $udom,$uname);
 4461:         return if (!defined($queue_status{'gradingqueue'}));
 4462:     }
 4463:     $$ctr++;
 4464:     my %aggregates = ();
 4465:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4466: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4467: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4468: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4469: 	'\');" target="_self">'.$fullname.'</a> '.
 4470: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4471:     $student=~s/:/_/; # colon doen't work in javascript for names
 4472:     foreach my $apart (@$parts) {
 4473: 	my ($part,$type) = &split_part_type($apart);
 4474: 	my $score=$record{"resource.$part.$type"};
 4475:         $result.='<td align="center">';
 4476:         my ($aggtries,$totaltries);
 4477:         unless (exists($aggregates{$part})) {
 4478: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4479: 	    $aggtries = $totaltries;
 4480:             if ($$last_resets{$part}) {  
 4481:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4482: 					   $part);
 4483:             }
 4484:             $result.='<input type="hidden" name="'.
 4485:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4486:             $result.='<input type="hidden" name="'.
 4487:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4488:             $aggregates{$part} = 1;
 4489:         }
 4490: 	if ($type eq 'awarded') {
 4491: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4492: 	    $result.='<input type="hidden" name="'.
 4493: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4494: 	    $result.='<input type="text" name="'.
 4495: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4496:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4497: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4498: 	} elsif ($type eq 'solved') {
 4499: 	    my ($status,$foo)=split(/_/,$score,2);
 4500: 	    $status = 'nothing' if ($status eq '');
 4501: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4502: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4503: 	    $result.='&nbsp;<select name="'.
 4504: 		'GD_'.$student.'_'.$part.'_solved" '.
 4505:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4506: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4507: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4508: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4509: 	    $result.="</select>&nbsp;</td>\n";
 4510: 	} else {
 4511: 	    $result.='<input type="hidden" name="'.
 4512: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4513: 		    "\n";
 4514: 	    $result.='<input type="text" name="'.
 4515: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4516: 		'value="'.$score.'" size="4" /></td>'."\n";
 4517: 	}
 4518:     }
 4519:     $result.=&Apache::loncommon::end_data_table_row();
 4520:     return $result;
 4521: }
 4522: 
 4523: #--- change scores for all the students in a section/class
 4524: #    record does not get update if unchanged
 4525: sub editgrades {
 4526:     my ($request,$symb) = @_;
 4527:     my $toolsymb;
 4528:     if ($symb =~ /ext\.tool$/) {
 4529:         $toolsymb = $symb;
 4530:     }
 4531: 
 4532:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4533:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4534:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4535: 
 4536:     my $result= &Apache::loncommon::start_data_table().
 4537: 	&Apache::loncommon::start_data_table_header_row().
 4538: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4539: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4540:     my %scoreptr = (
 4541: 		    'correct'  =>'correct_by_override',
 4542: 		    'incorrect'=>'incorrect_by_override',
 4543: 		    'excused'  =>'excused',
 4544: 		    'ungraded' =>'ungraded_attempted',
 4545:                     'credited' =>'credit_attempted',
 4546: 		    'nothing'  => '',
 4547: 		    );
 4548:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4549: 
 4550:     my (@partid);
 4551:     my %weight = ();
 4552:     my %columns = ();
 4553:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4554: 
 4555:     my $partserror;
 4556:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4557:     if ($partserror) {
 4558:         return &navmap_errormsg();
 4559:     }
 4560:     my $header;
 4561:     while ($ctr < $env{'form.totalparts'}) {
 4562: 	my $partid = $env{'form.partid_'.$ctr};
 4563: 	push(@partid,$partid);
 4564: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4565: 	$ctr++;
 4566:     }
 4567:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4568:     my $totcolspan = 0;
 4569:     foreach my $partid (@partid) {
 4570: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4571: 	    '<th align="center">'.&mt('New Score').'</th>';
 4572: 	$columns{$partid}=2;
 4573: 	foreach my $stores (@parts) {
 4574: 	    my ($part,$type) = &split_part_type($stores);
 4575: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4576: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4577: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4578: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4579:             my $narrowtext = &mt('Tries');
 4580: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4581: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4582: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4583: 	    $columns{$partid}+=2;
 4584: 	}
 4585:         $totcolspan += $columns{$partid};
 4586:     }
 4587:     foreach my $partid (@partid) {
 4588: 	my $display_part=&get_display_part($partid,$symb);
 4589: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4590: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4591: 	    '</th>';
 4592: 
 4593:     }
 4594:     $result .= &Apache::loncommon::end_data_table_header_row().
 4595: 	&Apache::loncommon::start_data_table_header_row().
 4596: 	$header.
 4597: 	&Apache::loncommon::end_data_table_header_row();
 4598:     my @noupdate;
 4599:     my ($updateCtr,$noupdateCtr) = (1,1);
 4600:     my ($got_types,%queueable);
 4601:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4602: 	my $user = $env{'form.ctr'.$i};
 4603: 	my ($uname,$udom)=split(/:/,$user);
 4604: 	my %newrecord;
 4605: 	my $updateflag = 0;
 4606:         my $usec=$classlist->{"$uname:$udom"}[5];
 4607:         my $canmodify = &canmodify($usec);
 4608:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4609:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4610:         if (!$canmodify) {
 4611:             push(@noupdate,
 4612:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4613:                  &mt('Not allowed to modify student')."</span></td>");
 4614:             next;
 4615:         }
 4616:         my %aggregate = ();
 4617:         my $aggregateflag = 0;
 4618: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4619: 	foreach (@partid) {
 4620: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4621: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4622: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4623: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4624: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4625: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4626: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4627: 	    my $score;
 4628: 	    if ($partial eq '') {
 4629: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4630: 	    } elsif ($partial > 0) {
 4631: 		$score = 'correct_by_override';
 4632: 	    } elsif ($partial == 0) {
 4633: 		$score = 'incorrect_by_override';
 4634: 	    }
 4635: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4636: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4637: 
 4638: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4639: 		"$env{'user.name'}:$env{'user.domain'}";
 4640: 	    if ($dropMenu eq 'reset status' &&
 4641: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4642: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4643: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4644: 		$newrecord{'resource.'.$_.'.award'} = '';
 4645: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4646: 		$updateflag = 1;
 4647:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4648:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4649:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4650:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4651:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4652:                     $aggregateflag = 1;
 4653:                 }
 4654: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4655: 		$updateflag = 1;
 4656: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4657: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4658: 		$rec_update++;
 4659: 	    }
 4660: 
 4661: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4662: 		'<td align="center">'.$awarded.
 4663: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4664: 
 4665: 
 4666: 	    my $partid=$_;
 4667: 	    foreach my $stores (@parts) {
 4668: 		my ($part,$type) = &split_part_type($stores);
 4669: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4670: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4671: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4672: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4673: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4674: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4675: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4676: 		    $updateflag=1;
 4677: 		}
 4678: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4679: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4680: 	    }
 4681: 	}
 4682: 	$line.="\n";
 4683: 
 4684: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4685: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4686: 
 4687: 	if ($updateflag) {
 4688: 	    $count++;
 4689: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4690: 				    $udom,$uname);
 4691: 
 4692: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4693: 					      $cnum,$udom,$uname)) {
 4694: 		# need to figure out if should be in queue.
 4695: 		my %record =  
 4696: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4697: 					     $udom,$uname);
 4698: 		my $all_graded = 1;
 4699: 		my $none_graded = 1;
 4700:                 unless ($got_types) {
 4701:                     my $error;
 4702:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4703:                     unless ($error) {
 4704:                         foreach my $part (@parts) {
 4705:                             if (ref($resptype->{$part}) eq 'HASH') {
 4706:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4707:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4708:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4709:                                         $queueable{$part} = 1;
 4710:                                         last;
 4711:                                     }
 4712:                                 }
 4713:                             }
 4714:                         }
 4715:                     }
 4716:                     $got_types = 1;
 4717:                 }
 4718: 		foreach my $part (@parts) {
 4719:                     if ($queueable{$part}) {
 4720: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4721: 			    $all_graded = 0;
 4722: 		        } else {
 4723: 			    $none_graded = 0;
 4724: 		        }
 4725:                     }
 4726: 		}
 4727: 
 4728: 		if ($all_graded || $none_graded) {
 4729: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4730: 							   $symb,$cdom,$cnum,
 4731: 							   $udom,$uname);
 4732: 		}
 4733: 	    }
 4734: 
 4735: 	    $result.=&Apache::loncommon::start_data_table_row().
 4736: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4737: 		&Apache::loncommon::end_data_table_row();
 4738: 	    $updateCtr++;
 4739: 	} else {
 4740: 	    push(@noupdate,
 4741: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4742: 	    $noupdateCtr++;
 4743: 	}
 4744:         if ($aggregateflag) {
 4745:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4746: 				  $cdom,$cnum);
 4747:         }
 4748:     }
 4749:     if (@noupdate) {
 4750:         my $numcols=$totcolspan+2;
 4751: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4752: 	    '<td align="center" colspan="'.$numcols.'">'.
 4753: 	    &mt('No Changes Occurred For the Students Below').
 4754: 	    '</td>'.
 4755: 	    &Apache::loncommon::end_data_table_row();
 4756: 	foreach my $line (@noupdate) {
 4757: 	    $result.=
 4758: 		&Apache::loncommon::start_data_table_row().
 4759: 		$line.
 4760: 		&Apache::loncommon::end_data_table_row();
 4761: 	}
 4762:     }
 4763:     $result .= &Apache::loncommon::end_data_table();
 4764:     my $msg = '<p><b>'.
 4765: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4766: 	    $rec_update,$count).'</b><br />'.
 4767: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4768: 	'</b></p>';
 4769:     return $title.$msg.$result;
 4770: }
 4771: 
 4772: sub split_part_type {
 4773:     my ($partstr) = @_;
 4774:     my ($temp,@allparts)=split(/_/,$partstr);
 4775:     my $type=pop(@allparts);
 4776:     my $part=join('_',@allparts);
 4777:     return ($part,$type);
 4778: }
 4779: 
 4780: #------------- end of section for handling grading by section/class ---------
 4781: #
 4782: #----------------------------------------------------------------------------
 4783: 
 4784: 
 4785: #----------------------------------------------------------------------------
 4786: #
 4787: #-------------------------- Next few routines handles grading by csv upload
 4788: #
 4789: #--- Javascript to handle csv upload
 4790: sub csvupload_javascript_reverse_associate {
 4791:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4792:     my $error2=&mt('You need to specify at least one grading field');
 4793:   &js_escape(\$error1);
 4794:   &js_escape(\$error2);
 4795:   return(<<ENDPICK);
 4796:   function verify(vf) {
 4797:     var foundsomething=0;
 4798:     var founduname=0;
 4799:     var foundID=0;
 4800:     for (i=0;i<=vf.nfields.value;i++) {
 4801:       tw=eval('vf.f'+i+'.selectedIndex');
 4802:       if (i==0 && tw!=0) { foundID=1; }
 4803:       if (i==1 && tw!=0) { founduname=1; }
 4804:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4805:     }
 4806:     if (founduname==0 && foundID==0) {
 4807: 	alert('$error1');
 4808: 	return;
 4809:     }
 4810:     if (foundsomething==0) {
 4811: 	alert('$error2');
 4812: 	return;
 4813:     }
 4814:     vf.submit();
 4815:   }
 4816:   function flip(vf,tf) {
 4817:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4818:     var i;
 4819:     for (i=0;i<=vf.nfields.value;i++) {
 4820:       //can not pick the same destination field for both name and domain
 4821:       if (((i ==0)||(i ==1)) && 
 4822:           ((tf==0)||(tf==1)) && 
 4823:           (i!=tf) &&
 4824:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4825:         eval('vf.f'+i+'.selectedIndex=0;')
 4826:       }
 4827:     }
 4828:   }
 4829: ENDPICK
 4830: }
 4831: 
 4832: sub csvupload_javascript_forward_associate {
 4833:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4834:     my $error2=&mt('You need to specify at least one grading field');
 4835:   &js_escape(\$error1);
 4836:   &js_escape(\$error2);
 4837:   return(<<ENDPICK);
 4838:   function verify(vf) {
 4839:     var foundsomething=0;
 4840:     var founduname=0;
 4841:     var foundID=0;
 4842:     for (i=0;i<=vf.nfields.value;i++) {
 4843:       tw=eval('vf.f'+i+'.selectedIndex');
 4844:       if (tw==1) { foundID=1; }
 4845:       if (tw==2) { founduname=1; }
 4846:       if (tw>3) { foundsomething=1; }
 4847:     }
 4848:     if (founduname==0 && foundID==0) {
 4849: 	alert('$error1');
 4850: 	return;
 4851:     }
 4852:     if (foundsomething==0) {
 4853: 	alert('$error2');
 4854: 	return;
 4855:     }
 4856:     vf.submit();
 4857:   }
 4858:   function flip(vf,tf) {
 4859:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4860:     var i;
 4861:     //can not pick the same destination field twice
 4862:     for (i=0;i<=vf.nfields.value;i++) {
 4863:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4864:         eval('vf.f'+i+'.selectedIndex=0;')
 4865:       }
 4866:     }
 4867:   }
 4868: ENDPICK
 4869: }
 4870: 
 4871: sub csvuploadmap_header {
 4872:     my ($request,$symb,$datatoken,$distotal)= @_;
 4873:     my $javascript;
 4874:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4875: 	$javascript=&csvupload_javascript_reverse_associate();
 4876:     } else {
 4877: 	$javascript=&csvupload_javascript_forward_associate();
 4878:     }
 4879: 
 4880:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4881:     my $ignore=&mt('Ignore First Line');
 4882:     $symb = &Apache::lonenc::check_encrypt($symb);
 4883:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4884:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4885:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4886:     my $reverse=&mt("Reverse Association");
 4887:     $request->print(<<ENDPICK);
 4888: <br />
 4889: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4890: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4891: <input type="hidden" name="associate"  value="" />
 4892: <input type="hidden" name="phase"      value="three" />
 4893: <input type="hidden" name="datatoken"  value="$datatoken" />
 4894: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4895: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4896: <input type="hidden" name="upfile_associate" 
 4897:                                        value="$env{'form.upfile_associate'}" />
 4898: <input type="hidden" name="symb"       value="$symb" />
 4899: <input type="hidden" name="command"    value="csvuploadoptions" />
 4900: <hr />
 4901: ENDPICK
 4902:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4903:     return '';
 4904: 
 4905: }
 4906: 
 4907: sub csvupload_fields {
 4908:     my ($symb,$errorref) = @_;
 4909:     my $toolsymb;
 4910:     if ($symb =~ /ext\.tool$/) {
 4911:         $toolsymb = $symb;
 4912:     }
 4913:     my (@parts) = &getpartlist($symb,$errorref);
 4914:     if (ref($errorref)) {
 4915:         if ($$errorref) {
 4916:             return;
 4917:         }
 4918:     }
 4919: 
 4920:     my @fields=(['ID','Student/Employee ID'],
 4921: 		['username','Student Username'],
 4922: 		['domain','Student Domain']);
 4923:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4924:     foreach my $part (sort(@parts)) {
 4925: 	my @datum;
 4926: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4927: 	my $name=$part;
 4928: 	if  (!$display) { $display = $name; }
 4929: 	@datum=($name,$display);
 4930: 	if ($name=~/^stores_(.*)_awarded/) {
 4931: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4932: 	}
 4933: 	push(@fields,\@datum);
 4934:     }
 4935:     return (@fields);
 4936: }
 4937: 
 4938: sub csvuploadmap_footer {
 4939:     my ($request,$i,$keyfields) =@_;
 4940:     my $buttontext = &mt('Assign Grades');
 4941:     $request->print(<<ENDPICK);
 4942: </table>
 4943: <input type="hidden" name="nfields" value="$i" />
 4944: <input type="hidden" name="keyfields" value="$keyfields" />
 4945: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4946: </form>
 4947: ENDPICK
 4948: }
 4949: 
 4950: sub checkforfile_js {
 4951:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4952:     &js_escape(\$alertmsg);
 4953:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4954:     function checkUpload(formname) {
 4955: 	if (formname.upfile.value == "") {
 4956: 	    alert("$alertmsg");
 4957: 	    return false;
 4958: 	}
 4959: 	formname.submit();
 4960:     }
 4961: CSVFORMJS
 4962:     return $result;
 4963: }
 4964: 
 4965: sub upcsvScores_form {
 4966:     my ($request,$symb) = @_;
 4967:     if (!$symb) {return '';}
 4968:     my $result=&checkforfile_js();
 4969:     $result.=&Apache::loncommon::start_data_table().
 4970:              &Apache::loncommon::start_data_table_header_row().
 4971:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4972:              &Apache::loncommon::end_data_table_header_row().
 4973:              &Apache::loncommon::start_data_table_row().'<td>';
 4974:     my $upload=&mt("Upload Scores");
 4975:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4976:     my $ignore=&mt('Ignore First Line');
 4977:     $symb = &Apache::lonenc::check_encrypt($symb);
 4978:     $result.=<<ENDUPFORM;
 4979: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4980: <input type="hidden" name="symb" value="$symb" />
 4981: <input type="hidden" name="command" value="csvuploadmap" />
 4982: $upfile_select
 4983: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4984: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4985: </form>
 4986: ENDUPFORM
 4987:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4988:                            &mt("How do I create a CSV file from a spreadsheet")).
 4989:             '</td>'.
 4990:             &Apache::loncommon::end_data_table_row().
 4991:             &Apache::loncommon::end_data_table();
 4992:     return $result;
 4993: }
 4994: 
 4995: 
 4996: sub csvuploadmap {
 4997:     my ($request,$symb) = @_;
 4998:     if (!$symb) {return '';}
 4999: 
 5000:     my $datatoken;
 5001:     if (!$env{'form.datatoken'}) {
 5002: 	$datatoken=&Apache::loncommon::upfile_store($request);
 5003:     } else {
 5004:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 5005:         if ($datatoken ne '') { 
 5006: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 5007:         }
 5008:     }
 5009:     my @records=&Apache::loncommon::upfile_record_sep();
 5010:     if ($env{'form.noFirstLine'}) { shift(@records); }
 5011:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 5012:     my ($i,$keyfields);
 5013:     if (@records) {
 5014:         my $fieldserror;
 5015: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 5016:         if ($fieldserror) {
 5017:             $request->print(&navmap_errormsg());
 5018:             return;
 5019:         }
 5020: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 5021: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 5022: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 5023: 							  \@fields);
 5024: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 5025: 	    chop($keyfields);
 5026: 	} else {
 5027: 	    unshift(@fields,['none','']);
 5028: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 5029: 							    \@fields);
 5030:             foreach my $rec (@records) {
 5031:                 my %temp = &Apache::loncommon::record_sep($rec);
 5032:                 if (%temp) {
 5033:                     $keyfields=join(',',sort(keys(%temp)));
 5034:                     last;
 5035:                 }
 5036:             }
 5037: 	}
 5038:     }
 5039:     &csvuploadmap_footer($request,$i,$keyfields);
 5040: 
 5041:     return '';
 5042: }
 5043: 
 5044: sub csvuploadoptions {
 5045:     my ($request,$symb)= @_;
 5046:     my $overwrite=&mt('Overwrite any existing score');
 5047:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 5048:     my $ignore=&mt('Ignore First Line');
 5049:     $request->print(<<ENDPICK);
 5050: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 5051: <input type="hidden" name="command"    value="csvuploadassign" />
 5052: <p>
 5053: <label>
 5054:    <input type="checkbox" name="overwite_scores" checked="checked" />
 5055:    $overwrite
 5056: </label>
 5057: </p>
 5058: ENDPICK
 5059:     my %fields=&get_fields();
 5060:     if (!defined($fields{'domain'})) {
 5061: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 5062:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 5063:     }
 5064:     foreach my $key (sort(keys(%env))) {
 5065: 	if ($key !~ /^form\.(.*)$/) { next; }
 5066: 	my $cleankey=$1;
 5067: 	if ($cleankey eq 'command') { next; }
 5068: 	$request->print('<input type="hidden" name="'.$cleankey.
 5069: 			'"  value="'.$env{$key}.'" />'."\n");
 5070:     }
 5071:     # FIXME do a check for any duplicated user ids...
 5072:     # FIXME do a check for any invalid user ids?...
 5073:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 5074: <hr /></form>'."\n");
 5075:     return '';
 5076: }
 5077: 
 5078: sub get_fields {
 5079:     my %fields;
 5080:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 5081:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 5082: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 5083: 	    if ($env{'form.f'.$i} ne 'none') {
 5084: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 5085: 	    }
 5086: 	} else {
 5087: 	    if ($env{'form.f'.$i} ne 'none') {
 5088: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 5089: 	    }
 5090: 	}
 5091:     }
 5092:     return %fields;
 5093: }
 5094: 
 5095: sub csvuploadassign {
 5096:     my ($request,$symb) = @_;
 5097:     if (!$symb) {return '';}
 5098:     my $error_msg = '';
 5099:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 5100:     if ($datatoken ne '') {
 5101:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 5102:     }
 5103:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 5104:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 5105:     my %fields=&get_fields();
 5106:     my $courseid=$env{'request.course.id'};
 5107:     my ($classlist) = &getclasslist('all',0);
 5108:     my @notallowed;
 5109:     my @skipped;
 5110:     my @warnings;
 5111:     my $countdone=0;
 5112:     foreach my $grade (@gradedata) {
 5113: 	my %entries=&Apache::loncommon::record_sep($grade);
 5114: 	my $domain;
 5115: 	if ($entries{$fields{'domain'}}) {
 5116: 	    $domain=$entries{$fields{'domain'}};
 5117: 	} else {
 5118: 	    $domain=$env{'form.default_domain'};
 5119: 	}
 5120: 	$domain=~s/\s//g;
 5121: 	my $username=$entries{$fields{'username'}};
 5122: 	$username=~s/\s//g;
 5123: 	if (!$username) {
 5124: 	    my $id=$entries{$fields{'ID'}};
 5125: 	    $id=~s/\s//g;
 5126: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 5127: 	    $username=$ids{$id};
 5128: 	}
 5129: 	if (!exists($$classlist{"$username:$domain"})) {
 5130: 	    my $id=$entries{$fields{'ID'}};
 5131: 	    $id=~s/\s//g;
 5132: 	    if ($id) {
 5133: 		push(@skipped,"$id:$domain");
 5134: 	    } else {
 5135: 		push(@skipped,"$username:$domain");
 5136: 	    }
 5137: 	    next;
 5138: 	}
 5139: 	my $usec=$classlist->{"$username:$domain"}[5];
 5140: 	if (!&canmodify($usec)) {
 5141: 	    push(@notallowed,"$username:$domain");
 5142: 	    next;
 5143: 	}
 5144: 	my %points;
 5145: 	my %grades;
 5146: 	foreach my $dest (keys(%fields)) {
 5147: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5148: 		$dest eq 'domain') { next; }
 5149: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5150: 	    if ($dest=~/stores_(.*)_points/) {
 5151: 		my $part=$1;
 5152: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5153: 					      $symb,$domain,$username);
 5154:                 if ($wgt) {
 5155:                     $entries{$fields{$dest}}=~s/\s//g;
 5156:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5157:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5158:                                           : 'correct_by_override';
 5159:                     if ($pcr>1) {
 5160:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5161:                     }
 5162:                     $grades{"resource.$part.awarded"}=$pcr;
 5163:                     $grades{"resource.$part.solved"}=$award;
 5164:                     $points{$part}=1;
 5165:                 } else {
 5166:                     $error_msg = "<br />" .
 5167:                         &mt("Some point values were assigned"
 5168:                             ." for problems with a weight "
 5169:                             ."of zero. These values were "
 5170:                             ."ignored.");
 5171:                 }
 5172: 	    } else {
 5173: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5174: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5175: 		my $store_key=$dest;
 5176: 		$store_key=~s/^stores/resource/;
 5177: 		$store_key=~s/_/\./g;
 5178: 		$grades{$store_key}=$entries{$fields{$dest}};
 5179: 	    }
 5180: 	}
 5181: 	if (! %grades) {
 5182:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5183:         } else {
 5184: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5185: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5186: 					   $env{'request.course.id'},
 5187: 					   $domain,$username);
 5188: 	   if ($result eq 'ok') {
 5189: # Successfully stored
 5190: 	      $request->print('.');
 5191: # Remove from grading queue
 5192:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5193:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5194:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5195:                                              $domain,$username);
 5196: 	   } else {
 5197: 	      $request->print("<p><span class=\"LC_error\">".
 5198:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5199:                                   "$username:$domain",$result)."</span></p>");
 5200: 	   }
 5201: 	   $request->rflush();
 5202: 	   $countdone++;
 5203:         }
 5204:     }
 5205:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5206:     if (@warnings) {
 5207:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5208:         $request->print(join(', ',@warnings));
 5209:     }
 5210:     if (@skipped) {
 5211: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5212:         $request->print(join(', ',@skipped));
 5213:     }
 5214:     if (@notallowed) {
 5215: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5216: 	$request->print(join(', ',@notallowed));
 5217:     }
 5218:     $request->print("<br />\n");
 5219:     return $error_msg;
 5220: }
 5221: #------------- end of section for handling csv file upload ---------
 5222: #
 5223: #-------------------------------------------------------------------
 5224: #
 5225: #-------------- Next few routines handle grading by page/sequence
 5226: #
 5227: #--- Select a page/sequence and a student to grade
 5228: sub pickStudentPage {
 5229:     my ($request,$symb) = @_;
 5230: 
 5231:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5232:     &js_escape(\$alertmsg);
 5233:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5234: 
 5235: function checkPickOne(formname) {
 5236:     if (radioSelection(formname.student) == null) {
 5237: 	alert("$alertmsg");
 5238: 	return;
 5239:     }
 5240:     ptr = pullDownSelection(formname.selectpage);
 5241:     formname.page.value = formname["page"+ptr].value;
 5242:     formname.title.value = formname["title"+ptr].value;
 5243:     formname.submit();
 5244: }
 5245: 
 5246: LISTJAVASCRIPT
 5247:     &commonJSfunctions($request);
 5248: 
 5249:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5250:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5251:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5252:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5253: 
 5254:     my $result='<h3><span class="LC_info">&nbsp;'.
 5255: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5256: 
 5257:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5258:     my $map_error;
 5259:     my ($titles,$symbx) = &getSymbMap($map_error);
 5260:     if ($map_error) {
 5261:         $request->print(&navmap_errormsg());
 5262:         return; 
 5263:     }
 5264:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5265: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5266: #    my $type=($curpage =~ /\.(page|sequence)/);
 5267: 
 5268:     # Collection of hidden fields
 5269:     my $ctr=0;
 5270:     foreach (@$titles) {
 5271: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5272: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5273: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5274: 	$ctr++;
 5275:     }
 5276:     $result.='<input type="hidden" name="page" />'."\n".
 5277: 	'<input type="hidden" name="title" />'."\n";
 5278: 
 5279:     $result.=&build_section_inputs();
 5280:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5281:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5282:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5283:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5284: 
 5285:     # Show grading options
 5286:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5287:     my $select = '<select name="selectpage">'."\n";
 5288:     $ctr=0;
 5289:     foreach (@$titles) {
 5290:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5291:         $select.='<option value="'.$ctr.'"'.
 5292:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5293:             '>'.$showtitle.'</option>'."\n";
 5294:         $ctr++;
 5295:     }
 5296:     $select.= '</select>';
 5297: 
 5298:     $result.=
 5299:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5300:        .$select
 5301:        .&Apache::lonhtmlcommon::row_closure();
 5302: 
 5303:     $result.=
 5304:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5305:        .'<label><input type="radio" name="vProb" value="no"'
 5306:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5307:        .'<label><input type="radio" name="vProb" value="yes" />'
 5308:            .&mt('yes').'</label>'."\n"
 5309:        .&Apache::lonhtmlcommon::row_closure();
 5310: 
 5311:     $result.=
 5312:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5313:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5314:            .&mt('none').' </label>'."\n"
 5315:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5316:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5317:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5318:            .&mt('all submissions with details').' </label>'
 5319:        .&Apache::lonhtmlcommon::row_closure();
 5320: 
 5321:     $result.=
 5322:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5323:        .'<input type="text" name="CODE" value="" />'
 5324:        .&Apache::lonhtmlcommon::row_closure(1)
 5325:        .&Apache::lonhtmlcommon::end_pick_box();
 5326: 
 5327:     # Show list of students to select for grading
 5328:     $result.='<br /><input type="button" '.
 5329:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5330: 
 5331:     $request->print($result);
 5332: 
 5333:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5334: 	&Apache::loncommon::start_data_table().
 5335: 	&Apache::loncommon::start_data_table_header_row().
 5336: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5337: 	'<th>'.&nameUserString('header').'</th>'.
 5338: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5339: 	'<th>'.&nameUserString('header').'</th>'.
 5340: 	&Apache::loncommon::end_data_table_header_row();
 5341:  
 5342:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5343:     my $ptr = 1;
 5344:     foreach my $student (sort 
 5345: 			 {
 5346: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5347: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5348: 			     }
 5349: 			     return $a cmp $b;
 5350: 			 } (keys(%$fullname))) {
 5351: 	my ($uname,$udom) = split(/:/,$student);
 5352: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5353:                                   : '</td>');
 5354: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5355: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5356: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5357: 	$studentTable.=
 5358: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5359:                          : '');
 5360: 	$ptr++;
 5361:     }
 5362:     if ($ptr%2 == 0) {
 5363: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5364: 	    &Apache::loncommon::end_data_table_row();
 5365:     }
 5366:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5367:     $studentTable.='<input type="button" '.
 5368:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5369: 
 5370:     $request->print($studentTable);
 5371: 
 5372:     return '';
 5373: }
 5374: 
 5375: sub getSymbMap {
 5376:     my ($map_error) = @_;
 5377:     my $navmap = Apache::lonnavmaps::navmap->new();
 5378:     unless (ref($navmap)) {
 5379:         if (ref($map_error)) {
 5380:             $$map_error = 'navmap';
 5381:         }
 5382:         return;
 5383:     }
 5384:     my %symbx = ();
 5385:     my @titles = ();
 5386:     my $minder = 0;
 5387: 
 5388:     # Gather every sequence that has problems.
 5389:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5390: 					       1,0,1);
 5391:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5392: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5393: 	    my $title = $minder.'.'.
 5394: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5395: 	    push(@titles, $title); # minder in case two titles are identical
 5396: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5397: 	    $minder++;
 5398: 	}
 5399:     }
 5400:     return \@titles,\%symbx;
 5401: }
 5402: 
 5403: #
 5404: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5405: sub displayPage {
 5406:     my ($request,$symb) = @_;
 5407:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5408:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5409:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5410:     my $pageTitle = $env{'form.page'};
 5411:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5412:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5413:     my $usec=$classlist->{$env{'form.student'}}[5];
 5414: 
 5415:     #need to make sure we have the correct data for later EXT calls, 
 5416:     #thus invalidate the cache
 5417:     &Apache::lonnet::devalidatecourseresdata(
 5418:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5419:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5420:     &Apache::lonnet::clear_EXT_cache_status();
 5421: 
 5422:     if (!&canview($usec)) {
 5423: 	$request->print(
 5424:             '<span class="LC_warning">'.
 5425:             &mt('Unable to view requested student. ([_1])',
 5426:                 $env{'form.student'}).
 5427:             '</span>');
 5428:         return;
 5429:     }
 5430:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5431:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5432: 	'</h3>'."\n";
 5433:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5434:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5435: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5436:     } else {
 5437: 	delete($env{'form.CODE'});
 5438:     }
 5439:     &sub_page_js($request);
 5440:     $request->print($result);
 5441: 
 5442:     my $navmap = Apache::lonnavmaps::navmap->new();
 5443:     unless (ref($navmap)) {
 5444:         $request->print(&navmap_errormsg());
 5445:         return;
 5446:     }
 5447:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5448:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5449:     if (!$map) {
 5450: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5451: 	return; 
 5452:     }
 5453:     my $iterator = $navmap->getIterator($map->map_start(),
 5454: 					$map->map_finish());
 5455: 
 5456:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5457: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5458: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5459: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5460: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5461: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5462: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5463: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5464: 
 5465:     if (defined($env{'form.CODE'})) {
 5466: 	$studentTable.=
 5467: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5468:     }
 5469:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5470: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5471: 
 5472:     $studentTable.='&nbsp;<span class="LC_info">'.
 5473:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5474:         '</span>'."\n".
 5475: 	&Apache::loncommon::start_data_table().
 5476: 	&Apache::loncommon::start_data_table_header_row().
 5477: 	'<th>'.&mt('Prob.').'</th>'.
 5478: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5479: 	&Apache::loncommon::end_data_table_header_row();
 5480: 
 5481:     &Apache::lonxml::clear_problem_counter();
 5482:     my ($depth,$question,$prob) = (1,1,1);
 5483:     $iterator->next(); # skip the first BEGIN_MAP
 5484:     my $curRes = $iterator->next(); # for "current resource"
 5485:     while ($depth > 0) {
 5486:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5487:         if($curRes == $iterator->END_MAP) { $depth--; }
 5488: 
 5489:         if (ref($curRes) && $curRes->is_gradable()) {
 5490: 	    my $parts = $curRes->parts();
 5491:             my $title = $curRes->compTitle();
 5492: 	    my $symbx = $curRes->symb();
 5493:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5494: 	    $studentTable.=
 5495: 		&Apache::loncommon::start_data_table_row().
 5496: 		'<td align="center" valign="top" >'.$prob.
 5497: 		(scalar(@{$parts}) == 1 ? '' 
 5498: 		                        : '<br />('.&mt('[_1]parts',
 5499: 							scalar(@{$parts}).'&nbsp;').')'
 5500: 		 ).
 5501: 		 '</td>';
 5502: 	    $studentTable.='<td valign="top">';
 5503: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5504:             if ($is_tool) {
 5505:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5506:             } else {
 5507: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5508: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5509: 			   		         undef,'both',\%form);
 5510: 	        } else {
 5511: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5512: 		    $companswer =~ s|<form(.*?)>||g;
 5513: 		    $companswer =~ s|</form>||g;
 5514: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5515: #		        $companswer =~ s/$1/ /ms;
 5516: #		        $request->print('match='.$1."<br />\n");
 5517: #		    }
 5518: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5519: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5520:                 }
 5521: 	    }
 5522: 
 5523: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5524: 
 5525: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5526: 		if ($record{'version'} eq '') {
 5527:                     my $msg = &mt('No recorded submission for this problem.');
 5528:                     if ($is_tool) {
 5529:                         $msg = &mt('No recorded transactions for this external tool');
 5530:                     }
 5531: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5532: 		} else {
 5533: 		    my %responseType = ();
 5534: 		    foreach my $partid (@{$parts}) {
 5535: 			my @responseIds =$curRes->responseIds($partid);
 5536: 			my @responseType =$curRes->responseType($partid);
 5537: 			my %responseIds;
 5538: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5539: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5540: 			}
 5541: 			$responseType{$partid} = \%responseIds;
 5542: 		    }
 5543: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5544: 
 5545: 		}
 5546: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5547: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5548:                 my $identifier = (&canmodify($usec)? $prob : '');
 5549: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5550: 									$env{'request.course.id'},
 5551: 									'','.submission',undef,
 5552:                                                                         $usec,$identifier);
 5553:  
 5554: 	    }
 5555: 	    if (&canmodify($usec)) {
 5556:             $studentTable.=&gradeBox_start();
 5557: 		foreach my $partid (@{$parts}) {
 5558: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5559: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5560: 		    $question++;
 5561: 		}
 5562:             $studentTable.=&gradeBox_end();
 5563: 		$prob++;
 5564: 	    }
 5565: 	    $studentTable.='</td></tr>';
 5566: 
 5567: 	}
 5568:         $curRes = $iterator->next();
 5569:     }
 5570:     my $disabled;
 5571:     unless (&canmodify($usec)) {
 5572:         $disabled = ' disabled="disabled"';
 5573:     }
 5574: 
 5575:     $studentTable.=
 5576:         '</table>'."\n".
 5577:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5578:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5579:         '</form>'."\n";
 5580:     $request->print($studentTable);
 5581: 
 5582:     return '';
 5583: }
 5584: 
 5585: sub displaySubByDates {
 5586:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5587:     my $isCODE=0;
 5588:     my $isTask = ($symb =~/\.task$/);
 5589:     my $is_tool = ($symb =~/\.tool$/);
 5590:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5591:     my $studentTable=&Apache::loncommon::start_data_table().
 5592: 	&Apache::loncommon::start_data_table_header_row().
 5593: 	'<th>'.&mt('Date/Time').'</th>'.
 5594: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5595:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5596: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5597: 	'<th>'.&mt('Status').'</th>'.
 5598: 	&Apache::loncommon::end_data_table_header_row();
 5599:     my ($version);
 5600:     my %mark;
 5601:     my %orders;
 5602:     $mark{'correct_by_student'} = $checkIcon;
 5603:     if (!exists($$record{'1:timestamp'})) {
 5604:         if ($is_tool) {
 5605:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5606:         } else {
 5607: 	    return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5608:         }
 5609:     }
 5610: 
 5611:     my $interaction;
 5612:     my $no_increment = 1;
 5613:     my (%lastrndseed,%lasttype);
 5614:     for ($version=1;$version<=$$record{'version'};$version++) {
 5615: 	my $timestamp = 
 5616: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5617: 	if (exists($$record{$version.':resource.0.version'})) {
 5618: 	    $interaction = $$record{$version.':resource.0.version'};
 5619: 	}
 5620:         if ($isTask && $env{'form.previousversion'}) {
 5621:             next unless ($interaction == $env{'form.previousversion'});
 5622:         }
 5623: 	my $where = ($isTask ? "$version:resource.$interaction"
 5624: 		             : "$version:resource");
 5625: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5626: 	    '<td>'.$timestamp.'</td>';
 5627: 	if ($isCODE) {
 5628: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5629: 	}
 5630:         if ($isTask) {
 5631:             $studentTable.='<td>'.$interaction.'</td>';
 5632:         }
 5633: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5634: 	my @displaySub = ();
 5635: 	foreach my $partid (@{$parts}) {
 5636:             my ($hidden,$type);
 5637:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5638:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5639:                 $hidden = 1;
 5640:             }
 5641: 	    my @matchKey;
 5642:             if ($isTask) {
 5643:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5644:             } elsif ($is_tool) {
 5645:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5646:             } else {
 5647: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5648:             }
 5649: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5650: 	    my $display_part=&get_display_part($partid,$symb);
 5651: 	    foreach my $matchKey (@matchKey) {
 5652: 		if (exists($$record{$version.':'.$matchKey}) &&
 5653: 		    $$record{$version.':'.$matchKey} ne '') {
 5654:                     if ($is_tool) {
 5655:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5656:                     } else {
 5657: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5658: 			    	                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5659:                         $displaySub[0].='<span class="LC_nobreak">';
 5660:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5661:                                        .' <span class="LC_internal_info">'
 5662:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5663:                                        .'</span>'
 5664:                                        .' <b>';
 5665:                         if ($hidden) {
 5666:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5667:                         } else {
 5668:                             my ($trial,$rndseed,$newvariation);
 5669:                             if ($type eq 'randomizetry') {
 5670:                                 $trial = $$record{"$where.$partid.tries"};
 5671:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5672:                             }
 5673: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5674: 			        $displaySub[0].=&mt('Trial not counted');
 5675: 		            } else {
 5676: 			        $displaySub[0].=&mt('Trial: [_1]',
 5677: 				    	        $$record{"$where.$partid.tries"});
 5678:                                 if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5679:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5680:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5681:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5682:                                     }
 5683:                                 }
 5684:                                 $lastrndseed{$partid} = $rndseed;
 5685:                                 $lasttype{$partid} = $type;
 5686: 		           }
 5687: 		           my $responseType=($isTask ? 'Task'
 5688:                                                   : $responseType->{$partid}->{$responseId});
 5689: 		           if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5690: 		           if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5691: 			       $orders{$partid}->{$responseId}=
 5692: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5693:                                                $no_increment,$type,$trial,$rndseed);
 5694: 		            }
 5695: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5696: 		            $displaySub[0].='&nbsp; '.
 5697: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5698:                         }
 5699:                     }
 5700: 		}
 5701: 	    }
 5702: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5703: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5704: 				    $$record{"$where.$partid.checkedin"},
 5705: 				    $$record{"$where.$partid.checkedin.slot"}).
 5706: 					'<br />';
 5707: 	    }
 5708: 	    if (exists $$record{"$where.$partid.award"}) {
 5709: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5710: 		    lc($$record{"$where.$partid.award"}).' '.
 5711: 		    $mark{$$record{"$where.$partid.solved"}}.
 5712: 		    '<br />';
 5713:             } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5714:                 if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5715:                     $displaySub[1].=&mt('Grade passed back by external tool');
 5716:                 }
 5717: 	    }
 5718: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5719: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5720:                 unless ($is_tool) {
 5721: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5722:                 }
 5723: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5724: 		$displaySub[2].=
 5725: 		    $$record{"$version:resource.$partid.regrader"};
 5726:                 unless ($is_tool) {
 5727: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5728:                 }
 5729: 	    }
 5730: 	}
 5731: 	# needed because old essay regrader has not parts info
 5732: 	if (exists $$record{"$version:resource.regrader"}) {
 5733: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5734: 	}
 5735: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5736: 	if ($displaySub[2]) {
 5737: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5738: 	}
 5739: 	$studentTable.='&nbsp;</td>'.
 5740: 	    &Apache::loncommon::end_data_table_row();
 5741:     }
 5742:     $studentTable.=&Apache::loncommon::end_data_table();
 5743:     return $studentTable;
 5744: }
 5745: 
 5746: sub updateGradeByPage {
 5747:     my ($request,$symb) = @_;
 5748: 
 5749:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5750:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5751:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5752:     my $pageTitle = $env{'form.page'};
 5753:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5754:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5755:     my $usec=$classlist->{$env{'form.student'}}[5];
 5756:     if (!&canmodify($usec)) {
 5757: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5758: 	return;
 5759:     }
 5760:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5761:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5762: 	'</h3>'."\n";
 5763: 
 5764:     $request->print($result);
 5765: 
 5766: 
 5767:     my $navmap = Apache::lonnavmaps::navmap->new();
 5768:     unless (ref($navmap)) {
 5769:         $request->print(&navmap_errormsg());
 5770:         return;
 5771:     }
 5772:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5773:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5774:     if (!$map) {
 5775: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5776: 	return; 
 5777:     }
 5778:     my $iterator = $navmap->getIterator($map->map_start(),
 5779: 					$map->map_finish());
 5780: 
 5781:     my $studentTable=
 5782: 	&Apache::loncommon::start_data_table().
 5783: 	&Apache::loncommon::start_data_table_header_row().
 5784: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5785: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5786: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5787: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5788: 	&Apache::loncommon::end_data_table_header_row();
 5789: 
 5790:     $iterator->next(); # skip the first BEGIN_MAP
 5791:     my $curRes = $iterator->next(); # for "current resource"
 5792:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5793:     while ($depth > 0) {
 5794:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5795:         if($curRes == $iterator->END_MAP) { $depth--; }
 5796: 
 5797:         if (ref($curRes) && $curRes->is_problem()) {
 5798: 	    my $parts = $curRes->parts();
 5799:             my $title = $curRes->compTitle();
 5800: 	    my $symbx = $curRes->symb();
 5801: 	    $studentTable.=
 5802: 		&Apache::loncommon::start_data_table_row().
 5803: 		'<td align="center" valign="top" >'.$prob.
 5804: 		(scalar(@{$parts}) == 1 ? '' 
 5805:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5806: 		.')').'</td>';
 5807: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5808: 
 5809: 	    my %newrecord=();
 5810: 	    my @displayPts=();
 5811:             my %aggregate = ();
 5812:             my $aggregateflag = 0;
 5813:             my %queueable;
 5814:             if ($env{'form.HIDE'.$prob}) {
 5815:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5816:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5817:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5818:                 $hideflag += $numchgs;
 5819:             }
 5820: 	    foreach my $partid (@{$parts}) {
 5821: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5822: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5823:                 my @types = $curRes->responseType($partid);
 5824:                 if (grep(/^essay$/,@types)) {
 5825:                     $queueable{$partid} = 1;
 5826:                 } else {
 5827:                     my @ids = $curRes->responseIds($partid);
 5828:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5829:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
 5830:                                                           '.handgrade',$symb);
 5831:                         if (lc($hndgrd) eq 'yes') {
 5832:                             $queueable{$partid} = 1;
 5833:                             last;
 5834:                         }
 5835:                     }
 5836:                 }
 5837: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5838: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5839: 		my $partial = $newpts/$wgt;
 5840: 		my $score;
 5841: 		if ($partial > 0) {
 5842: 		    $score = 'correct_by_override';
 5843: 		} elsif ($newpts ne '') { #empty is taken as 0
 5844: 		    $score = 'incorrect_by_override';
 5845: 		}
 5846: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5847: 		if ($dropMenu eq 'excused') {
 5848: 		    $partial = '';
 5849: 		    $score = 'excused';
 5850: 		} elsif ($dropMenu eq 'reset status'
 5851: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5852: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5853: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5854: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5855: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5856: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5857: 		    $changeflag++;
 5858: 		    $newpts = '';
 5859:                     
 5860:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5861:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5862:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5863:                     if ($aggtries > 0) {
 5864:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5865:                         $aggregateflag = 1;
 5866:                     }
 5867: 		}
 5868: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5869: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5870: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5871: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5872: 		    '&nbsp;<br />';
 5873: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5874: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5875: 		    '&nbsp;<br />';
 5876: 		$question++;
 5877: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5878: 
 5879: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5880: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5881: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5882: 		    if (scalar(keys(%newrecord)) > 0);
 5883: 
 5884: 		$changeflag++;
 5885: 	    }
 5886: 	    if (scalar(keys(%newrecord)) > 0) {
 5887: 		my %record = 
 5888: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5889: 					     $udom,$uname);
 5890: 
 5891: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5892: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5893: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5894: 		    $newrecord{'resource.CODE'} = '';
 5895: 		}
 5896: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5897: 					$udom,$uname);
 5898: 		%record = &Apache::lonnet::restore($symbx,
 5899: 						   $env{'request.course.id'},
 5900: 						   $udom,$uname);
 5901: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5902: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5903: 	    }
 5904: 	    
 5905:             if ($aggregateflag) {
 5906:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5907:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5908:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5909:             }
 5910: 
 5911: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5912: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5913: 		&Apache::loncommon::end_data_table_row();
 5914: 
 5915: 	    $prob++;
 5916: 	}
 5917:         $curRes = $iterator->next();
 5918:     }
 5919: 
 5920:     $studentTable.=&Apache::loncommon::end_data_table();
 5921:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5922: 		  &mt('The scores were changed for [quant,_1,problem].',
 5923: 		  $changeflag).'<br />');
 5924:     my $hidemsg=($hideflag == 0 ? '' :
 5925:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5926:                      $hideflag).'<br />');
 5927:     $request->print($hidemsg.$grademsg.$studentTable);
 5928: 
 5929:     return '';
 5930: }
 5931: 
 5932: #-------- end of section for handling grading by page/sequence ---------
 5933: #
 5934: #-------------------------------------------------------------------
 5935: 
 5936: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5937: #
 5938: #------ start of section for handling grading by page/sequence ---------
 5939: 
 5940: =pod
 5941: 
 5942: =head1 Bubble sheet grading routines
 5943: 
 5944:   For this documentation:
 5945: 
 5946:    'scanline' refers to the full line of characters
 5947:    from the file that we are parsing that represents one entire sheet
 5948: 
 5949:    'bubble line' refers to the data
 5950:    representing the line of bubbles that are on the physical bubblesheet
 5951: 
 5952: 
 5953: The overall process is that a scanned in bubblesheet data is uploaded
 5954: into a course. When a user wants to grade, they select a
 5955: sequence/folder of resources, a file of bubblesheet info, and pick
 5956: one of the predefined configurations for what each scanline looks
 5957: like.
 5958: 
 5959: Next each scanline is checked for any errors of either 'missing
 5960: bubbles' (it's an error because it may have been mis-scanned
 5961: because too light bubbling), 'double bubble' (each bubble line should
 5962: have no more than one letter picked), invalid or duplicated CODE,
 5963: invalid student/employee ID
 5964: 
 5965: If the CODE option is used that determines the randomization of the
 5966: homework problems, either way the student/employee ID is looked up into a
 5967: username:domain.
 5968: 
 5969: During the validation phase the instructor can choose to skip scanlines. 
 5970: 
 5971: After the validation phase, there are now 3 bubblesheet files
 5972: 
 5973:   scantron_original_filename (unmodified original file)
 5974:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5975:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5976: 
 5977: Also there is a separate hash nohist_scantrondata that contains extra
 5978: correction information that isn't representable in the bubblesheet
 5979: file (see &scantron_getfile() for more information)
 5980: 
 5981: After all scanlines are either valid, marked as valid or skipped, then
 5982: foreach line foreach problem in the picked sequence, an ssi request is
 5983: made that simulates a user submitting their selected letter(s) against
 5984: the homework problem.
 5985: 
 5986: =over 4
 5987: 
 5988: 
 5989: 
 5990: =item defaultFormData
 5991: 
 5992:   Returns html hidden inputs used to hold context/default values.
 5993: 
 5994:  Arguments:
 5995:   $symb - $symb of the current resource 
 5996: 
 5997: =cut
 5998: 
 5999: sub defaultFormData {
 6000:     my ($symb)=@_;
 6001:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 6002: }
 6003: 
 6004: 
 6005: =pod 
 6006: 
 6007: =item getSequenceDropDown
 6008: 
 6009:    Return html dropdown of possible sequences to grade
 6010:  
 6011:  Arguments:
 6012:    $symb - $symb of the current resource
 6013:    $map_error - ref to scalar which will container error if
 6014:                 $navmap object is unavailable in &getSymbMap().
 6015: 
 6016: =cut
 6017: 
 6018: sub getSequenceDropDown {
 6019:     my ($symb,$map_error)=@_;
 6020:     my $result='<select name="selectpage">'."\n";
 6021:     my ($titles,$symbx) = &getSymbMap($map_error);
 6022:     if (ref($map_error)) {
 6023:         return if ($$map_error);
 6024:     }
 6025:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 6026:     my $ctr=0;
 6027:     foreach (@$titles) {
 6028: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 6029: 	$result.='<option value="'.$$symbx{$_}.'" '.
 6030: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 6031: 	    '>'.$showtitle.'</option>'."\n";
 6032: 	$ctr++;
 6033:     }
 6034:     $result.= '</select>';
 6035:     return $result;
 6036: }
 6037: 
 6038: my %bubble_lines_per_response;     # no. bubble lines for each response.
 6039:                                    # key is zero-based index - 0, 1, 2 ...
 6040: 
 6041: my %first_bubble_line;             # First bubble line no. for each bubble.
 6042: 
 6043: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 6044:                                    # matchresponse or rankresponse, where 
 6045:                                    # an individual response can have multiple 
 6046:                                    # lines
 6047: 
 6048: my %responsetype_per_response;     # responsetype for each response
 6049: 
 6050: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 6051:                                    # numbered response. Needed when randomorder
 6052:                                    # or randompick are in use. Key is ID, value 
 6053:                                    # is response number.
 6054: 
 6055: # Save and restore the bubble lines array to the form env.
 6056: 
 6057: 
 6058: sub save_bubble_lines {
 6059:     foreach my $line (keys(%bubble_lines_per_response)) {
 6060: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 6061: 	$env{"form.scantron.first_bubble_line.$line"} =
 6062: 	    $first_bubble_line{$line};
 6063:         $env{"form.scantron.sub_bubblelines.$line"} = 
 6064:             $subdivided_bubble_lines{$line};
 6065:         $env{"form.scantron.responsetype.$line"} =
 6066:             $responsetype_per_response{$line};
 6067:     }
 6068:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 6069:         my $line = $masterseq_id_responsenum{$resid};
 6070:         $env{"form.scantron.residpart.$line"} = $resid;
 6071:     }
 6072: }
 6073: 
 6074: 
 6075: sub restore_bubble_lines {
 6076:     my $line = 0;
 6077:     %bubble_lines_per_response = ();
 6078:     %masterseq_id_responsenum = ();
 6079:     while ($env{"form.scantron.bubblelines.$line"}) {
 6080: 	my $value = $env{"form.scantron.bubblelines.$line"};
 6081: 	$bubble_lines_per_response{$line} = $value;
 6082: 	$first_bubble_line{$line}  =
 6083: 	    $env{"form.scantron.first_bubble_line.$line"};
 6084:         $subdivided_bubble_lines{$line} =
 6085:             $env{"form.scantron.sub_bubblelines.$line"};
 6086:         $responsetype_per_response{$line} =
 6087:             $env{"form.scantron.responsetype.$line"};
 6088:         my $id = $env{"form.scantron.residpart.$line"};
 6089:         $masterseq_id_responsenum{$id} = $line;
 6090: 	$line++;
 6091:     }
 6092: }
 6093: 
 6094: =pod 
 6095: 
 6096: =item scantron_filenames
 6097: 
 6098:    Returns a list of the scantron files in the current course 
 6099: 
 6100: =cut
 6101: 
 6102: sub scantron_filenames {
 6103:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6104:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6105:     my $getpropath = 1;
 6106:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6107:                                                         $cname,$getpropath);
 6108:     my @possiblenames;
 6109:     if (ref($dirlist) eq 'ARRAY') {
 6110:         foreach my $filename (sort(@{$dirlist})) {
 6111: 	    ($filename)=split(/&/,$filename);
 6112: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6113: 	    $filename=~s/^scantron_orig_//;
 6114: 	    push(@possiblenames,$filename);
 6115:         }
 6116:     }
 6117:     return @possiblenames;
 6118: }
 6119: 
 6120: =pod 
 6121: 
 6122: =item scantron_uploads
 6123: 
 6124:    Returns  html drop-down list of scantron files in current course.
 6125: 
 6126:  Arguments:
 6127:    $file2grade - filename to set as selected in the dropdown
 6128: 
 6129: =cut
 6130: 
 6131: sub scantron_uploads {
 6132:     my ($file2grade) = @_;
 6133:     my $result=	'<select name="scantron_selectfile">';
 6134:     $result.="<option></option>";
 6135:     foreach my $filename (sort(&scantron_filenames())) {
 6136: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6137:     }
 6138:     $result.="</select>";
 6139:     return $result;
 6140: }
 6141: 
 6142: =pod 
 6143: 
 6144: =item scantron_scantab
 6145: 
 6146:   Returns html drop down of the scantron formats in the scantronformat.tab
 6147:   file.
 6148: 
 6149: =cut
 6150: 
 6151: sub scantron_scantab {
 6152:     my $result='<select name="scantron_format">'."\n";
 6153:     $result.='<option></option>'."\n";
 6154:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6155:     if (@lines > 0) {
 6156:         foreach my $line (@lines) {
 6157:             next if (($line =~ /^\#/) || ($line eq ''));
 6158: 	    my ($name,$descrip)=split(/:/,$line);
 6159: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6160:         }
 6161:     }
 6162:     $result.='</select>'."\n";
 6163:     return $result;
 6164: }
 6165: 
 6166: =pod 
 6167: 
 6168: =item scantron_CODElist
 6169: 
 6170:   Returns html drop down of the saved CODE lists from current course,
 6171:   generated from earlier printings.
 6172: 
 6173: =cut
 6174: 
 6175: sub scantron_CODElist {
 6176:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6177:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6178:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6179:     my $namechoice='<option></option>';
 6180:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6181: 	if ($name =~ /^error: 2 /) { next; }
 6182: 	if ($name =~ /^type\0/) { next; }
 6183: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6184:     }
 6185:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6186:     return $namechoice;
 6187: }
 6188: 
 6189: =pod 
 6190: 
 6191: =item scantron_CODEunique
 6192: 
 6193:   Returns the html for "Each CODE to be used once" radio.
 6194: 
 6195: =cut
 6196: 
 6197: sub scantron_CODEunique {
 6198:     my $result='<span class="LC_nobreak">
 6199:                  <label><input type="radio" name="scantron_CODEunique"
 6200:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6201:                 </span>
 6202:                 <span class="LC_nobreak">
 6203:                  <label><input type="radio" name="scantron_CODEunique"
 6204:                         value="no" />'.&mt('No').' </label>
 6205:                 </span>';
 6206:     return $result;
 6207: }
 6208: 
 6209: =pod 
 6210: 
 6211: =item scantron_selectphase
 6212: 
 6213:   Generates the initial screen to start the bubblesheet process.
 6214:   Allows for - starting a grading run.
 6215:              - downloading existing scan data (original, corrected
 6216:                                                 or skipped info)
 6217: 
 6218:              - uploading new scan data
 6219: 
 6220:  Arguments:
 6221:   $r          - The Apache request object
 6222:   $file2grade - name of the file that contain the scanned data to score
 6223: 
 6224: =cut
 6225: 
 6226: sub scantron_selectphase {
 6227:     my ($r,$file2grade,$symb) = @_;
 6228:     if (!$symb) {return '';}
 6229:     my $map_error;
 6230:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6231:     if ($map_error) {
 6232:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6233:         return;
 6234:     }
 6235:     my $default_form_data=&defaultFormData($symb);
 6236:     my $file_selector=&scantron_uploads($file2grade);
 6237:     my $format_selector=&scantron_scantab();
 6238:     my $CODE_selector=&scantron_CODElist();
 6239:     my $CODE_unique=&scantron_CODEunique();
 6240:     my $result;
 6241: 
 6242:     $ssi_error = 0;
 6243: 
 6244:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6245:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6246: 
 6247:         # Chunk of form to prompt for a scantron file upload.
 6248: 
 6249:         $r->print('
 6250:     <br />');
 6251:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6252:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6253:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6254:         &js_escape(\$alertmsg);
 6255:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6256:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6257:     function checkUpload(formname) {
 6258:         if (formname.upfile.value == "") {
 6259:             alert("'.$alertmsg.'");
 6260:             return false;
 6261:         }
 6262:         formname.submit();
 6263:     }'."\n".$formatjs));
 6264:         $r->print('
 6265:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6266:                 '.$default_form_data.'
 6267:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6268:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6269:                 <input name="command" value="scantronupload_save" type="hidden" />
 6270:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6271:               '.&Apache::loncommon::start_data_table_header_row().'
 6272:                 <th>
 6273:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6274:                 </th>
 6275:               '.&Apache::loncommon::end_data_table_header_row().'
 6276:               '.&Apache::loncommon::start_data_table_row().'
 6277:             <td>
 6278:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6279:         if ($formatoptions) {
 6280:             $r->print('</td>
 6281:                  '.&Apache::loncommon::end_data_table_row().'
 6282:                  '.&Apache::loncommon::start_data_table_row().'
 6283:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6284:                  </td>
 6285:                  '.&Apache::loncommon::end_data_table_row().'
 6286:                  '.&Apache::loncommon::start_data_table_row().'
 6287:                  <td>'
 6288:             );
 6289:         } else {
 6290:             $r->print(' <br />');
 6291:         }
 6292:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6293:               </td>
 6294:              '.&Apache::loncommon::end_data_table_row().'
 6295:              '.&Apache::loncommon::end_data_table().'
 6296:              </form>'
 6297:         );
 6298: 
 6299:     }
 6300: 
 6301:     # Chunk of form to prompt for a file to grade and how:
 6302: 
 6303:     $result.= '
 6304:     <br />
 6305:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6306:     <input type="hidden" name="command" value="scantron_warning" />
 6307:     '.$default_form_data.'
 6308:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6309:        '.&Apache::loncommon::start_data_table_header_row().'
 6310:             <th colspan="2">
 6311:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6312:             </th>
 6313:        '.&Apache::loncommon::end_data_table_header_row().'
 6314:        '.&Apache::loncommon::start_data_table_row().'
 6315:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6316:        '.&Apache::loncommon::end_data_table_row().'
 6317:        '.&Apache::loncommon::start_data_table_row().'
 6318:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6319:        '.&Apache::loncommon::end_data_table_row().'
 6320:        '.&Apache::loncommon::start_data_table_row().'
 6321:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6322:        '.&Apache::loncommon::end_data_table_row().'
 6323:        '.&Apache::loncommon::start_data_table_row().'
 6324:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6325:        '.&Apache::loncommon::end_data_table_row().'
 6326:        '.&Apache::loncommon::start_data_table_row().'
 6327:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6328:        '.&Apache::loncommon::end_data_table_row().'
 6329:        '.&Apache::loncommon::start_data_table_row().'
 6330: 	    <td> '.&mt('Options:').' </td>
 6331:             <td>
 6332: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6333:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6334:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6335: 	    </td>
 6336:        '.&Apache::loncommon::end_data_table_row().'
 6337:        '.&Apache::loncommon::start_data_table_row().'
 6338:             <td colspan="2">
 6339:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6340:             </td>
 6341:        '.&Apache::loncommon::end_data_table_row().'
 6342:     '.&Apache::loncommon::end_data_table().'
 6343:     </form>
 6344: ';
 6345:    
 6346:     $r->print($result);
 6347: 
 6348:     # Chunk of the form that prompts to view a scoring office file,
 6349:     # corrected file, skipped records in a file.
 6350: 
 6351:     $r->print('
 6352:    <br />
 6353:    <form action="/adm/grades" name="scantron_download">
 6354:      '.$default_form_data.'
 6355:      <input type="hidden" name="command" value="scantron_download" />
 6356:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6357:        '.&Apache::loncommon::start_data_table_header_row().'
 6358:               <th>
 6359:                 &nbsp;'.&mt('Download a scoring office file').'
 6360:               </th>
 6361:        '.&Apache::loncommon::end_data_table_header_row().'
 6362:        '.&Apache::loncommon::start_data_table_row().'
 6363:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6364:                 <br />
 6365:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6366:        '.&Apache::loncommon::end_data_table_row().'
 6367:      '.&Apache::loncommon::end_data_table().'
 6368:    </form>
 6369:    <br />
 6370: ');
 6371: 
 6372:     &Apache::lonpickcode::code_list($r,2);
 6373: 
 6374:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6375:              $default_form_data."\n".
 6376:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6377:              &Apache::loncommon::start_data_table_header_row()."\n".
 6378:              '<th colspan="2">
 6379:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6380:              '</th>'."\n".
 6381:               &Apache::loncommon::end_data_table_header_row()."\n".
 6382:               &Apache::loncommon::start_data_table_row()."\n".
 6383:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6384:               '<td> '.$sequence_selector.' </td>'.
 6385:               &Apache::loncommon::end_data_table_row()."\n".
 6386:               &Apache::loncommon::start_data_table_row()."\n".
 6387:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6388:               '<td> '.$file_selector.' </td>'."\n".
 6389:               &Apache::loncommon::end_data_table_row()."\n".
 6390:               &Apache::loncommon::start_data_table_row()."\n".
 6391:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6392:               '<td> '.$format_selector.' </td>'."\n".
 6393:               &Apache::loncommon::end_data_table_row()."\n".
 6394:               &Apache::loncommon::start_data_table_row()."\n".
 6395:               '<td> '.&mt('Options').' </td>'."\n".
 6396:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6397:               &Apache::loncommon::end_data_table_row()."\n".
 6398:               &Apache::loncommon::start_data_table_row()."\n".
 6399:               '<td colspan="2">'."\n".
 6400:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6401:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6402:               '</td>'."\n".
 6403:               &Apache::loncommon::end_data_table_row()."\n".
 6404:               &Apache::loncommon::end_data_table()."\n".
 6405:               '</form><br />');
 6406:     return;
 6407: }
 6408: 
 6409: =pod 
 6410: 
 6411: =item username_to_idmap
 6412: 
 6413:     creates a hash keyed by student/employee ID with values of the corresponding
 6414:     student username:domain.
 6415: 
 6416:   Arguments:
 6417: 
 6418:     $classlist - reference to the class list hash. This is a hash
 6419:                  keyed by student name:domain  whose elements are references
 6420:                  to arrays containing various chunks of information
 6421:                  about the student. (See loncoursedata for more info).
 6422: 
 6423:   Returns
 6424:     %idmap - the constructed hash
 6425: 
 6426: =cut
 6427: 
 6428: sub username_to_idmap {
 6429:     my ($classlist)= @_;
 6430:     my %idmap;
 6431:     foreach my $student (keys(%$classlist)) {
 6432:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6433:         unless ($id eq '') {
 6434:             if (!exists($idmap{$id})) {
 6435:                 $idmap{$id} = $student;
 6436:             } else {
 6437:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6438:                 if ($status eq 'Active') {
 6439:                     $idmap{$id} = $student;
 6440:                 }
 6441:             }
 6442:         }
 6443:     }
 6444:     return %idmap;
 6445: }
 6446: 
 6447: =pod
 6448: 
 6449: =item scantron_fixup_scanline
 6450: 
 6451:    Process a requested correction to a scanline.
 6452: 
 6453:   Arguments:
 6454:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6455:     $scan_data         - hash of correction information 
 6456:                           (see &scantron_getfile())
 6457:     $line              - existing scanline
 6458:     $whichline         - line number of the passed in scanline
 6459:     $field             - type of change to process 
 6460:                          (either 
 6461:                           'ID'     -> correct the student/employee ID
 6462:                           'CODE'   -> correct the CODE
 6463:                           'answer' -> fixup the submitted answers)
 6464:     
 6465:    $args               - hash of additional info,
 6466:                           - 'ID' 
 6467:                                'newid' -> studentID to use in replacement
 6468:                                           of existing one
 6469:                           - 'CODE' 
 6470:                                'CODE_ignore_dup' - set to true if duplicates
 6471:                                                    should be ignored.
 6472: 	                       'CODE' - is new code or 'use_unfound'
 6473:                                         if the existing unfound code should
 6474:                                         be used as is
 6475:                           - 'answer'
 6476:                                'response' - new answer or 'none' if blank
 6477:                                'question' - the bubble line to change
 6478:                                'questionnum' - the question identifier,
 6479:                                                may include subquestion. 
 6480: 
 6481:   Returns:
 6482:     $line - the modified scanline
 6483: 
 6484:   Side effects: 
 6485:     $scan_data - may be updated
 6486: 
 6487: =cut
 6488: 
 6489: 
 6490: sub scantron_fixup_scanline {
 6491:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6492:     if ($field eq 'ID') {
 6493: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6494: 	    return ($line,1,'New value too large');
 6495: 	}
 6496: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6497: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6498: 				     $args->{'newid'});
 6499: 	}
 6500: 	substr($line,$$scantron_config{'IDstart'}-1,
 6501: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6502: 	if ($args->{'newid'}=~/^\s*$/) {
 6503: 	    &scan_data($scan_data,"$whichline.user",
 6504: 		       $args->{'username'}.':'.$args->{'domain'});
 6505: 	}
 6506:     } elsif ($field eq 'CODE') {
 6507: 	if ($args->{'CODE_ignore_dup'}) {
 6508: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6509: 	}
 6510: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6511: 	if ($args->{'CODE'} ne 'use_unfound') {
 6512: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6513: 		return ($line,1,'New CODE value too large');
 6514: 	    }
 6515: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6516: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6517: 	    }
 6518: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6519: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6520: 	}
 6521:     } elsif ($field eq 'answer') {
 6522: 	my $length=$scantron_config->{'Qlength'};
 6523: 	my $off=$scantron_config->{'Qoff'};
 6524: 	my $on=$scantron_config->{'Qon'};
 6525: 	my $answer=${off}x$length;
 6526: 	if ($args->{'response'} eq 'none') {
 6527: 	    &scan_data($scan_data,
 6528: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6529: 	} else {
 6530: 	    if ($on eq 'letter') {
 6531: 		my @alphabet=('A'..'Z');
 6532: 		$answer=$alphabet[$args->{'response'}];
 6533: 	    } elsif ($on eq 'number') {
 6534: 		$answer=$args->{'response'}+1;
 6535: 		if ($answer == 10) { $answer = '0'; }
 6536: 	    } else {
 6537: 		substr($answer,$args->{'response'},1)=$on;
 6538: 	    }
 6539: 	    &scan_data($scan_data,
 6540: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6541: 	}
 6542: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6543: 	substr($line,$where-1,$length)=$answer;
 6544:     }
 6545:     return $line;
 6546: }
 6547: 
 6548: =pod
 6549: 
 6550: =item scan_data
 6551: 
 6552:     Edit or look up  an item in the scan_data hash.
 6553: 
 6554:   Arguments:
 6555:     $scan_data  - The hash (see scantron_getfile)
 6556:     $key        - shorthand of the key to edit (actual key is
 6557:                   scantronfilename_key).
 6558:     $data        - New value of the hash entry.
 6559:     $delete      - If true, the entry is removed from the hash.
 6560: 
 6561:   Returns:
 6562:     The new value of the hash table field (undefined if deleted).
 6563: 
 6564: =cut
 6565: 
 6566: 
 6567: sub scan_data {
 6568:     my ($scan_data,$key,$value,$delete)=@_;
 6569:     my $filename=$env{'form.scantron_selectfile'};
 6570:     if (defined($value)) {
 6571: 	$scan_data->{$filename.'_'.$key} = $value;
 6572:     }
 6573:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6574:     return $scan_data->{$filename.'_'.$key};
 6575: }
 6576: 
 6577: # ----- These first few routines are general use routines.----
 6578: 
 6579: # Return the number of occurences of a pattern in a string.
 6580: 
 6581: sub occurence_count {
 6582:     my ($string, $pattern) = @_;
 6583: 
 6584:     my @matches = ($string =~ /$pattern/g);
 6585: 
 6586:     return scalar(@matches);
 6587: }
 6588: 
 6589: 
 6590: # Take a string known to have digits and convert all the
 6591: # digits into letters in the range J,A..I.
 6592: 
 6593: sub digits_to_letters {
 6594:     my ($input) = @_;
 6595: 
 6596:     my @alphabet = ('J', 'A'..'I');
 6597: 
 6598:     my @input    = split(//, $input);
 6599:     my $output ='';
 6600:     for (my $i = 0; $i < scalar(@input); $i++) {
 6601: 	if ($input[$i] =~ /\d/) {
 6602: 	    $output .= $alphabet[$input[$i]];
 6603: 	} else {
 6604: 	    $output .= $input[$i];
 6605: 	}
 6606:     }
 6607:     return $output;
 6608: }
 6609: 
 6610: =pod 
 6611: 
 6612: =item scantron_parse_scanline
 6613: 
 6614:   Decodes a scanline from the selected scantron file
 6615: 
 6616:  Arguments:
 6617:     line             - The text of the scantron file line to process
 6618:     whichline        - Line number
 6619:     scantron_config  - Hash describing the format of the scantron lines.
 6620:     scan_data        - Hash of extra information about the scanline
 6621:                        (see scantron_getfile for more information)
 6622:     just_header      - True if should not process question answers but only
 6623:                        the stuff to the left of the answers.
 6624:     randomorder      - True if randomorder in use
 6625:     randompick       - True if randompick in use
 6626:     sequence         - Exam folder URL
 6627:     master_seq       - Ref to array containing symbs in exam folder
 6628:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6629:                        (corresponding values are resource objects)
 6630:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6631:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6632:                        are refs to an array of resource objects, ordered
 6633:                        according to order used for CODE, when randomorder
 6634:                        and or randompick are in use.
 6635:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6636:                        for current line to question number used for same question
 6637:                         in "Master Sequence" (as seen by Course Coordinator).
 6638:     startline        - Ref to hash where key is question number (0 is first)
 6639:                        and value is number of first bubble line for current 
 6640:                        student or code-based randompick and/or randomorder.
 6641:     totalref         - Ref of scalar used to score total number of bubble
 6642:                        lines needed for responses in a scan line (used when
 6643:                        randompick in use. 
 6644: 
 6645:  Returns:
 6646:    Hash containing the result of parsing the scanline
 6647: 
 6648:    Keys are all proceeded by the string 'scantron.'
 6649: 
 6650:        CODE    - the CODE in use for this scanline
 6651:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6652:                  by the operator
 6653:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6654:                             CODEs were selected, but the usage has been
 6655:                             forced by the operator
 6656:        ID  - student/employee ID
 6657:        PaperID - if used, the ID number printed on the sheet when the 
 6658:                  paper was scanned
 6659:        FirstName - first name from the sheet
 6660:        LastName  - last name from the sheet
 6661: 
 6662:      if just_header was not true these key may also exist
 6663: 
 6664:        missingerror - a list of bubble ranges that are considered to be answers
 6665:                       to a single question that don't have any bubbles filled in.
 6666:                       Of the form questionnumber:firstbubblenumber:count.
 6667:        doubleerror  - a list of bubble ranges that are considered to be answers
 6668:                       to a single question that have more than one bubble filled in.
 6669:                       Of the form questionnumber::firstbubblenumber:count
 6670:    
 6671:                 In the above, count is the number of bubble responses in the
 6672:                 input line needed to represent the possible answers to the question.
 6673:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6674:                 per line would have count = 2.
 6675: 
 6676:        maxquest     - the number of the last bubble line that was parsed
 6677: 
 6678:        (<number> starts at 1)
 6679:        <number>.answer - zero or more letters representing the selected
 6680:                          letters from the scanline for the bubble line 
 6681:                          <number>.
 6682:                          if blank there was either no bubble or there where
 6683:                          multiple bubbles, (consult the keys missingerror and
 6684:                          doubleerror if this is an error condition)
 6685: 
 6686: =cut
 6687: 
 6688: sub scantron_parse_scanline {
 6689:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6690:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6691:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6692: 
 6693:     my %record;
 6694:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6695:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6696: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6697: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6698: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6699: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6700: 	    $record{'scantron.CODE'}=substr($data,
 6701: 					    $$scantron_config{'CODEstart'}-1,
 6702: 					    $$scantron_config{'CODElength'});
 6703: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6704: 		$record{'scantron.useCODE'}=1;
 6705: 	    }
 6706: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6707: 		$record{'scantron.CODE_ignore_dup'}=1;
 6708: 	    }
 6709: 	} else {
 6710: 	    #FIXME interpret first N questions
 6711: 	}
 6712:     }
 6713:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6714: 				  $$scantron_config{'IDlength'});
 6715:     $record{'scantron.PaperID'}=
 6716: 	substr($data,$$scantron_config{'PaperID'}-1,
 6717: 	       $$scantron_config{'PaperIDlength'});
 6718:     $record{'scantron.FirstName'}=
 6719: 	substr($data,$$scantron_config{'FirstName'}-1,
 6720: 	       $$scantron_config{'FirstNamelength'});
 6721:     $record{'scantron.LastName'}=
 6722: 	substr($data,$$scantron_config{'LastName'}-1,
 6723: 	       $$scantron_config{'LastNamelength'});
 6724:     if ($just_header) { return \%record; }
 6725: 
 6726:     my @alphabet=('A'..'Z');
 6727:     my $questnum=0;
 6728:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6729: 
 6730:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6731:     if ($randompick || $randomorder) {
 6732:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6733:                                          $master_seq,$symb_to_resource,
 6734:                                          $partids_by_symb,$orderedforcode,
 6735:                                          $respnumlookup,$startline);
 6736:         if ($total) {
 6737:             $lastpos = $total*$$scantron_config{'Qlength'};
 6738:         }
 6739:         if (ref($totalref)) {
 6740:             $$totalref = $total;
 6741:         }
 6742:     }
 6743:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6744:     chomp($questions);		# Get rid of any trailing \n.
 6745:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6746:     while (length($questions)) {
 6747:         my $answers_needed;
 6748:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6749:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6750:         } else {
 6751:             $answers_needed = $bubble_lines_per_response{$questnum};
 6752:         }
 6753:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6754:                              || 1;
 6755:         $questnum++;
 6756:         my $quest_id = $questnum;
 6757:         my $currentquest = substr($questions,0,$answer_length);
 6758:         $questions       = substr($questions,$answer_length);
 6759:         if (length($currentquest) < $answer_length) { next; }
 6760: 
 6761:         my $subdivided;
 6762:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6763:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6764:         } else {
 6765:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6766:         }
 6767:         if ($subdivided =~ /,/) {
 6768:             my $subquestnum = 1;
 6769:             my $subquestions = $currentquest;
 6770:             my @subanswers_needed = split(/,/,$subdivided);
 6771:             foreach my $subans (@subanswers_needed) {
 6772:                 my $subans_length =
 6773:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6774:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6775:                 $subquestions   = substr($subquestions,$subans_length);
 6776:                 $quest_id = "$questnum.$subquestnum";
 6777:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6778:                     ($$scantron_config{'Qon'} eq 'number')) {
 6779:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6780:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6781:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6782:                         $randomorder,$randompick,$respnumlookup);
 6783:                 } else {
 6784:                     $ansnum = &scantron_validator_positional($ansnum,
 6785:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6786:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6787:                         $randomorder,$randompick,$respnumlookup);
 6788:                 }
 6789:                 $subquestnum ++;
 6790:             }
 6791:         } else {
 6792:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6793:                 ($$scantron_config{'Qon'} eq 'number')) {
 6794:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6795:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6796:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6797:                     $randomorder,$randompick,$respnumlookup);
 6798:             } else {
 6799:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6800:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6801:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6802:                     $randomorder,$randompick,$respnumlookup);
 6803:             }
 6804:         }
 6805:     }
 6806:     $record{'scantron.maxquest'}=$questnum;
 6807:     return \%record;
 6808: }
 6809: 
 6810: sub get_master_seq {
 6811:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
 6812:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6813:                    (ref($symb_to_resource) eq 'HASH'));
 6814:     if ($need_symb_in_map) {
 6815:         return unless (ref($symb_for_examcode) eq 'HASH');
 6816:     }
 6817:     my $resource_error;
 6818:     foreach my $resource (@{$resources}) {
 6819:         my $ressymb;
 6820:         if (ref($resource)) {
 6821:             $ressymb = $resource->symb();
 6822:             push(@{$master_seq},$ressymb);
 6823:             $symb_to_resource->{$ressymb} = $resource;
 6824:             if ($need_symb_in_map) {
 6825:                 unless ($resource->is_map()) {
 6826:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
 6827:                     unless (exists($symb_for_examcode->{$map})) {
 6828:                         $symb_for_examcode->{$map} = $ressymb;
 6829:                     }
 6830:                 }
 6831:             }
 6832:         } else {
 6833:             $resource_error = 1;
 6834:             last;
 6835:         }
 6836:     }
 6837:     return $resource_error;
 6838: }
 6839: 
 6840: sub get_respnum_lookups {
 6841:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6842:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6843:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6844:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6845:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6846:                    (ref($startline) eq 'HASH'));
 6847:     my ($user,$scancode);
 6848:     if ((exists($record->{'scantron.CODE'})) &&
 6849:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6850:         $scancode = $record->{'scantron.CODE'};
 6851:     } else {
 6852:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6853:     }
 6854:     my @mapresources =
 6855:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6856:                      $orderedforcode);
 6857:     my $total = 0;
 6858:     my $count = 0;
 6859:     foreach my $resource (@mapresources) {
 6860:         my $id = $resource->id();
 6861:         my $symb = $resource->symb();
 6862:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6863:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6864:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6865:                 if ($respnum ne '') {
 6866:                     $respnumlookup->{$count} = $respnum;
 6867:                     $startline->{$count} = $total;
 6868:                     $total += $bubble_lines_per_response{$respnum};
 6869:                     $count ++;
 6870:                 }
 6871:             }
 6872:         }
 6873:     }
 6874:     return $total;
 6875: }
 6876: 
 6877: sub scantron_validator_lettnum {
 6878:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6879:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6880:         $randompick,$respnumlookup) = @_;
 6881: 
 6882:     # Qon 'letter' implies for each slot in currquest we have:
 6883:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6884:     #    about anything else (esp. a value of Qoff) for missing
 6885:     #    bubbles.
 6886:     #
 6887:     # Qon 'number' implies each slot gives a digit that indexes the
 6888:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6889:     #    and * or ? for double bubbles on a single line.
 6890:     #
 6891: 
 6892:     my $matchon;
 6893:     if ($$scantron_config{'Qon'} eq 'letter') {
 6894:         $matchon = '[A-Z]';
 6895:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6896:         $matchon = '\d';
 6897:     }
 6898:     my $occurrences = 0;
 6899:     my $responsenum = $questnum-1;
 6900:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6901:        $responsenum = $respnumlookup->{$questnum-1}
 6902:     }
 6903:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6904:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6905:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6906:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6907:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6908:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6909:         my @singlelines = split('',$currquest);
 6910:         foreach my $entry (@singlelines) {
 6911:             $occurrences = &occurence_count($entry,$matchon);
 6912:             if ($occurrences > 1) {
 6913:                 last;
 6914:             }
 6915:         }
 6916:     } else {
 6917:         $occurrences = &occurence_count($currquest,$matchon); 
 6918:     }
 6919:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6920:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6921:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6922:             my $bubble = substr($currquest,$ans,1);
 6923:             if ($bubble =~ /$matchon/ ) {
 6924:                 if ($$scantron_config{'Qon'} eq 'number') {
 6925:                     if ($bubble == 0) {
 6926:                         $bubble = 10; 
 6927:                     }
 6928:                     $record->{"scantron.$ansnum.answer"} = 
 6929:                         $alphabet->[$bubble-1];
 6930:                 } else {
 6931:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6932:                 }
 6933:             } else {
 6934:                 $record->{"scantron.$ansnum.answer"}='';
 6935:             }
 6936:             $ansnum++;
 6937:         }
 6938:     } elsif (!defined($currquest)
 6939:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6940:             || (&occurence_count($currquest,$matchon) == 0)) {
 6941:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6942:             $record->{"scantron.$ansnum.answer"}='';
 6943:             $ansnum++;
 6944:         }
 6945:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6946:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6947:         }
 6948:     } else {
 6949:         if ($$scantron_config{'Qon'} eq 'number') {
 6950:             $currquest = &digits_to_letters($currquest);            
 6951:         }
 6952:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6953:             my $bubble = substr($currquest,$ans,1);
 6954:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6955:             $ansnum++;
 6956:         }
 6957:     }
 6958:     return $ansnum;
 6959: }
 6960: 
 6961: sub scantron_validator_positional {
 6962:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6963:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6964:         $randomorder,$randompick,$respnumlookup) = @_;
 6965: 
 6966:     # Otherwise there's a positional notation;
 6967:     # each bubble line requires Qlength items, and there are filled in
 6968:     # bubbles for each case where there 'Qon' characters.
 6969:     #
 6970: 
 6971:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6972: 
 6973:     # If the split only gives us one element.. the full length of the
 6974:     # answer string, no bubbles are filled in:
 6975: 
 6976:     if ($answers_needed eq '') {
 6977:         return;
 6978:     }
 6979: 
 6980:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6981:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6982:             $record->{"scantron.$ansnum.answer"}='';
 6983:             $ansnum++;
 6984:         }
 6985:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6986:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6987:         }
 6988:     } elsif (scalar(@array) == 2) {
 6989:         my $location = length($array[0]);
 6990:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6991:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6992:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6993:             if ($ans eq $line_num) {
 6994:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6995:             } else {
 6996:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6997:             }
 6998:             $ansnum++;
 6999:          }
 7000:     } else {
 7001:         #  If there's more than one instance of a bubble character
 7002:         #  That's a double bubble; with positional notation we can
 7003:         #  record all the bubbles filled in as well as the
 7004:         #  fact this response consists of multiple bubbles.
 7005:         #
 7006:         my $responsenum = $questnum-1;
 7007:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 7008:             $responsenum = $respnumlookup->{$questnum-1}
 7009:         }
 7010:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7011:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7012:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7013:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7014:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7015:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7016:             my $doubleerror = 0;
 7017:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 7018:                    (!$doubleerror)) {
 7019:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 7020:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 7021:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 7022:                if (length(@currarray) > 2) {
 7023:                    $doubleerror = 1;
 7024:                } 
 7025:             }
 7026:             if ($doubleerror) {
 7027:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 7028:             }
 7029:         } else {
 7030:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 7031:         }
 7032:         my $item = $ansnum;
 7033:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 7034:             $record->{"scantron.$item.answer"} = '';
 7035:             $item ++;
 7036:         }
 7037: 
 7038:         my @ans=@array;
 7039:         my $i=0;
 7040:         my $increment = 0;
 7041:         while ($#ans) {
 7042:             $i+=length($ans[0]) + $increment;
 7043:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 7044:             my $bubble = $i%$$scantron_config{'Qlength'};
 7045:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 7046:             shift(@ans);
 7047:             $increment = 1;
 7048:         }
 7049:         $ansnum += $answers_needed;
 7050:     }
 7051:     return $ansnum;
 7052: }
 7053: 
 7054: =pod
 7055: 
 7056: =item scantron_add_delay
 7057: 
 7058:    Adds an error message that occurred during the grading phase to a
 7059:    queue of messages to be shown after grading pass is complete
 7060: 
 7061:  Arguments:
 7062:    $delayqueue  - arrary ref of hash ref of error messages
 7063:    $scanline    - the scanline that caused the error
 7064:    $errormesage - the error message
 7065:    $errorcode   - a numeric code for the error
 7066: 
 7067:  Side Effects:
 7068:    updates the $delayqueue to have a new hash ref of the error
 7069: 
 7070: =cut
 7071: 
 7072: sub scantron_add_delay {
 7073:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 7074:     push(@$delayqueue,
 7075: 	 {'line' => $scanline, 'emsg' => $errormessage,
 7076: 	  'ecode' => $errorcode }
 7077: 	 );
 7078: }
 7079: 
 7080: =pod
 7081: 
 7082: =item scantron_find_student
 7083: 
 7084:    Finds the username for the current scanline
 7085: 
 7086:   Arguments:
 7087:    $scantron_record - hash result from scantron_parse_scanline
 7088:    $scan_data       - hash of correction information 
 7089:                       (see &scantron_getfile() form more information)
 7090:    $idmap           - hash from &username_to_idmap()
 7091:    $line            - number of current scanline
 7092:  
 7093:   Returns:
 7094:    Either 'username:domain' or undef if unknown
 7095: 
 7096: =cut
 7097: 
 7098: sub scantron_find_student {
 7099:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 7100:     my $scanID=$$scantron_record{'scantron.ID'};
 7101:     if ($scanID =~ /^\s*$/) {
 7102:  	return &scan_data($scan_data,"$line.user");
 7103:     }
 7104:     foreach my $id (keys(%$idmap)) {
 7105:  	if (lc($id) eq lc($scanID)) {
 7106:  	    return $$idmap{$id};
 7107:  	}
 7108:     }
 7109:     return undef;
 7110: }
 7111: 
 7112: =pod
 7113: 
 7114: =item scantron_filter
 7115: 
 7116:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7117:    hidden resources was selected
 7118: 
 7119: =cut
 7120: 
 7121: sub scantron_filter {
 7122:     my ($curres)=@_;
 7123: 
 7124:     if (ref($curres) && $curres->is_problem()) {
 7125: 	# if the user has asked to not have either hidden
 7126: 	# or 'randomout' controlled resources to be graded
 7127: 	# don't include them
 7128: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7129: 	    && $curres->randomout) {
 7130: 	    return 0;
 7131: 	}
 7132: 	return 1;
 7133:     }
 7134:     return 0;
 7135: }
 7136: 
 7137: =pod
 7138: 
 7139: =item scantron_process_corrections
 7140: 
 7141:    Gets correction information out of submitted form data and corrects
 7142:    the scanline
 7143: 
 7144: =cut
 7145: 
 7146: sub scantron_process_corrections {
 7147:     my ($r) = @_;
 7148:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7149:     my ($scanlines,$scan_data)=&scantron_getfile();
 7150:     my $classlist=&Apache::loncoursedata::get_classlist();
 7151:     my $which=$env{'form.scantron_line'};
 7152:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7153:     my ($skip,$err,$errmsg);
 7154:     if ($env{'form.scantron_skip_record'}) {
 7155: 	$skip=1;
 7156:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7157: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7158: 	    $env{'form.scantron_domain'};
 7159: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7160: 	($line,$err,$errmsg)=
 7161: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7162: 				     'ID',{'newid'=>$newid,
 7163: 				    'username'=>$env{'form.scantron_username'},
 7164: 				    'domain'=>$env{'form.scantron_domain'}});
 7165:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7166: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7167: 	my $newCODE;
 7168: 	my %args;
 7169: 	if      ($resolution eq 'use_unfound') {
 7170: 	    $newCODE='use_unfound';
 7171: 	} elsif ($resolution eq 'use_found') {
 7172: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7173: 	} elsif ($resolution eq 'use_typed') {
 7174: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7175: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7176: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7177: 	}
 7178: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7179: 	    $args{'CODE_ignore_dup'}=1;
 7180: 	}
 7181: 	$args{'CODE'}=$newCODE;
 7182: 	($line,$err,$errmsg)=
 7183: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7184: 				     'CODE',\%args);
 7185:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7186: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7187: 	    ($line,$err,$errmsg)=
 7188: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7189: 					 $which,'answer',
 7190: 					 { 'question'=>$question,
 7191: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7192:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7193: 	    if ($err) { last; }
 7194: 	}
 7195:     }
 7196:     if ($err) {
 7197: 	$r->print(
 7198:             '<p class="LC_error">'
 7199:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7200:                 $errmsg)
 7201:            .'</p>');
 7202:     } else {
 7203: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7204: 	&scantron_putfile($scanlines,$scan_data);
 7205:     }
 7206: }
 7207: 
 7208: =pod
 7209: 
 7210: =item reset_skipping_status
 7211: 
 7212:    Forgets the current set of remember skipped scanlines (and thus
 7213:    reverts back to considering all lines in the
 7214:    scantron_skipped_<filename> file)
 7215: 
 7216: =cut
 7217: 
 7218: sub reset_skipping_status {
 7219:     my ($scanlines,$scan_data)=&scantron_getfile();
 7220:     &scan_data($scan_data,'remember_skipping',undef,1);
 7221:     &scantron_putfile(undef,$scan_data);
 7222: }
 7223: 
 7224: =pod
 7225: 
 7226: =item start_skipping
 7227: 
 7228:    Marks a scanline to be skipped. 
 7229: 
 7230: =cut
 7231: 
 7232: sub start_skipping {
 7233:     my ($scan_data,$i)=@_;
 7234:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7235:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7236: 	$remembered{$i}=2;
 7237:     } else {
 7238: 	$remembered{$i}=1;
 7239:     }
 7240:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7241: }
 7242: 
 7243: =pod
 7244: 
 7245: =item should_be_skipped
 7246: 
 7247:    Checks whether a scanline should be skipped.
 7248: 
 7249: =cut
 7250: 
 7251: sub should_be_skipped {
 7252:     my ($scanlines,$scan_data,$i)=@_;
 7253:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7254: 	# not redoing old skips
 7255: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7256: 	return 0;
 7257:     }
 7258:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7259: 
 7260:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7261: 	return 0;
 7262:     }
 7263:     return 1;
 7264: }
 7265: 
 7266: =pod
 7267: 
 7268: =item remember_current_skipped
 7269: 
 7270:    Discovers what scanlines are in the scantron_skipped_<filename>
 7271:    file and remembers them into scan_data for later use.
 7272: 
 7273: =cut
 7274: 
 7275: sub remember_current_skipped {
 7276:     my ($scanlines,$scan_data)=&scantron_getfile();
 7277:     my %to_remember;
 7278:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7279: 	if ($scanlines->{'skipped'}[$i]) {
 7280: 	    $to_remember{$i}=1;
 7281: 	}
 7282:     }
 7283: 
 7284:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7285:     &scantron_putfile(undef,$scan_data);
 7286: }
 7287: 
 7288: =pod
 7289: 
 7290: =item check_for_error
 7291: 
 7292:     Checks if there was an error when attempting to remove a specific
 7293:     scantron_.. bubblesheet data file. Prints out an error if
 7294:     something went wrong.
 7295: 
 7296: =cut
 7297: 
 7298: sub check_for_error {
 7299:     my ($r,$result)=@_;
 7300:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7301: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7302:     }
 7303: }
 7304: 
 7305: =pod
 7306: 
 7307: =item scantron_warning_screen
 7308: 
 7309:    Interstitial screen to make sure the operator has selected the
 7310:    correct options before we start the validation phase.
 7311: 
 7312: =cut
 7313: 
 7314: sub scantron_warning_screen {
 7315:     my ($button_text,$symb)=@_;
 7316:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7317:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7318:     my $CODElist;
 7319:     if ($scantron_config{'CODElocation'} &&
 7320: 	$scantron_config{'CODEstart'} &&
 7321: 	$scantron_config{'CODElength'}) {
 7322: 	$CODElist=$env{'form.scantron_CODElist'};
 7323: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7324: 	$CODElist=
 7325: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7326: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7327:     }
 7328:     my $lastbubblepoints;
 7329:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7330:         $lastbubblepoints =
 7331:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7332:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7333:     }
 7334:     return ('
 7335: <p>
 7336: <span class="LC_warning">
 7337: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7338: </p>
 7339: <table>
 7340: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7341: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7342: '.$CODElist.$lastbubblepoints.'
 7343: </table>
 7344: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7345: '.&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>
 7346: 
 7347: <br />
 7348: ');
 7349: }
 7350: 
 7351: =pod
 7352: 
 7353: =item scantron_do_warning
 7354: 
 7355:    Check if the operator has picked something for all required
 7356:    fields. Error out if something is missing.
 7357: 
 7358: =cut
 7359: 
 7360: sub scantron_do_warning {
 7361:     my ($r,$symb)=@_;
 7362:     if (!$symb) {return '';}
 7363:     my $default_form_data=&defaultFormData($symb);
 7364:     $r->print(&scantron_form_start().$default_form_data);
 7365:     if ( $env{'form.selectpage'} eq '' ||
 7366: 	 $env{'form.scantron_selectfile'} eq '' ||
 7367: 	 $env{'form.scantron_format'} eq '' ) {
 7368: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7369: 	if ( $env{'form.selectpage'} eq '') {
 7370: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7371: 	} 
 7372: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7373: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7374: 	} 
 7375: 	if ( $env{'form.scantron_format'} eq '') {
 7376: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7377: 	} 
 7378:     } else {
 7379: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7380:         my $bubbledbyhand=&hand_bubble_option();
 7381: 	$r->print('
 7382: '.$warning.$bubbledbyhand.'
 7383: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7384: <input type="hidden" name="command" value="scantron_validate" />
 7385: ');
 7386:     }
 7387:     $r->print("</form><br />");
 7388:     return '';
 7389: }
 7390: 
 7391: =pod
 7392: 
 7393: =item scantron_form_start
 7394: 
 7395:     html hidden input for remembering all selected grading options
 7396: 
 7397: =cut
 7398: 
 7399: sub scantron_form_start {
 7400:     my ($max_bubble)=@_;
 7401:     my $result= <<SCANTRONFORM;
 7402: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7403:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7404:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7405:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7406:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7407:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7408:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7409:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7410:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7411:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7412: SCANTRONFORM
 7413: 
 7414:   my $line = 0;
 7415:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7416:        my $chunk =
 7417: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7418:        $chunk .=
 7419: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7420:        $chunk .= 
 7421:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7422:        $chunk .=
 7423:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7424:        $chunk .=
 7425:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7426:        $result .= $chunk;
 7427:        $line++;
 7428:     }
 7429:     return $result;
 7430: }
 7431: 
 7432: =pod
 7433: 
 7434: =item scantron_validate_file
 7435: 
 7436:     Dispatch routine for doing validation of a bubblesheet data file.
 7437: 
 7438:     Also processes any necessary information resets that need to
 7439:     occur before validation begins (ignore previous corrections,
 7440:     restarting the skipped records processing)
 7441: 
 7442: =cut
 7443: 
 7444: sub scantron_validate_file {
 7445:     my ($r,$symb) = @_;
 7446:     if (!$symb) {return '';}
 7447:     my $default_form_data=&defaultFormData($symb);
 7448:     
 7449:     # do the detection of only doing skipped records first before we delete
 7450:     # them when doing the corrections reset
 7451:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7452: 	&reset_skipping_status();
 7453:     }
 7454:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7455: 	&remember_current_skipped();
 7456: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7457:     }
 7458: 
 7459:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7460: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7461: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7462: 	&check_for_error($r,&scantron_remove_scan_data());
 7463: 	$env{'form.scantron_options_ignore'}='done';
 7464:     }
 7465: 
 7466:     if ($env{'form.scantron_corrections'}) {
 7467: 	&scantron_process_corrections($r);
 7468:     }
 7469:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7470:     #get the student pick code ready
 7471:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7472:     my $nav_error;
 7473:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7474:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7475:     if ($nav_error) {
 7476:         $r->print(&navmap_errormsg());
 7477:         return '';
 7478:     }
 7479:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7480:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7481:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7482:     }
 7483:     $r->print($result);
 7484:     
 7485:     my @validate_phases=( 'sequence',
 7486: 			  'ID',
 7487: 			  'CODE',
 7488: 			  'doublebubble',
 7489: 			  'missingbubbles');
 7490:     if (!$env{'form.validatepass'}) {
 7491: 	$env{'form.validatepass'} = 0;
 7492:     }
 7493:     my $currentphase=$env{'form.validatepass'};
 7494: 
 7495: 
 7496:     my $stop=0;
 7497:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7498: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7499: 	$r->rflush();
 7500: 
 7501: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7502: 	{
 7503: 	    no strict 'refs';
 7504: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7505: 	}
 7506:     }
 7507:     if (!$stop) {
 7508: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7509: 	$r->print(&mt('Validation process complete.').'<br />'.
 7510:                   $warning.
 7511:                   &mt('Perform verification for each student after storage of submissions?').
 7512:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7513:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7514:                   ('&nbsp;'x3).'<label>'.
 7515:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7516:                   '</label></span><br />'.
 7517:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7518:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7519:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7520:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7521:     } else {
 7522: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7523: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7524:     }
 7525:     if ($stop) {
 7526: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7527: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7528: 	    $r->print(' '.&mt('this error').' <br />');
 7529: 
 7530:             $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>');
 7531: 	} else {
 7532:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7533: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7534:             } else {
 7535:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7536:             }
 7537: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7538: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7539: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7540: 	}
 7541:     }
 7542:     $r->print(" </form><br />");
 7543:     return '';
 7544: }
 7545: 
 7546: 
 7547: =pod
 7548: 
 7549: =item scantron_remove_file
 7550: 
 7551:    Removes the requested bubblesheet data file, makes sure that
 7552:    scantron_original_<filename> is never removed
 7553: 
 7554: 
 7555: =cut
 7556: 
 7557: sub scantron_remove_file {
 7558:     my ($which)=@_;
 7559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7561:     my $file='scantron_';
 7562:     if ($which eq 'corrected' || $which eq 'skipped') {
 7563: 	$file.=$which.'_';
 7564:     } else {
 7565: 	return 'refused';
 7566:     }
 7567:     $file.=$env{'form.scantron_selectfile'};
 7568:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7569: }
 7570: 
 7571: 
 7572: =pod
 7573: 
 7574: =item scantron_remove_scan_data
 7575: 
 7576:    Removes all scan_data correction for the requested bubblesheet
 7577:    data file.  (In the case that both the are doing skipped records we need
 7578:    to remember the old skipped lines for the time being so that element
 7579:    persists for a while.)
 7580: 
 7581: =cut
 7582: 
 7583: sub scantron_remove_scan_data {
 7584:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7585:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7586:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7587:     my @todelete;
 7588:     my $filename=$env{'form.scantron_selectfile'};
 7589:     foreach my $key (@keys) {
 7590: 	if ($key=~/^\Q$filename\E_/) {
 7591: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7592: 		$key=~/remember_skipping/) {
 7593: 		next;
 7594: 	    }
 7595: 	    push(@todelete,$key);
 7596: 	}
 7597:     }
 7598:     my $result;
 7599:     if (@todelete) {
 7600: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7601: 				       \@todelete,$cdom,$cname);
 7602:     } else {
 7603: 	$result = 'ok';
 7604:     }
 7605:     return $result;
 7606: }
 7607: 
 7608: 
 7609: =pod
 7610: 
 7611: =item scantron_getfile
 7612: 
 7613:     Fetches the requested bubblesheet data file (all 3 versions), and
 7614:     the scan_data hash
 7615:   
 7616:   Arguments:
 7617:     None
 7618: 
 7619:   Returns:
 7620:     2 hash references
 7621: 
 7622:      - first one has 
 7623:          orig      -
 7624:          corrected -
 7625:          skipped   -  each of which points to an array ref of the specified
 7626:                       file broken up into individual lines
 7627:          count     - number of scanlines
 7628:  
 7629:      - second is the scan_data hash possible keys are
 7630:        ($number refers to scanline numbered $number and thus the key affects
 7631:         only that scanline
 7632:         $bubline refers to the specific bubble line element and the aspects
 7633:         refers to that specific bubble line element)
 7634: 
 7635:        $number.user - username:domain to use
 7636:        $number.CODE_ignore_dup 
 7637:                     - ignore the duplicate CODE error 
 7638:        $number.useCODE
 7639:                     - use the CODE in the scanline as is
 7640:        $number.no_bubble.$bubline
 7641:                     - it is valid that there is no bubbled in bubble
 7642:                       at $number $bubline
 7643:        remember_skipping
 7644:                     - a frozen hash containing keys of $number and values
 7645:                       of either 
 7646:                         1 - we are on a 'do skipped records pass' and plan
 7647:                             on processing this line
 7648:                         2 - we are on a 'do skipped records pass' and this
 7649:                             scanline has been marked to skip yet again
 7650: 
 7651: =cut
 7652: 
 7653: sub scantron_getfile {
 7654:     #FIXME really would prefer a scantron directory
 7655:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7656:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7657:     my $lines;
 7658:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7659: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7660:     my %scanlines;
 7661:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7662:     my $temp=$scanlines{'orig'};
 7663:     $scanlines{'count'}=$#$temp;
 7664: 
 7665:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7666: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7667:     if ($lines eq '-1') {
 7668: 	$scanlines{'corrected'}=[];
 7669:     } else {
 7670: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7671:     }
 7672:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7673: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7674:     if ($lines eq '-1') {
 7675: 	$scanlines{'skipped'}=[];
 7676:     } else {
 7677: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7678:     }
 7679:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7680:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7681:     my %scan_data = @tmp;
 7682:     return (\%scanlines,\%scan_data);
 7683: }
 7684: 
 7685: =pod
 7686: 
 7687: =item lonnet_putfile
 7688: 
 7689:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7690: 
 7691:  Arguments:
 7692:    $contents - data to store
 7693:    $filename - filename to store $contents into
 7694: 
 7695:  Returns:
 7696:    result value from &Apache::lonnet::finishuserfileupload
 7697: 
 7698: =cut
 7699: 
 7700: sub lonnet_putfile {
 7701:     my ($contents,$filename)=@_;
 7702:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7703:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7704:     $env{'form.sillywaytopassafilearound'}=$contents;
 7705:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7706: 
 7707: }
 7708: 
 7709: =pod
 7710: 
 7711: =item scantron_putfile
 7712: 
 7713:     Stores the current version of the bubblesheet data files, and the
 7714:     scan_data hash. (Does not modify the original version only the
 7715:     corrected and skipped versions.
 7716: 
 7717:  Arguments:
 7718:     $scanlines - hash ref that looks like the first return value from
 7719:                  &scantron_getfile()
 7720:     $scan_data - hash ref that looks like the second return value from
 7721:                  &scantron_getfile()
 7722: 
 7723: =cut
 7724: 
 7725: sub scantron_putfile {
 7726:     my ($scanlines,$scan_data) = @_;
 7727:     #FIXME really would prefer a scantron directory
 7728:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7729:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7730:     if ($scanlines) {
 7731: 	my $prefix='scantron_';
 7732: # no need to update orig, shouldn't change
 7733: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7734: #		    $env{'form.scantron_selectfile'});
 7735: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7736: 			$prefix.'corrected_'.
 7737: 			$env{'form.scantron_selectfile'});
 7738: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7739: 			$prefix.'skipped_'.
 7740: 			$env{'form.scantron_selectfile'});
 7741:     }
 7742:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7743: }
 7744: 
 7745: =pod
 7746: 
 7747: =item scantron_get_line
 7748: 
 7749:    Returns the correct version of the scanline
 7750: 
 7751:  Arguments:
 7752:     $scanlines - hash ref that looks like the first return value from
 7753:                  &scantron_getfile()
 7754:     $scan_data - hash ref that looks like the second return value from
 7755:                  &scantron_getfile()
 7756:     $i         - number of the requested line (starts at 0)
 7757: 
 7758:  Returns:
 7759:    A scanline, (either the original or the corrected one if it
 7760:    exists), or undef if the requested scanline should be
 7761:    skipped. (Either because it's an skipped scanline, or it's an
 7762:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7763:    pass.
 7764: 
 7765: =cut
 7766: 
 7767: sub scantron_get_line {
 7768:     my ($scanlines,$scan_data,$i)=@_;
 7769:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7770:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7771:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7772:     return $scanlines->{'orig'}[$i]; 
 7773: }
 7774: 
 7775: =pod
 7776: 
 7777: =item scantron_todo_count
 7778: 
 7779:     Counts the number of scanlines that need processing.
 7780: 
 7781:  Arguments:
 7782:     $scanlines - hash ref that looks like the first return value from
 7783:                  &scantron_getfile()
 7784:     $scan_data - hash ref that looks like the second return value from
 7785:                  &scantron_getfile()
 7786: 
 7787:  Returns:
 7788:     $count - number of scanlines to process
 7789: 
 7790: =cut
 7791: 
 7792: sub get_todo_count {
 7793:     my ($scanlines,$scan_data)=@_;
 7794:     my $count=0;
 7795:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7796: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7797: 	if ($line=~/^[\s\cz]*$/) { next; }
 7798: 	$count++;
 7799:     }
 7800:     return $count;
 7801: }
 7802: 
 7803: =pod
 7804: 
 7805: =item scantron_put_line
 7806: 
 7807:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7808:     data file.
 7809: 
 7810:  Arguments:
 7811:     $scanlines - hash ref that looks like the first return value from
 7812:                  &scantron_getfile()
 7813:     $scan_data - hash ref that looks like the second return value from
 7814:                  &scantron_getfile()
 7815:     $i         - line number to update
 7816:     $newline   - contents of the updated scanline
 7817:     $skip      - if true make the line for skipping and update the
 7818:                  'skipped' file
 7819: 
 7820: =cut
 7821: 
 7822: sub scantron_put_line {
 7823:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7824:     if ($skip) {
 7825: 	$scanlines->{'skipped'}[$i]=$newline;
 7826: 	&start_skipping($scan_data,$i);
 7827: 	return;
 7828:     }
 7829:     $scanlines->{'corrected'}[$i]=$newline;
 7830: }
 7831: 
 7832: =pod
 7833: 
 7834: =item scantron_clear_skip
 7835: 
 7836:    Remove a line from the 'skipped' file
 7837: 
 7838:  Arguments:
 7839:     $scanlines - hash ref that looks like the first return value from
 7840:                  &scantron_getfile()
 7841:     $scan_data - hash ref that looks like the second return value from
 7842:                  &scantron_getfile()
 7843:     $i         - line number to update
 7844: 
 7845: =cut
 7846: 
 7847: sub scantron_clear_skip {
 7848:     my ($scanlines,$scan_data,$i)=@_;
 7849:     if (exists($scanlines->{'skipped'}[$i])) {
 7850: 	undef($scanlines->{'skipped'}[$i]);
 7851: 	return 1;
 7852:     }
 7853:     return 0;
 7854: }
 7855: 
 7856: =pod
 7857: 
 7858: =item scantron_filter_not_exam
 7859: 
 7860:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7861:    filter out resources that are not marked as 'exam' mode
 7862: 
 7863: =cut
 7864: 
 7865: sub scantron_filter_not_exam {
 7866:     my ($curres)=@_;
 7867:     
 7868:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7869: 	# if the user has asked to not have either hidden
 7870: 	# or 'randomout' controlled resources to be graded
 7871: 	# don't include them
 7872: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7873: 	    && $curres->randomout) {
 7874: 	    return 0;
 7875: 	}
 7876: 	return 1;
 7877:     }
 7878:     return 0;
 7879: }
 7880: 
 7881: =pod
 7882: 
 7883: =item scantron_validate_sequence
 7884: 
 7885:     Validates the selected sequence, checking for resource that are
 7886:     not set to exam mode.
 7887: 
 7888: =cut
 7889: 
 7890: sub scantron_validate_sequence {
 7891:     my ($r,$currentphase) = @_;
 7892: 
 7893:     my $navmap=Apache::lonnavmaps::navmap->new();
 7894:     unless (ref($navmap)) {
 7895:         $r->print(&navmap_errormsg());
 7896:         return (1,$currentphase);
 7897:     }
 7898:     my (undef,undef,$sequence)=
 7899: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7900: 
 7901:     my $map=$navmap->getResourceByUrl($sequence);
 7902: 
 7903:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7904:                                     value="ignore" />');
 7905:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7906: 	my @resources=
 7907: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7908: 	if (@resources) {
 7909: 	    $r->print('<p class="LC_warning">'
 7910:                .&mt('Some resources in the sequence currently are not set to'
 7911:                    .' exam mode. Grading these resources currently may not'
 7912:                    .' work correctly.')
 7913:                .'</p>'
 7914:             );
 7915: 	    return (1,$currentphase);
 7916: 	}
 7917:     }
 7918: 
 7919:     return (0,$currentphase+1);
 7920: }
 7921: 
 7922: 
 7923: 
 7924: sub scantron_validate_ID {
 7925:     my ($r,$currentphase) = @_;
 7926:     
 7927:     #get student info
 7928:     my $classlist=&Apache::loncoursedata::get_classlist();
 7929:     my %idmap=&username_to_idmap($classlist);
 7930: 
 7931:     #get scantron line setup
 7932:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7933:     my ($scanlines,$scan_data)=&scantron_getfile();
 7934: 
 7935:     my $nav_error;
 7936:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7937:     if ($nav_error) {
 7938:         $r->print(&navmap_errormsg());
 7939:         return(1,$currentphase);
 7940:     }
 7941: 
 7942:     my %found=('ids'=>{},'usernames'=>{});
 7943:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7944: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7945: 	if ($line=~/^[\s\cz]*$/) { next; }
 7946: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7947: 						 $scan_data);
 7948: 	my $id=$$scan_record{'scantron.ID'};
 7949: 	my $found;
 7950: 	foreach my $checkid (keys(%idmap)) {
 7951: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7952: 	}
 7953: 	if ($found) {
 7954: 	    my $username=$idmap{$found};
 7955: 	    if ($found{'ids'}{$found}) {
 7956: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7957: 					 $line,'duplicateID',$found);
 7958: 		return(1,$currentphase);
 7959: 	    } elsif ($found{'usernames'}{$username}) {
 7960: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7961: 					 $line,'duplicateID',$username);
 7962: 		return(1,$currentphase);
 7963: 	    }
 7964: 	    #FIXME store away line we previously saw the ID on to use above
 7965: 	    $found{'ids'}{$found}++;
 7966: 	    $found{'usernames'}{$username}++;
 7967: 	} else {
 7968: 	    if ($id =~ /^\s*$/) {
 7969: 		my $username=&scan_data($scan_data,"$i.user");
 7970: 		if (defined($username) && $found{'usernames'}{$username}) {
 7971: 		    &scantron_get_correction($r,$i,$scan_record,
 7972: 					     \%scantron_config,
 7973: 					     $line,'duplicateID',$username);
 7974: 		    return(1,$currentphase);
 7975: 		} elsif (!defined($username)) {
 7976: 		    &scantron_get_correction($r,$i,$scan_record,
 7977: 					     \%scantron_config,
 7978: 					     $line,'incorrectID');
 7979: 		    return(1,$currentphase);
 7980: 		}
 7981: 		$found{'usernames'}{$username}++;
 7982: 	    } else {
 7983: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7984: 					 $line,'incorrectID');
 7985: 		return(1,$currentphase);
 7986: 	    }
 7987: 	}
 7988:     }
 7989: 
 7990:     return (0,$currentphase+1);
 7991: }
 7992: 
 7993: 
 7994: sub scantron_get_correction {
 7995:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7996:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7997: #FIXME in the case of a duplicated ID the previous line, probably need
 7998: #to show both the current line and the previous one and allow skipping
 7999: #the previous one or the current one
 8000: 
 8001:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8002:         $r->print(
 8003:             '<p class="LC_warning">'
 8004:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8005:                 "<b>$error</b>",
 8006:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8007:            ."</p> \n");
 8008:     } else {
 8009:         $r->print(
 8010:             '<p class="LC_warning">'
 8011:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8012:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8013:            ."</p> \n");
 8014:     }
 8015:     my $message =
 8016:         '<p>'
 8017:        .&mt('The ID on the form is [_1]',
 8018:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8019:        .'<br />'
 8020:        .&mt('The name on the paper is [_1], [_2]',
 8021:             $$scan_record{'scantron.LastName'},
 8022:             $$scan_record{'scantron.FirstName'})
 8023:        .'</p>';
 8024: 
 8025:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8026:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8027:                            # Array populated for doublebubble or
 8028:     my @lines_to_correct;  # missingbubble errors to build javascript
 8029:                            # to validate radio button checking   
 8030: 
 8031:     if ($error =~ /ID$/) {
 8032: 	if ($error eq 'incorrectID') {
 8033: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8034: 		      "</p>\n");
 8035: 	} elsif ($error eq 'duplicateID') {
 8036: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8037: 	}
 8038: 	$r->print($message);
 8039: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8040: 	$r->print("\n<ul><li> ");
 8041: 	#FIXME it would be nice if this sent back the user ID and
 8042: 	#could do partial userID matches
 8043: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8044: 				       'scantron_username','scantron_domain'));
 8045: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8046: 	$r->print("\n:\n".
 8047: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8048: 
 8049: 	$r->print('</li>');
 8050:     } elsif ($error =~ /CODE$/) {
 8051: 	if ($error eq 'incorrectCODE') {
 8052: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8053: 	} elsif ($error eq 'duplicateCODE') {
 8054: 	    $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");
 8055: 	}
 8056:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 8057:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8058:                  ."</p>\n");
 8059: 	$r->print($message);
 8060: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8061: 	$r->print("\n<br /> ");
 8062: 	my $i=0;
 8063: 	if ($error eq 'incorrectCODE' 
 8064: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8065: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8066: 	    if ($closest > 0) {
 8067: 		foreach my $testcode (@{$closest}) {
 8068: 		    my $checked='';
 8069: 		    if (!$i) { $checked=' checked="checked"'; }
 8070: 		    $r->print("
 8071:    <label>
 8072:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8073:        ".&mt("Use the similar CODE [_1] instead.",
 8074: 	    "<b><tt>".$testcode."</tt></b>")."
 8075:     </label>
 8076:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8077: 		    $r->print("\n<br />");
 8078: 		    $i++;
 8079: 		}
 8080: 	    }
 8081: 	}
 8082: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8083: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8084: 	    $r->print("
 8085:     <label>
 8086:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8087:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8088: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8089:     </label>");
 8090: 	    $r->print("\n<br />");
 8091: 	}
 8092: 
 8093: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8094: function change_radio(field) {
 8095:     var slct=document.scantronupload.scantron_CODE_resolution;
 8096:     var i;
 8097:     for (i=0;i<slct.length;i++) {
 8098:         if (slct[i].value==field) { slct[i].checked=true; }
 8099:     }
 8100: }
 8101: ENDSCRIPT
 8102: 	my $href="/adm/pickcode?".
 8103: 	   "form=".&escape("scantronupload").
 8104: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8105: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8106: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8107: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8108: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8109: 	    $r->print("
 8110:     <label>
 8111:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8112:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8113: 	     "<a target='_blank' href='$href'>","</a>")."
 8114:     </label> 
 8115:     ".&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\')" />'));
 8116: 	    $r->print("\n<br />");
 8117: 	}
 8118: 	$r->print("
 8119:     <label>
 8120:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8121:        ".&mt("Use [_1] as the CODE.",
 8122: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8123: 	$r->print("\n<br /><br />");
 8124:     } elsif ($error eq 'doublebubble') {
 8125: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8126: 
 8127: 	# The form field scantron_questions is acutally a list of line numbers.
 8128: 	# represented by this form so:
 8129: 
 8130: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8131:                                                 $respnumlookup,$startline);
 8132: 
 8133: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8134: 		  $line_list.'" />');
 8135: 	$r->print($message);
 8136: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8137: 	foreach my $question (@{$arg}) {
 8138: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8139:                                                    $scan_record, $error,
 8140:                                                    $randomorder,$randompick,
 8141:                                                    $respnumlookup,$startline);
 8142:             push(@lines_to_correct,@linenums);
 8143: 	}
 8144:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8145:     } elsif ($error eq 'missingbubble') {
 8146: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8147: 	$r->print($message);
 8148: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8149: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8150: 
 8151: 	# The form field scantron_questions is actually a list of line numbers not
 8152: 	# a list of question numbers. Therefore:
 8153: 	#
 8154: 	
 8155: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8156:                                                 $respnumlookup,$startline);
 8157: 
 8158: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8159: 		  $line_list.'" />');
 8160: 	foreach my $question (@{$arg}) {
 8161: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8162:                                                    $scan_record, $error,
 8163:                                                    $randomorder,$randompick,
 8164:                                                    $respnumlookup,$startline);
 8165:             push(@lines_to_correct,@linenums);
 8166: 	}
 8167:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8168:     } else {
 8169: 	$r->print("\n<ul>");
 8170:     }
 8171:     $r->print("\n</li></ul>");
 8172: }
 8173: 
 8174: sub verify_bubbles_checked {
 8175:     my (@ansnums) = @_;
 8176:     my $ansnumstr = join('","',@ansnums);
 8177:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8178:     &js_escape(\$warning);
 8179:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8180: function verify_bubble_radio(form) {
 8181:     var ansnumArray = new Array ("$ansnumstr");
 8182:     var need_bubble_count = 0;
 8183:     for (var i=0; i<ansnumArray.length; i++) {
 8184:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8185:             var bubble_picked = 0; 
 8186:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8187:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8188:                     bubble_picked = 1;
 8189:                 }
 8190:             }
 8191:             if (bubble_picked == 0) {
 8192:                 need_bubble_count ++;
 8193:             }
 8194:         }
 8195:     }
 8196:     if (need_bubble_count) {
 8197:         alert("$warning");
 8198:         return;
 8199:     }
 8200:     form.submit(); 
 8201: }
 8202: ENDSCRIPT
 8203:     return $output;
 8204: }
 8205: 
 8206: =pod
 8207: 
 8208: =item  questions_to_line_list
 8209: 
 8210: Converts a list of questions into a string of comma separated
 8211: line numbers in the answer sheet used by the questions.  This is
 8212: used to fill in the scantron_questions form field.
 8213: 
 8214:   Arguments:
 8215:      questions    - Reference to an array of questions.
 8216:      randomorder  - True if randomorder in use.
 8217:      randompick   - True if randompick in use.
 8218:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8219:                      for current line to question number used for same question
 8220:                      in "Master Seqence" (as seen by Course Coordinator).
 8221:      startline    - Reference to hash where key is question number (0 is first)
 8222:                     and key is number of first bubble line for current student
 8223:                     or code-based randompick and/or randomorder.
 8224: 
 8225: =cut
 8226: 
 8227: 
 8228: sub questions_to_line_list {
 8229:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8230:     my @lines;
 8231: 
 8232:     foreach my $item (@{$questions}) {
 8233:         my $question = $item;
 8234:         my ($first,$count,$last);
 8235:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8236:             $question = $1;
 8237:             my $subquestion = $2;
 8238:             my $responsenum = $question-1;
 8239:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8240:                 $responsenum = $respnumlookup->{$question-1};
 8241:                 if (ref($startline) eq 'HASH') {
 8242:                     $first = $startline->{$question-1} + 1;
 8243:                 }
 8244:             } else {
 8245:                 $first = $first_bubble_line{$responsenum} + 1;
 8246:             }
 8247:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8248:             my $subcount = 1;
 8249:             while ($subcount<$subquestion) {
 8250:                 $first += $subans[$subcount-1];
 8251:                 $subcount ++;
 8252:             }
 8253:             $count = $subans[$subquestion-1];
 8254:         } else {
 8255:             my $responsenum = $question-1;
 8256:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8257:                 $responsenum = $respnumlookup->{$question-1};
 8258:                 if (ref($startline) eq 'HASH') {
 8259:                     $first = $startline->{$question-1} + 1;
 8260:                 }
 8261:             } else {
 8262:                 $first = $first_bubble_line{$responsenum} + 1;
 8263:             }
 8264:             $count   = $bubble_lines_per_response{$responsenum};
 8265:         }
 8266:         $last = $first+$count-1;
 8267:         push(@lines, ($first..$last));
 8268:     }
 8269:     return join(',', @lines);
 8270: }
 8271: 
 8272: =pod 
 8273: 
 8274: =item prompt_for_corrections
 8275: 
 8276: Prompts for a potentially multiline correction to the
 8277: user's bubbling (factors out common code from scantron_get_correction
 8278: for multi and missing bubble cases).
 8279: 
 8280:  Arguments:
 8281:    $r           - Apache request object.
 8282:    $question    - The question number to prompt for.
 8283:    $scan_config - The scantron file configuration hash.
 8284:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8285:    $error       - Type of error
 8286:    $randomorder - True if randomorder in use.
 8287:    $randompick  - True if randompick in use.
 8288:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8289:                     for current line to question number used for same question
 8290:                     in "Master Seqence" (as seen by Course Coordinator).
 8291:    $startline   - Reference to hash where key is question number (0 is first)
 8292:                   and value is number of first bubble line for current student
 8293:                   or code-based randompick and/or randomorder.
 8294: 
 8295:  Implicit inputs:
 8296:    %bubble_lines_per_response   - Starting line numbers for each question.
 8297:                                   Numbered from 0 (but question numbers are from
 8298:                                   1.
 8299:    %first_bubble_line           - Starting bubble line for each question.
 8300:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8301:                                   type problems render as separate sub-questions, 
 8302:                                   in exam mode. This hash contains a 
 8303:                                   comma-separated list of the lines per 
 8304:                                   sub-question.
 8305:    %responsetype_per_response   - essayresponse, formularesponse,
 8306:                                   stringresponse, imageresponse, reactionresponse,
 8307:                                   and organicresponse type problem parts can have
 8308:                                   multiple lines per response if the weight
 8309:                                   assigned exceeds 10.  In this case, only
 8310:                                   one bubble per line is permitted, but more 
 8311:                                   than one line might contain bubbles, e.g.
 8312:                                   bubbling of: line 1 - J, line 2 - J, 
 8313:                                   line 3 - B would assign 22 points.  
 8314: 
 8315: =cut
 8316: 
 8317: sub prompt_for_corrections {
 8318:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8319:         $randompick, $respnumlookup, $startline) = @_;
 8320:     my ($current_line,$lines);
 8321:     my @linenums;
 8322:     my $questionnum = $question;
 8323:     my ($first,$responsenum);
 8324:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8325:         $question = $1;
 8326:         my $subquestion = $2;
 8327:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8328:             $responsenum = $respnumlookup->{$question-1};
 8329:             if (ref($startline) eq 'HASH') {
 8330:                 $first = $startline->{$question-1};
 8331:             }
 8332:         } else {
 8333:             $responsenum = $question-1;
 8334:             $first = $first_bubble_line{$responsenum};
 8335:         }
 8336:         $current_line = $first + 1 ;
 8337:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8338:         my $subcount = 1;
 8339:         while ($subcount<$subquestion) {
 8340:             $current_line += $subans[$subcount-1];
 8341:             $subcount ++;
 8342:         }
 8343:         $lines = $subans[$subquestion-1];
 8344:     } else {
 8345:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8346:             $responsenum = $respnumlookup->{$question-1};
 8347:             if (ref($startline) eq 'HASH') {
 8348:                 $first = $startline->{$question-1};
 8349:             }
 8350:         } else {
 8351:             $responsenum = $question-1;
 8352:             $first = $first_bubble_line{$responsenum};
 8353:         }
 8354:         $current_line = $first + 1;
 8355:         $lines        = $bubble_lines_per_response{$responsenum};
 8356:     }
 8357:     if ($lines > 1) {
 8358:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8359:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8360:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8361:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8362:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8363:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8364:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8365:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 8366:         } else {
 8367:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8368:         }
 8369:     }
 8370:     for (my $i =0; $i < $lines; $i++) {
 8371:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8372: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8373: 	        		  $questionnum,$error,split('', $selected));
 8374:         push(@linenums,$current_line);
 8375: 	$current_line++;
 8376:     }
 8377:     if ($lines > 1) {
 8378: 	$r->print("<hr /><br />");
 8379:     }
 8380:     return @linenums;
 8381: }
 8382: 
 8383: =pod
 8384: 
 8385: =item scantron_bubble_selector
 8386:   
 8387:    Generates the html radiobuttons to correct a single bubble line
 8388:    possibly showing the existing the selected bubbles if known
 8389: 
 8390:  Arguments:
 8391:     $r           - Apache request object
 8392:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8393:     $line        - Number of the line being displayed.
 8394:     $questionnum - Question number (may include subquestion)
 8395:     $error       - Type of error.
 8396:     @selected    - Array of bubbles picked on this line.
 8397: 
 8398: =cut
 8399: 
 8400: sub scantron_bubble_selector {
 8401:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8402:     my $max=$$scan_config{'Qlength'};
 8403: 
 8404:     my $scmode=$$scan_config{'Qon'};
 8405:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8406:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8407:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8408:             $max=$$scan_config{'BubblesPerRow'};
 8409:             if (($scmode eq 'number') && ($max > 10)) {
 8410:                 $max = 10;
 8411:             } elsif (($scmode eq 'letter') && $max > 26) {
 8412:                 $max = 26;
 8413:             }
 8414:         } else {
 8415:             $max = 10;
 8416:         }
 8417:     }
 8418: 
 8419:     my @alphabet=('A'..'Z');
 8420:     $r->print(&Apache::loncommon::start_data_table().
 8421:               &Apache::loncommon::start_data_table_row());
 8422:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8423:     for (my $i=0;$i<$max+1;$i++) {
 8424: 	$r->print("\n".'<td align="center">');
 8425: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8426: 	else { $r->print('&nbsp;'); }
 8427: 	$r->print('</td>');
 8428:     }
 8429:     $r->print(&Apache::loncommon::end_data_table_row().
 8430:               &Apache::loncommon::start_data_table_row());
 8431:     for (my $i=0;$i<$max;$i++) {
 8432: 	$r->print("\n".
 8433: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8434: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8435:     }
 8436:     my $nobub_checked = ' ';
 8437:     if ($error eq 'missingbubble') {
 8438:         $nobub_checked = ' checked = "checked" ';
 8439:     }
 8440:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8441: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8442:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8443:               $line.'" value="'.$questionnum.'" /></td>');
 8444:     $r->print(&Apache::loncommon::end_data_table_row().
 8445:               &Apache::loncommon::end_data_table());
 8446: }
 8447: 
 8448: =pod
 8449: 
 8450: =item num_matches
 8451: 
 8452:    Counts the number of characters that are the same between the two arguments.
 8453: 
 8454:  Arguments:
 8455:    $orig - CODE from the scanline
 8456:    $code - CODE to match against
 8457: 
 8458:  Returns:
 8459:    $count - integer count of the number of same characters between the
 8460:             two arguments
 8461: 
 8462: =cut
 8463: 
 8464: sub num_matches {
 8465:     my ($orig,$code) = @_;
 8466:     my @code=split(//,$code);
 8467:     my @orig=split(//,$orig);
 8468:     my $same=0;
 8469:     for (my $i=0;$i<scalar(@code);$i++) {
 8470: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8471:     }
 8472:     return $same;
 8473: }
 8474: 
 8475: =pod
 8476: 
 8477: =item scantron_get_closely_matching_CODEs
 8478: 
 8479:    Cycles through all CODEs and finds the set that has the greatest
 8480:    number of same characters as the provided CODE
 8481: 
 8482:  Arguments:
 8483:    $allcodes - hash ref returned by &get_codes()
 8484:    $CODE     - CODE from the current scanline
 8485: 
 8486:  Returns:
 8487:    2 element list
 8488:     - first elements is number of how closely matching the best fit is 
 8489:       (5 means best set has 5 matching characters)
 8490:     - second element is an arrary ref containing the set of valid CODEs
 8491:       that best fit the passed in CODE
 8492: 
 8493: =cut
 8494: 
 8495: sub scantron_get_closely_matching_CODEs {
 8496:     my ($allcodes,$CODE)=@_;
 8497:     my @CODEs;
 8498:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8499: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8500:     }
 8501: 
 8502:     return ($#CODEs,$CODEs[-1]);
 8503: }
 8504: 
 8505: =pod
 8506: 
 8507: =item get_codes
 8508: 
 8509:    Builds a hash which has keys of all of the valid CODEs from the selected
 8510:    set of remembered CODEs.
 8511: 
 8512:  Arguments:
 8513:   $old_name - name of the set of remembered CODEs
 8514:   $cdom     - domain of the course
 8515:   $cnum     - internal course name
 8516: 
 8517:  Returns:
 8518:   %allcodes - keys are the valid CODEs, values are all 1
 8519: 
 8520: =cut
 8521: 
 8522: sub get_codes {
 8523:     my ($old_name, $cdom, $cnum) = @_;
 8524:     if (!$old_name) {
 8525: 	$old_name=$env{'form.scantron_CODElist'};
 8526:     }
 8527:     if (!$cdom) {
 8528: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8529:     }
 8530:     if (!$cnum) {
 8531: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8532:     }
 8533:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8534: 				    $cdom,$cnum);
 8535:     my %allcodes;
 8536:     if ($result{"type\0$old_name"} eq 'number') {
 8537: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8538:     } else {
 8539: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8540:     }
 8541:     return %allcodes;
 8542: }
 8543: 
 8544: =pod
 8545: 
 8546: =item scantron_validate_CODE
 8547: 
 8548:    Validates all scanlines in the selected file to not have any
 8549:    invalid or underspecified CODEs and that none of the codes are
 8550:    duplicated if this was requested.
 8551: 
 8552: =cut
 8553: 
 8554: sub scantron_validate_CODE {
 8555:     my ($r,$currentphase) = @_;
 8556:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8557:     if ($scantron_config{'CODElocation'} &&
 8558: 	$scantron_config{'CODEstart'} &&
 8559: 	$scantron_config{'CODElength'}) {
 8560: 	if (!defined($env{'form.scantron_CODElist'})) {
 8561: 	    &FIXME_blow_up()
 8562: 	}
 8563:     } else {
 8564: 	return (0,$currentphase+1);
 8565:     }
 8566:     
 8567:     my %usedCODEs;
 8568: 
 8569:     my %allcodes=&get_codes();
 8570: 
 8571:     my $nav_error;
 8572:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8573:     if ($nav_error) {
 8574:         $r->print(&navmap_errormsg());
 8575:         return(1,$currentphase);
 8576:     }
 8577: 
 8578:     my ($scanlines,$scan_data)=&scantron_getfile();
 8579:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8580: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8581: 	if ($line=~/^[\s\cz]*$/) { next; }
 8582: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8583: 						 $scan_data);
 8584: 	my $CODE=$$scan_record{'scantron.CODE'};
 8585: 	my $error=0;
 8586: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8587: 	    &scantron_get_correction($r,$i,$scan_record,
 8588: 				     \%scantron_config,
 8589: 				     $line,'incorrectCODE',\%allcodes);
 8590: 	    return(1,$currentphase);
 8591: 	}
 8592: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8593: 	    && !$$scan_record{'scantron.useCODE'}) {
 8594: 	    &scantron_get_correction($r,$i,$scan_record,
 8595: 				     \%scantron_config,
 8596: 				     $line,'incorrectCODE',\%allcodes);
 8597: 	    return(1,$currentphase);
 8598: 	}
 8599: 	if (exists($usedCODEs{$CODE}) 
 8600: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8601: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8602: 	    &scantron_get_correction($r,$i,$scan_record,
 8603: 				     \%scantron_config,
 8604: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8605: 	    return(1,$currentphase);
 8606: 	}
 8607: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8608:     }
 8609:     return (0,$currentphase+1);
 8610: }
 8611: 
 8612: =pod
 8613: 
 8614: =item scantron_validate_doublebubble
 8615: 
 8616:    Validates all scanlines in the selected file to not have any
 8617:    bubble lines with multiple bubbles marked.
 8618: 
 8619: =cut
 8620: 
 8621: sub scantron_validate_doublebubble {
 8622:     my ($r,$currentphase) = @_;
 8623:     #get student info
 8624:     my $classlist=&Apache::loncoursedata::get_classlist();
 8625:     my %idmap=&username_to_idmap($classlist);
 8626:     my (undef,undef,$sequence)=
 8627:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8628: 
 8629:     #get scantron line setup
 8630:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8631:     my ($scanlines,$scan_data)=&scantron_getfile();
 8632: 
 8633:     my $navmap = Apache::lonnavmaps::navmap->new();
 8634:     unless (ref($navmap)) {
 8635:         $r->print(&navmap_errormsg());
 8636:         return(1,$currentphase);
 8637:     }
 8638:     my $map=$navmap->getResourceByUrl($sequence);
 8639:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8640:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8641:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8642:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8643: 
 8644:     my $nav_error;
 8645:     if (ref($map)) {
 8646:         $randomorder = $map->randomorder();
 8647:         $randompick = $map->randompick();
 8648:         unless ($randomorder || $randompick) {
 8649:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8650:                 if ($res->randomorder()) {
 8651:                     $randomorder = 1;
 8652:                 }
 8653:                 if ($res->randompick()) {
 8654:                     $randompick = 1;
 8655:                 }
 8656:                 last if ($randomorder || $randompick);
 8657:             }
 8658:         }
 8659:         if ($randomorder || $randompick) {
 8660:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8661:             if ($nav_error) {
 8662:                 $r->print(&navmap_errormsg());
 8663:                 return(1,$currentphase);
 8664:             }
 8665:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8666:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8667:         }
 8668:     } else {
 8669:         $r->print(&navmap_errormsg());
 8670:         return(1,$currentphase);
 8671:     }
 8672: 
 8673:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8674:     if ($nav_error) {
 8675:         $r->print(&navmap_errormsg());
 8676:         return(1,$currentphase);
 8677:     }
 8678: 
 8679:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8680: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8681: 	if ($line=~/^[\s\cz]*$/) { next; }
 8682: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8683: 						 $scan_data,undef,\%idmap,$randomorder,
 8684:                                                  $randompick,$sequence,\@master_seq,
 8685:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8686:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8687: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8688: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8689: 				 'doublebubble',
 8690: 				 $$scan_record{'scantron.doubleerror'},
 8691:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8692:     	return (1,$currentphase);
 8693:     }
 8694:     return (0,$currentphase+1);
 8695: }
 8696: 
 8697: 
 8698: sub scantron_get_maxbubble {
 8699:     my ($nav_error,$scantron_config) = @_;
 8700:     if (defined($env{'form.scantron_maxbubble'}) &&
 8701: 	$env{'form.scantron_maxbubble'}) {
 8702: 	&restore_bubble_lines();
 8703: 	return $env{'form.scantron_maxbubble'};
 8704:     }
 8705: 
 8706:     my (undef, undef, $sequence) =
 8707: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8708: 
 8709:     my $navmap=Apache::lonnavmaps::navmap->new();
 8710:     unless (ref($navmap)) {
 8711:         if (ref($nav_error)) {
 8712:             $$nav_error = 1;
 8713:         }
 8714:         return;
 8715:     }
 8716:     my $map=$navmap->getResourceByUrl($sequence);
 8717:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8718:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8719: 
 8720:     &Apache::lonxml::clear_problem_counter();
 8721: 
 8722:     my $uname       = $env{'user.name'};
 8723:     my $udom        = $env{'user.domain'};
 8724:     my $cid         = $env{'request.course.id'};
 8725:     my $total_lines = 0;
 8726:     %bubble_lines_per_response = ();
 8727:     %first_bubble_line         = ();
 8728:     %subdivided_bubble_lines   = ();
 8729:     %responsetype_per_response = ();
 8730:     %masterseq_id_responsenum  = ();
 8731: 
 8732:     my $response_number = 0;
 8733:     my $bubble_line     = 0;
 8734:     foreach my $resource (@resources) {
 8735:         my $resid = $resource->id();
 8736:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8737:                                                           $udom,undef,$bubbles_per_row);
 8738:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8739: 	    foreach my $part_id (@{$parts}) {
 8740:                 my $lines;
 8741: 
 8742: 	        # TODO - make this a persistent hash not an array.
 8743: 
 8744:                 # optionresponse, matchresponse and rankresponse type items 
 8745:                 # render as separate sub-questions in exam mode.
 8746:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8747:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8748:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8749:                     my ($numbub,$numshown);
 8750:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8751:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8752:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8753:                         }
 8754:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8755:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8756:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8757:                         }
 8758:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8759:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8760:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8761:                         }
 8762:                     }
 8763:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8764:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8765:                     }
 8766:                     my $bubbles_per_row =
 8767:                         &bubblesheet_bubbles_per_row($scantron_config);
 8768:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8769:                     if (($numbub % $bubbles_per_row) != 0) {
 8770:                         $inner_bubble_lines++;
 8771:                     }
 8772:                     for (my $i=0; $i<$numshown; $i++) {
 8773:                         $subdivided_bubble_lines{$response_number} .= 
 8774:                             $inner_bubble_lines.',';
 8775:                     }
 8776:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8777:                     $lines = $numshown * $inner_bubble_lines;
 8778:                 } else {
 8779:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8780:                 }
 8781: 
 8782:                 $first_bubble_line{$response_number} = $bubble_line;
 8783: 	        $bubble_lines_per_response{$response_number} = $lines;
 8784:                 $responsetype_per_response{$response_number} = 
 8785:                     $analysis->{$part_id.'.type'};
 8786:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8787: 	        $response_number++;
 8788: 
 8789: 	        $bubble_line +=  $lines;
 8790: 	        $total_lines +=  $lines;
 8791: 	    }
 8792:         }
 8793:     }
 8794:     &Apache::lonnet::delenv('scantron.');
 8795: 
 8796:     &save_bubble_lines();
 8797:     $env{'form.scantron_maxbubble'} =
 8798: 	$total_lines;
 8799:     return $env{'form.scantron_maxbubble'};
 8800: }
 8801: 
 8802: sub bubblesheet_bubbles_per_row {
 8803:     my ($scantron_config) = @_;
 8804:     my $bubbles_per_row;
 8805:     if (ref($scantron_config) eq 'HASH') {
 8806:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8807:     }
 8808:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8809:         $bubbles_per_row = 10;
 8810:     }
 8811:     return $bubbles_per_row;
 8812: }
 8813: 
 8814: sub scantron_validate_missingbubbles {
 8815:     my ($r,$currentphase) = @_;
 8816:     #get student info
 8817:     my $classlist=&Apache::loncoursedata::get_classlist();
 8818:     my %idmap=&username_to_idmap($classlist);
 8819:     my (undef,undef,$sequence)=
 8820:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8821: 
 8822:     #get scantron line setup
 8823:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8824:     my ($scanlines,$scan_data)=&scantron_getfile();
 8825: 
 8826:     my $navmap = Apache::lonnavmaps::navmap->new();
 8827:     unless (ref($navmap)) {
 8828:         $r->print(&navmap_errormsg());
 8829:         return(1,$currentphase);
 8830:     }
 8831: 
 8832:     my $map=$navmap->getResourceByUrl($sequence);
 8833:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8834:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8835:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8836:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8837: 
 8838:     my $nav_error;
 8839:     if (ref($map)) {
 8840:         $randomorder = $map->randomorder();
 8841:         $randompick = $map->randompick();
 8842:         unless ($randomorder || $randompick) {
 8843:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8844:                 if ($res->randomorder()) {
 8845:                     $randomorder = 1;
 8846:                 }
 8847:                 if ($res->randompick()) {
 8848:                     $randompick = 1;
 8849:                 }
 8850:                 last if ($randomorder || $randompick);
 8851:             }
 8852:         }
 8853:         if ($randomorder || $randompick) {
 8854:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8855:             if ($nav_error) {
 8856:                 $r->print(&navmap_errormsg());
 8857:                 return(1,$currentphase);
 8858:             }
 8859:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8860:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8861:         }
 8862:     } else {
 8863:         $r->print(&navmap_errormsg());
 8864:         return(1,$currentphase);
 8865:     }
 8866: 
 8867: 
 8868:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8869:     if ($nav_error) {
 8870:         $r->print(&navmap_errormsg());
 8871:         return(1,$currentphase);
 8872:     }
 8873: 
 8874:     if (!$max_bubble) { $max_bubble=2**31; }
 8875:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8876: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8877: 	if ($line=~/^[\s\cz]*$/) { next; }
 8878:         my $scan_record =
 8879:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8880:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8881:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8882:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8883: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8884: 	my @to_correct;
 8885: 	
 8886: 	# Probably here's where the error is...
 8887: 
 8888: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8889:             my $lastbubble;
 8890:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8891:                 my $question = $1;
 8892:                 my $subquestion = $2;
 8893:                 my ($first,$responsenum);
 8894:                 if ($randomorder || $randompick) {
 8895:                     $responsenum = $respnumlookup{$question-1};
 8896:                     $first = $startline{$question-1};
 8897:                 } else {
 8898:                     $responsenum = $question-1;
 8899:                     $first = $first_bubble_line{$responsenum};
 8900:                 }
 8901:                 if (!defined($first)) { next; }
 8902:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8903:                 my $subcount = 1;
 8904:                 while ($subcount<$subquestion) {
 8905:                     $first += $subans[$subcount-1];
 8906:                     $subcount ++;
 8907:                 }
 8908:                 my $count = $subans[$subquestion-1];
 8909:                 $lastbubble = $first + $count;
 8910:             } else {
 8911:                 my ($first,$responsenum);
 8912:                 if ($randomorder || $randompick) {
 8913:                     $responsenum = $respnumlookup{$missing-1};
 8914:                     $first = $startline{$missing-1};
 8915:                 } else {
 8916:                     $responsenum = $missing-1;
 8917:                     $first = $first_bubble_line{$responsenum};
 8918:                 }
 8919:                 if (!defined($first)) { next; }
 8920:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8921:             }
 8922:             if ($lastbubble > $max_bubble) { next; }
 8923: 	    push(@to_correct,$missing);
 8924: 	}
 8925: 	if (@to_correct) {
 8926: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8927: 				     $line,'missingbubble',\@to_correct,
 8928:                                      $randomorder,$randompick,\%respnumlookup,
 8929:                                      \%startline);
 8930: 	    return (1,$currentphase);
 8931: 	}
 8932: 
 8933:     }
 8934:     return (0,$currentphase+1);
 8935: }
 8936: 
 8937: sub hand_bubble_option {
 8938:     my (undef, undef, $sequence) =
 8939:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8940:     return if ($sequence eq '');
 8941:     my $navmap = Apache::lonnavmaps::navmap->new();
 8942:     unless (ref($navmap)) {
 8943:         return;
 8944:     }
 8945:     my $needs_hand_bubbles;
 8946:     my $map=$navmap->getResourceByUrl($sequence);
 8947:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8948:     foreach my $res (@resources) {
 8949:         if (ref($res)) {
 8950:             if ($res->is_problem()) {
 8951:                 my $partlist = $res->parts();
 8952:                 foreach my $part (@{ $partlist }) {
 8953:                     my @types = $res->responseType($part);
 8954:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8955:                         $needs_hand_bubbles = 1;
 8956:                         last;
 8957:                     }
 8958:                 }
 8959:             }
 8960:         }
 8961:     }
 8962:     if ($needs_hand_bubbles) {
 8963:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8964:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8965:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8966:                &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 />').
 8967:                '<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;'.
 8968:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8969:     }
 8970:     return;
 8971: }
 8972: 
 8973: sub scantron_process_students {
 8974:     my ($r,$symb) = @_;
 8975: 
 8976:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8977:     if (!$symb) {
 8978: 	return '';
 8979:     }
 8980:     my $default_form_data=&defaultFormData($symb);
 8981: 
 8982:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8983:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8984:     my ($scanlines,$scan_data)=&scantron_getfile();
 8985:     my $classlist=&Apache::loncoursedata::get_classlist();
 8986:     my %idmap=&username_to_idmap($classlist);
 8987:     my $navmap=Apache::lonnavmaps::navmap->new();
 8988:     unless (ref($navmap)) {
 8989:         $r->print(&navmap_errormsg());
 8990:         return '';
 8991:     }
 8992:     my $map=$navmap->getResourceByUrl($sequence);
 8993:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8994:         %grader_randomlists_by_symb,%symb_for_examcode);
 8995:     if (ref($map)) {
 8996:         $randomorder = $map->randomorder();
 8997:         $randompick = $map->randompick();
 8998:         unless ($randomorder || $randompick) {
 8999:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9000:                 if ($res->randomorder()) {
 9001:                     $randomorder = 1;
 9002:                 }
 9003:                 if ($res->randompick()) {
 9004:                     $randompick = 1;
 9005:                 }
 9006:                 last if ($randomorder || $randompick);
 9007:             }
 9008:         }
 9009:     } else {
 9010:         $r->print(&navmap_errormsg());
 9011:         return '';
 9012:     }
 9013:     my $nav_error;
 9014:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9015:     if ($randomorder || $randompick) {
 9016:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
 9017:         if ($nav_error) {
 9018:             $r->print(&navmap_errormsg());
 9019:             return '';
 9020:         }
 9021:     }
 9022:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9023:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9024: 
 9025:     my ($uname,$udom);
 9026:     my $result= <<SCANTRONFORM;
 9027: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9028:   <input type="hidden" name="command" value="scantron_configphase" />
 9029:   $default_form_data
 9030: SCANTRONFORM
 9031:     $r->print($result);
 9032: 
 9033:     my @delayqueue;
 9034:     my (%completedstudents,%scandata);
 9035:     
 9036:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9037:     my $count=&get_todo_count($scanlines,$scan_data);
 9038:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9039:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9040:     $r->print('<br />');
 9041:     my $start=&Time::HiRes::time();
 9042:     my $i=-1;
 9043:     my $started;
 9044: 
 9045:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9046:     if ($nav_error) {
 9047:         $r->print(&navmap_errormsg());
 9048:         return '';
 9049:     }
 9050: 
 9051:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9052:     # the user and return.
 9053: 
 9054:     if ($ssi_error) {
 9055: 	$r->print("</form>");
 9056: 	&ssi_print_error($r);
 9057:         &Apache::lonnet::remove_lock($lock);
 9058: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9059:     }
 9060: 
 9061:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9062:     my $numletts = scalar(keys(%lettdig));
 9063:     my %orderedforcode;
 9064: 
 9065:     while ($i<$scanlines->{'count'}) {
 9066:  	($uname,$udom)=('','');
 9067:  	$i++;
 9068:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9069:  	if ($line=~/^[\s\cz]*$/) { next; }
 9070: 	if ($started) {
 9071: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9072: 	}
 9073: 	$started=1;
 9074:         my %respnumlookup = ();
 9075:         my %startline = ();
 9076:         my $total;
 9077:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9078:  						 $scan_data,undef,\%idmap,$randomorder,
 9079:                                                  $randompick,$sequence,\@master_seq,
 9080:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9081:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9082:                                                  \$total);
 9083:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9084:  					      \%idmap,$i)) {
 9085:   	    &scantron_add_delay(\@delayqueue,$line,
 9086:  				'Unable to find a student that matches',1);
 9087:  	    next;
 9088:   	}
 9089:  	if (exists $completedstudents{$uname}) {
 9090:  	    &scantron_add_delay(\@delayqueue,$line,
 9091:  				'Student '.$uname.' has multiple sheets',2);
 9092:  	    next;
 9093:  	}
 9094:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9095:         my $user = $uname.':'.$usec;
 9096:   	($uname,$udom)=split(/:/,$uname);
 9097: 
 9098:         my $scancode;
 9099:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9100:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9101:             $scancode = $scan_record->{'scantron.CODE'};
 9102:         } else {
 9103:             $scancode = '';
 9104:         }
 9105: 
 9106:         my @mapresources = @resources;
 9107:         if ($randomorder || $randompick) {
 9108:             @mapresources =
 9109:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9110:                              \%orderedforcode);
 9111:         }
 9112:         my (%partids_by_symb,$res_error);
 9113:         foreach my $resource (@mapresources) {
 9114:             my $ressymb;
 9115:             if (ref($resource)) {
 9116:                 $ressymb = $resource->symb();
 9117:             } else {
 9118:                 $res_error = 1;
 9119:                 last;
 9120:             }
 9121:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9122:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9123:                 my $currcode;
 9124:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9125:                     $currcode = $scancode;
 9126:                 }
 9127:                 my ($analysis,$parts) =
 9128:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9129:                                               $uname,$udom,undef,$bubbles_per_row,
 9130:                                               $currcode);
 9131:                 $partids_by_symb{$ressymb} = $parts;
 9132:             } else {
 9133:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9134:             }
 9135:         }
 9136: 
 9137:         if ($res_error) {
 9138:             &scantron_add_delay(\@delayqueue,$line,
 9139:                                 'An error occurred while grading student '.$uname,2);
 9140:             next;
 9141:         }
 9142: 
 9143: 	&Apache::lonxml::clear_problem_counter();
 9144:   	&Apache::lonnet::appenv($scan_record);
 9145: 
 9146: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9147: 	    &scantron_putfile($scanlines,$scan_data);
 9148: 	}
 9149: 	
 9150:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9151:                                    \@mapresources,\%partids_by_symb,
 9152:                                    $bubbles_per_row,$randomorder,$randompick,
 9153:                                    \%respnumlookup,\%startline) 
 9154:             eq 'ssi_error') {
 9155:             $ssi_error = 0; # So end of handler error message does not trigger.
 9156:             $r->print("</form>");
 9157:             &ssi_print_error($r);
 9158:             &Apache::lonnet::remove_lock($lock);
 9159:             return '';      # Why return ''?  Beats me.
 9160:         }
 9161: 
 9162:         if (($scancode) && ($randomorder || $randompick)) {
 9163:             foreach my $key (keys(%symb_for_examcode)) {
 9164:                 my $symb_in_map = $symb_for_examcode{$key};
 9165:                 if ($symb_in_map ne '') {
 9166:                     my $parmresult =
 9167:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
 9168:                                                                '0_examcode',2,$scancode,
 9169:                                                                'string_examcode',$uname,
 9170:                                                                $udom);
 9171:                 }
 9172:             }
 9173:         }
 9174: 	$completedstudents{$uname}={'line'=>$line};
 9175:         if ($env{'form.verifyrecord'}) {
 9176:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9177:             if ($randompick) {
 9178:                 if ($total) {
 9179:                     $lastpos = $total*$scantron_config{'Qlength'};
 9180:                 }
 9181:             }
 9182: 
 9183:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9184:             chomp($studentdata);
 9185:             $studentdata =~ s/\r$//;
 9186:             my $studentrecord = '';
 9187:             my $counter = -1;
 9188:             foreach my $resource (@mapresources) {
 9189:                 my $ressymb = $resource->symb();
 9190:                 ($counter,my $recording) =
 9191:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9192:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9193:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9194:                                              $randompick,\%respnumlookup,\%startline);
 9195:                 $studentrecord .= $recording;
 9196:             }
 9197:             if ($studentrecord ne $studentdata) {
 9198:                 &Apache::lonxml::clear_problem_counter();
 9199:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9200:                                            \@mapresources,\%partids_by_symb,
 9201:                                            $bubbles_per_row,$randomorder,$randompick,
 9202:                                            \%respnumlookup,\%startline)
 9203:                     eq 'ssi_error') {
 9204:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9205:                     $r->print("</form>");
 9206:                     &ssi_print_error($r);
 9207:                     &Apache::lonnet::remove_lock($lock);
 9208:                     delete($completedstudents{$uname});
 9209:                     return '';
 9210:                 }
 9211:                 $counter = -1;
 9212:                 $studentrecord = '';
 9213:                 foreach my $resource (@mapresources) {
 9214:                     my $ressymb = $resource->symb();
 9215:                     ($counter,my $recording) =
 9216:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9217:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9218:                                                  \%scantron_config,\%lettdig,$numletts,
 9219:                                                  $randomorder,$randompick,\%respnumlookup,
 9220:                                                  \%startline);
 9221:                     $studentrecord .= $recording;
 9222:                 }
 9223:                 if ($studentrecord ne $studentdata) {
 9224:                     $r->print('<p><span class="LC_warning">');
 9225:                     if ($scancode eq '') {
 9226:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9227:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9228:                     } else {
 9229:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9230:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9231:                     }
 9232:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9233:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9234:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9235:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9236:                               &Apache::loncommon::start_data_table_row().
 9237:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9238:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9239:                               &Apache::loncommon::end_data_table_row().
 9240:                               &Apache::loncommon::start_data_table_row().
 9241:                               '<td>'.&mt('Stored submissions').'</td>'.
 9242:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9243:                               &Apache::loncommon::end_data_table_row().
 9244:                               &Apache::loncommon::end_data_table().'</p>');
 9245:                 } else {
 9246:                     $r->print('<br /><span class="LC_warning">'.
 9247:                              &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 />'.
 9248:                              &mt("As a consequence, this user's submission history records two tries.").
 9249:                                  '</span><br />');
 9250:                 }
 9251:             }
 9252:         }
 9253:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9254:     } continue {
 9255: 	&Apache::lonxml::clear_problem_counter();
 9256: 	&Apache::lonnet::delenv('scantron.');
 9257:     }
 9258:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9259:     &Apache::lonnet::remove_lock($lock);
 9260: #    my $lasttime = &Time::HiRes::time()-$start;
 9261: #    $r->print("<p>took $lasttime</p>");
 9262: 
 9263:     $r->print("</form>");
 9264:     return '';
 9265: }
 9266: 
 9267: sub graders_resources_pass {
 9268:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9269:         $bubbles_per_row) = @_;
 9270:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9271:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9272:         foreach my $resource (@{$resources}) {
 9273:             my $ressymb = $resource->symb();
 9274:             my ($analysis,$parts) =
 9275:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9276:                                           $env{'user.name'},$env{'user.domain'},
 9277:                                           1,$bubbles_per_row);
 9278:             $grader_partids_by_symb->{$ressymb} = $parts;
 9279:             if (ref($analysis) eq 'HASH') {
 9280:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9281:                     $grader_randomlists_by_symb->{$ressymb} =
 9282:                         $analysis->{'parts_withrandomlist'};
 9283:                 }
 9284:             }
 9285:         }
 9286:     }
 9287:     return;
 9288: }
 9289: 
 9290: =pod
 9291: 
 9292: =item users_order
 9293: 
 9294:   Returns array of resources in current map, ordered based on either CODE,
 9295:   if this is a CODEd exam, or based on student's identity if this is a
 9296:   "NAMEd" exam.
 9297: 
 9298:   Should be used when randomorder and/or randompick applied when the 
 9299:   corresponding exam was printed, prior to students completing bubblesheets 
 9300:   for the version of the exam the student received.
 9301: 
 9302: =cut
 9303: 
 9304: sub users_order  {
 9305:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9306:     my @mapresources;
 9307:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9308:         return @mapresources;
 9309:     }
 9310:     if ($scancode) {
 9311:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9312:             @mapresources = @{$orderedforcode->{$scancode}};
 9313:         } else {
 9314:             $env{'form.CODE'} = $scancode;
 9315:             my $actual_seq =
 9316:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9317:                                                                $master_seq,
 9318:                                                                $user,$scancode,1);
 9319:             if (ref($actual_seq) eq 'ARRAY') {
 9320:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9321:                 if (ref($orderedforcode) eq 'HASH') {
 9322:                     if (@mapresources > 0) {
 9323:                         $orderedforcode->{$scancode} = \@mapresources;
 9324:                     }
 9325:                 }
 9326:             }
 9327:             delete($env{'form.CODE'});
 9328:         }
 9329:     } else {
 9330:         my $actual_seq =
 9331:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9332:                                                            $master_seq,
 9333:                                                            $user,undef,1);
 9334:         if (ref($actual_seq) eq 'ARRAY') {
 9335:             @mapresources =
 9336:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9337:         }
 9338:     }
 9339:     return @mapresources;
 9340: }
 9341: 
 9342: sub grade_student_bubbles {
 9343:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9344:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9345:     my $uselookup = 0;
 9346:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9347:         (ref($startline) eq 'HASH')) {
 9348:         $uselookup = 1;
 9349:     }
 9350: 
 9351:     if (ref($resources) eq 'ARRAY') {
 9352:         my $count = 0;
 9353:         foreach my $resource (@{$resources}) {
 9354:             my $ressymb = $resource->symb();
 9355:             my %form = ('submitted'      => 'scantron',
 9356:                         'grade_target'   => 'grade',
 9357:                         'grade_username' => $uname,
 9358:                         'grade_domain'   => $udom,
 9359:                         'grade_courseid' => $env{'request.course.id'},
 9360:                         'grade_symb'     => $ressymb,
 9361:                         'CODE'           => $scancode
 9362:                        );
 9363:             if ($bubbles_per_row ne '') {
 9364:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9365:             }
 9366:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9367:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9368:             }
 9369:             if (ref($parts) eq 'HASH') {
 9370:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9371:                     foreach my $part (@{$parts->{$ressymb}}) {
 9372:                         if ($uselookup) {
 9373:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9374:                         } else {
 9375:                             $form{'scantron_questnum_start.'.$part} =
 9376:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9377:                         }
 9378:                         $count++;
 9379:                     }
 9380:                 }
 9381:             }
 9382:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9383:             return 'ssi_error' if ($ssi_error);
 9384:             last if (&Apache::loncommon::connection_aborted($r));
 9385:         }
 9386:     }
 9387:     return;
 9388: }
 9389: 
 9390: sub scantron_upload_scantron_data {
 9391:     my ($r,$symb) = @_;
 9392:     my $dom = $env{'request.role.domain'};
 9393:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9394:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9395:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9396:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9397: 							  'domainid',
 9398: 							  'coursename',$dom);
 9399:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9400:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9401:     my $default_form_data=&defaultFormData($symb);
 9402:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9403:     &js_escape(\$nofile_alert);
 9404:     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.");
 9405:     &js_escape(\$nocourseid_alert);
 9406:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9407:     function checkUpload(formname) {
 9408: 	if (formname.upfile.value == "") {
 9409: 	    alert("'.$nofile_alert.'");
 9410: 	    return false;
 9411: 	}
 9412:         if (formname.courseid.value == "") {
 9413:             alert("'.$nocourseid_alert.'");
 9414:             return false;
 9415:         }
 9416: 	formname.submit();
 9417:     }
 9418: 
 9419:     function ToSyllabus() {
 9420:         var cdom = '."'$dom'".';
 9421:         var cnum = document.rules.courseid.value;
 9422:         if (cdom == "" || cdom == null) {
 9423:             return;
 9424:         }
 9425:         if (cnum == "" || cnum == null) {
 9426:            return;
 9427:         }
 9428:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9429:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9430:         return;
 9431:     }
 9432: 
 9433:     '.$formatjs.'
 9434: '));
 9435:     $r->print('
 9436: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9437: 
 9438: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9439: '.$default_form_data.
 9440:   &Apache::lonhtmlcommon::start_pick_box().
 9441:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9442:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9443:   &Apache::lonhtmlcommon::row_closure().
 9444:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9445:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9446:   &Apache::lonhtmlcommon::row_closure().
 9447:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9448:   '<input name="domainid" type="hidden" />'.$domdesc.
 9449:   &Apache::lonhtmlcommon::row_closure());
 9450:     if ($formatoptions) {
 9451:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9452:                   &Apache::lonhtmlcommon::row_closure());
 9453:     }
 9454:     $r->print(
 9455:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9456:   '<input type="file" name="upfile" size="50" />'.
 9457:   &Apache::lonhtmlcommon::row_closure(1).
 9458:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9459: 
 9460: <input name="command" value="scantronupload_save" type="hidden" />
 9461: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9462: </form>
 9463: ');
 9464:     return '';
 9465: }
 9466: 
 9467: sub scantron_upload_dataformat {
 9468:     my ($dom) = @_;
 9469:     my ($formatoptions,$formattitle,$formatjs);
 9470:     $formatjs = <<'END';
 9471: function toggleScantab(form) {
 9472:    return;
 9473: }
 9474: END
 9475:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9476:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9477:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9478:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9479:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9480:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9481:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9482:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9483:                             my ($onclick,$formatextra,$singleline);
 9484:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9485:                             my $count = 0;
 9486:                             foreach my $line (@lines) {
 9487:                                 next if (($line =~ /^\#/) || ($line eq ''));
 9488:                                 $singleline = $line;
 9489:                                 $count ++;
 9490:                             }
 9491:                             if ($count > 1) {
 9492:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9493:                                                '<span class="LC_nobreak">'.
 9494:                                                &mt('Bubblesheet type').':&nbsp;'.
 9495:                                                &scantron_scantab().'</span></div>';
 9496:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9497:                                 $formatjs = <<"END";
 9498: function toggleScantab(form) {
 9499:     var divid = 'bubbletype';
 9500:     if (document.getElementById(divid)) {
 9501:         var radioname = 'fileformat';
 9502:         var num = form.elements[radioname].length;
 9503:         if (num) {
 9504:             for (var i=0; i<num; i++) {
 9505:                 if (form.elements[radioname][i].checked) {
 9506:                     var chosen = form.elements[radioname][i].value;
 9507:                     if (chosen == 'dat') {
 9508:                         document.getElementById(divid).style.display = 'none';
 9509:                     } else if (chosen == 'csv') {
 9510:                         document.getElementById(divid).style.display = 'block';
 9511:                     }
 9512:                 }
 9513:             }
 9514:         }
 9515:     }
 9516:     return;
 9517: }
 9518: 
 9519: END
 9520:                             } elsif ($count == 1) {
 9521:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9522:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9523:                             }
 9524:                             $formattitle = &mt('File format');
 9525:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9526:                                              &mt('Plain Text (no delimiters)').
 9527:                                              '</label>'.('&nbsp;'x2).
 9528:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9529:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9530:                         }
 9531:                     }
 9532:                 }
 9533:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9534:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9535:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9536:                         $formattitle = &mt('Bubblesheet type');
 9537:                         $formatoptions = &scantron_scantab();
 9538:                     }
 9539:                 }
 9540:             }
 9541:         }
 9542:     }
 9543:     return ($formatoptions,$formattitle,$formatjs);
 9544: }
 9545: 
 9546: sub scantron_upload_scantron_data_save {
 9547:     my ($r,$symb) = @_;
 9548:     my $doanotherupload=
 9549: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9550: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9551: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9552: 	'</form>'."\n";
 9553:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9554: 	!&Apache::lonnet::allowed('usc',
 9555: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9556: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9557:         unless ($symb) {
 9558: 	    $r->print($doanotherupload);
 9559: 	}
 9560: 	return '';
 9561:     }
 9562:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9563:     my $uploadedfile;
 9564:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9565:     if (length($env{'form.upfile'}) < 2) {
 9566:         $r->print(
 9567:             &Apache::lonhtmlcommon::confirm_success(
 9568:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9569:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9570:     } else {
 9571:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9572:         my $parser;
 9573:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9574:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9575:                 my $is_csv;
 9576:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9577:                 if (@possibles > 1) {
 9578:                     if ($env{'form.fileformat'} eq 'csv') {
 9579:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9580:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9581:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9582:                                     $is_csv = 1;
 9583:                                 }
 9584:                             }
 9585:                         }
 9586:                     }
 9587:                 } elsif (@possibles == 1) {
 9588:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9589:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9590:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9591:                                 $is_csv = 1;
 9592:                             }
 9593:                         }
 9594:                     }
 9595:                 }
 9596:                 if ($is_csv) {
 9597:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9598:                 }
 9599:             }
 9600:         }
 9601:         my $result =
 9602:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9603:                                             $env{'form.courseid'},$env{'form.domainid'});
 9604: 	if ($result =~ m{^/uploaded/}) {
 9605:             $r->print(
 9606:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9607:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9608:                         (length($env{'form.upfile'})-1),
 9609:                         '<span class="LC_filename">'.$result.'</span>'));
 9610:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9611:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9612:                                                        $env{'form.courseid'},$uploadedfile));
 9613: 	} else {
 9614:             $r->print(
 9615:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9616:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9617:                           $result,
 9618: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9619: 	}
 9620:     }
 9621:     if ($symb) {
 9622: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9623:     } else {
 9624: 	$r->print($doanotherupload);
 9625:     }
 9626:     return '';
 9627: }
 9628: 
 9629: sub validate_uploaded_scantron_file {
 9630:     my ($cdom,$cname,$fname) = @_;
 9631:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9632:     my @lines;
 9633:     if ($scanlines ne '-1') {
 9634:         @lines=split("\n",$scanlines,-1);
 9635:     }
 9636:     my $output;
 9637:     if (@lines) {
 9638:         my (%counts,$max_match_format);
 9639:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9640:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9641:         my %idmap = &username_to_idmap($classlist);
 9642:         foreach my $key (keys(%idmap)) {
 9643:             my $lckey = lc($key);
 9644:             $idmap{$lckey} = $idmap{$key};
 9645:         }
 9646:         my %unique_formats;
 9647:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9648:         foreach my $line (@formatlines) {
 9649:             next if (($line =~ /^\#/) || ($line eq ''));
 9650:             my @config = split(/:/,$line);
 9651:             my $idstart = $config[5];
 9652:             my $idlength = $config[6];
 9653:             if (($idstart ne '') && ($idlength > 0)) {
 9654:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9655:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9656:                 } else {
 9657:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9658:                 }
 9659:             }
 9660:         }
 9661:         foreach my $key (keys(%unique_formats)) {
 9662:             my ($idstart,$idlength) = split(':',$key);
 9663:             %{$counts{$key}} = (
 9664:                                'found'   => 0,
 9665:                                'total'   => 0,
 9666:                               );
 9667:             foreach my $line (@lines) {
 9668:                 next if ($line =~ /^#/);
 9669:                 next if ($line =~ /^[\s\cz]*$/);
 9670:                 my $id = substr($line,$idstart-1,$idlength);
 9671:                 $id = lc($id);
 9672:                 if (exists($idmap{$id})) {
 9673:                     $counts{$key}{'found'} ++;
 9674:                 }
 9675:                 $counts{$key}{'total'} ++;
 9676:             }
 9677:             if ($counts{$key}{'total'}) {
 9678:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9679:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9680:                     $max_match_pct = $percent_match;
 9681:                     $max_match_format = $key;
 9682:                     $found_match_count = $counts{$key}{'found'};
 9683:                     $max_match_count = $counts{$key}{'total'};
 9684:                 }
 9685:             }
 9686:         }
 9687:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9688:             my $format_descs;
 9689:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9690:             for (my $i=0; $i<$numwithformat; $i++) {
 9691:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9692:                 if ($i<$numwithformat-2) {
 9693:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9694:                 } elsif ($i==$numwithformat-2) {
 9695:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9696:                 } elsif ($i==$numwithformat-1) {
 9697:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9698:                 }
 9699:             }
 9700:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9701:             $output .= '<br />';
 9702:             if ($found_match_count == $max_match_count) {
 9703:                 # 100% matching entries
 9704:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9705:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9706:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9707:                 &mt('Comparison of student IDs in the uploaded file with'.
 9708:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9709:                     ' in the file (for the format defined for [_3]).',
 9710:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9711:             } else {
 9712:                 # Not all entries matching? -> Show warning and additional info
 9713:                 $output .=
 9714:                     &Apache::lonhtmlcommon::confirm_success(
 9715:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9716:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9717:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9718:                     &mt('Comparison of student IDs in the uploaded file with'.
 9719:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9720:                         ' in the file (for the format defined for [_3]).',
 9721:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9722:                     '<p class="LC_info">'.
 9723:                     &mt('A low percentage of matches results from one of the following:').
 9724:                     '</p><ul>'.
 9725:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9726:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9727:                                '<i>'.$cdom.'</i>').'</li>'.
 9728:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9729:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9730:                     '</ul>';
 9731:             }
 9732:         }
 9733:     } else {
 9734:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9735:     }
 9736:     return $output;
 9737: }
 9738: 
 9739: sub valid_file {
 9740:     my ($requested_file)=@_;
 9741:     foreach my $filename (sort(&scantron_filenames())) {
 9742: 	if ($requested_file eq $filename) { return 1; }
 9743:     }
 9744:     return 0;
 9745: }
 9746: 
 9747: sub scantron_download_scantron_data {
 9748:     my ($r,$symb) = @_;
 9749:     my $default_form_data=&defaultFormData($symb);
 9750:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9751:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9752:     my $file=$env{'form.scantron_selectfile'};
 9753:     if (! &valid_file($file)) {
 9754: 	$r->print('
 9755: 	<p>
 9756: 	    '.&mt('The requested filename was invalid.').'
 9757:         </p>
 9758: ');
 9759: 	return;
 9760:     }
 9761:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9762:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9763:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9764:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9765:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9766:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9767:     $r->print('
 9768:     <p>
 9769: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9770: 	      '<a href="'.$orig.'">','</a>').'
 9771:     </p>
 9772:     <p>
 9773: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9774: 	      '<a href="'.$corrected.'">','</a>').'
 9775:     </p>
 9776:     <p>
 9777: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9778: 	      '<a href="'.$skipped.'">','</a>').'
 9779:     </p>
 9780: ');
 9781:     return '';
 9782: }
 9783: 
 9784: sub checkscantron_results {
 9785:     my ($r,$symb) = @_;
 9786:     if (!$symb) {return '';}
 9787:     my $cid = $env{'request.course.id'};
 9788:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9789:     my $numletts = scalar(keys(%lettdig));
 9790:     my $cnum = $env{'course.'.$cid.'.num'};
 9791:     my $cdom = $env{'course.'.$cid.'.domain'};
 9792:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9793:     my %record;
 9794:     my %scantron_config =
 9795:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9796:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9797:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9798:     my $classlist=&Apache::loncoursedata::get_classlist();
 9799:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9800:     my $navmap=Apache::lonnavmaps::navmap->new();
 9801:     unless (ref($navmap)) {
 9802:         $r->print(&navmap_errormsg());
 9803:         return '';
 9804:     }
 9805:     my $map=$navmap->getResourceByUrl($sequence);
 9806:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9807:         %grader_randomlists_by_symb,%orderedforcode);
 9808:     if (ref($map)) {
 9809:         $randomorder=$map->randomorder();
 9810:         $randompick=$map->randompick();
 9811:         unless ($randomorder || $randompick) {
 9812:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9813:                 if ($res->randomorder()) {
 9814:                     $randomorder = 1;
 9815:                 }
 9816:                 if ($res->randompick()) {
 9817:                     $randompick = 1;
 9818:                 }
 9819:                 last if ($randomorder || $randompick);
 9820:             }
 9821:         }
 9822:     }
 9823:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9824:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9825:     if ($nav_error) {
 9826:         $r->print(&navmap_errormsg());
 9827:         return '';
 9828:     }
 9829:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9830:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9831:     my ($uname,$udom);
 9832:     my (%scandata,%lastname,%bylast);
 9833:     $r->print('
 9834: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9835: 
 9836:     my @delayqueue;
 9837:     my %completedstudents;
 9838: 
 9839:     my $count=&get_todo_count($scanlines,$scan_data);
 9840:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9841:     my ($username,$domain,$started);
 9842:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9843:     if ($nav_error) {
 9844:         $r->print(&navmap_errormsg());
 9845:         return '';
 9846:     }
 9847: 
 9848:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9849:                                           'Processing first student');
 9850:     my $start=&Time::HiRes::time();
 9851:     my $i=-1;
 9852: 
 9853:     while ($i<$scanlines->{'count'}) {
 9854:         ($username,$domain,$uname)=('','','');
 9855:         $i++;
 9856:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9857:         if ($line=~/^[\s\cz]*$/) { next; }
 9858:         if ($started) {
 9859:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9860:                                                      'last student');
 9861:         }
 9862:         $started=1;
 9863:         my $scan_record=
 9864:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9865:                                                      $scan_data);
 9866:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9867:                                               \%idmap,$i)) {
 9868:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9869:                                 'Unable to find a student that matches',1);
 9870:             next;
 9871:         }
 9872:         if (exists $completedstudents{$uname}) {
 9873:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9874:                                 'Student '.$uname.' has multiple sheets',2);
 9875:             next;
 9876:         }
 9877:         my $pid = $scan_record->{'scantron.ID'};
 9878:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9879:         push(@{$bylast{$lastname{$pid}}},$pid);
 9880:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9881:         my $user = $uname.':'.$usec;
 9882:         ($username,$domain)=split(/:/,$uname);
 9883: 
 9884:         my $scancode;
 9885:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9886:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9887:             $scancode = $scan_record->{'scantron.CODE'};
 9888:         } else {
 9889:             $scancode = '';
 9890:         }
 9891: 
 9892:         my @mapresources = @resources;
 9893:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9894:         my %respnumlookup=();
 9895:         my %startline=();
 9896:         if ($randomorder || $randompick) {
 9897:             @mapresources =
 9898:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9899:                              \%orderedforcode);
 9900:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9901:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9902:                                              \%grader_partids_by_symb,\%orderedforcode,
 9903:                                              \%respnumlookup,\%startline);
 9904:             if ($randompick && $total) {
 9905:                 $lastpos = $total*$scantron_config{'Qlength'};
 9906:             }
 9907:         }
 9908:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9909:         chomp($scandata{$pid});
 9910:         $scandata{$pid} =~ s/\r$//;
 9911: 
 9912:         my $counter = -1;
 9913:         foreach my $resource (@mapresources) {
 9914:             my $parts;
 9915:             my $ressymb = $resource->symb();
 9916:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9917:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9918:                 my $currcode;
 9919:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9920:                     $currcode = $scancode;
 9921:                 }
 9922:                 (my $analysis,$parts) =
 9923:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9924:                                               $username,$domain,undef,
 9925:                                               $bubbles_per_row,$currcode);
 9926:             } else {
 9927:                 $parts = $grader_partids_by_symb{$ressymb};
 9928:             }
 9929:             ($counter,my $recording) =
 9930:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9931:                                          $scandata{$pid},$parts,
 9932:                                          \%scantron_config,\%lettdig,$numletts,
 9933:                                          $randomorder,$randompick,
 9934:                                          \%respnumlookup,\%startline);
 9935:             $record{$pid} .= $recording;
 9936:         }
 9937:     }
 9938:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9939:     $r->print('<br />');
 9940:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9941:     $passed = 0;
 9942:     $failed = 0;
 9943:     $numstudents = 0;
 9944:     foreach my $last (sort(keys(%bylast))) {
 9945:         if (ref($bylast{$last}) eq 'ARRAY') {
 9946:             foreach my $pid (sort(@{$bylast{$last}})) {
 9947:                 my $showscandata = $scandata{$pid};
 9948:                 my $showrecord = $record{$pid};
 9949:                 $showscandata =~ s/\s/&nbsp;/g;
 9950:                 $showrecord =~ s/\s/&nbsp;/g;
 9951:                 if ($scandata{$pid} eq $record{$pid}) {
 9952:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9953:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9954: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9955: '</tr>'."\n".
 9956: '<tr class="'.$css_class.'">'."\n".
 9957: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9958:                     $passed ++;
 9959:                 } else {
 9960:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9961:                     $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".
 9962: '</tr>'."\n".
 9963: '<tr class="'.$css_class.'">'."\n".
 9964: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9965: '</tr>'."\n";
 9966:                     $failed ++;
 9967:                 }
 9968:                 $numstudents ++;
 9969:             }
 9970:         }
 9971:     }
 9972:     $r->print('<p>'.
 9973:               &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).',
 9974:                   '<b>',
 9975:                   $numstudents,
 9976:                   '</b>',
 9977:                   $env{'form.scantron_maxbubble'}).
 9978:               '</p>'
 9979:     );
 9980:     $r->print('<p>'
 9981:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9982:              .'<br />'
 9983:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9984:              .'</p>');
 9985:     if ($passed) {
 9986:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9987:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9988:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9989:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9990:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9991:                  $okstudents."\n".
 9992:                  &Apache::loncommon::end_data_table().'<br />');
 9993:     }
 9994:     if ($failed) {
 9995:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9996:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9997:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9998:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9999:                  &Apache::loncommon::end_data_table_header_row()."\n".
10000:                  $badstudents."\n".
10001:                  &Apache::loncommon::end_data_table()).'<br />'.
10002:                  &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.');  
10003:     }
10004:     $r->print('</form><br />');
10005:     return;
10006: }
10007: 
10008: sub verify_scantron_grading {
10009:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10010:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10011:         $respnumlookup,$startline) = @_;
10012:     my ($record,%expected,%startpos);
10013:     return ($counter,$record) if (!ref($resource));
10014:     return ($counter,$record) if (!$resource->is_problem());
10015:     my $symb = $resource->symb();
10016:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10017:     foreach my $part_id (@{$partids}) {
10018:         $counter ++;
10019:         $expected{$part_id} = 0;
10020:         my $respnum = $counter;
10021:         if ($randomorder || $randompick) {
10022:             $respnum = $respnumlookup->{$counter};
10023:             $startpos{$part_id} = $startline->{$counter} + 1;
10024:         } else {
10025:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10026:         }
10027:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10028:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10029:             foreach my $item (@sub_lines) {
10030:                 $expected{$part_id} += $item;
10031:             }
10032:         } else {
10033:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10034:         }
10035:     }
10036:     if ($symb) {
10037:         my %recorded;
10038:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10039:         if ($returnhash{'version'}) {
10040:             my %lasthash=();
10041:             my $version;
10042:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10043:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10044:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10045:                 }
10046:             }
10047:             foreach my $key (keys(%lasthash)) {
10048:                 if ($key =~ /\.scantron$/) {
10049:                     my $value = &unescape($lasthash{$key});
10050:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10051:                     if ($value eq '') {
10052:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10053:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10054:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10055:                             }
10056:                         }
10057:                     } else {
10058:                         my @tocheck;
10059:                         my @items = split(//,$value);
10060:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10061:                             ($scantron_config->{'Qon'} eq 'number')) {
10062:                             if (@items < $expected{$part_id}) {
10063:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10064:                                 my @singles = split(//,$fragment);
10065:                                 foreach my $pos (@singles) {
10066:                                     if ($pos eq ' ') {
10067:                                         push(@tocheck,$pos);
10068:                                     } else {
10069:                                         my $next = shift(@items);
10070:                                         push(@tocheck,$next);
10071:                                     }
10072:                                 }
10073:                             } else {
10074:                                 @tocheck = @items;
10075:                             }
10076:                             foreach my $letter (@tocheck) {
10077:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10078:                                     if ($letter !~ /^[A-J]$/) {
10079:                                         $letter = $scantron_config->{'Qoff'};
10080:                                     }
10081:                                     $recorded{$part_id} .= $letter;
10082:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10083:                                     my $digit;
10084:                                     if ($letter !~ /^[A-J]$/) {
10085:                                         $digit = $scantron_config->{'Qoff'};
10086:                                     } else {
10087:                                         $digit = $lettdig->{$letter};
10088:                                     }
10089:                                     $recorded{$part_id} .= $digit;
10090:                                 }
10091:                             }
10092:                         } else {
10093:                             @tocheck = @items;
10094:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10095:                                 my $curr_sub = shift(@tocheck);
10096:                                 my $digit;
10097:                                 if ($curr_sub =~ /^[A-J]$/) {
10098:                                     $digit = $lettdig->{$curr_sub}-1;
10099:                                 }
10100:                                 if ($curr_sub eq 'J') {
10101:                                     $digit += scalar($numletts);
10102:                                 }
10103:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10104:                                     if ($j == $digit) {
10105:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10106:                                     } else {
10107:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10108:                                     }
10109:                                 }
10110:                             }
10111:                         }
10112:                     }
10113:                 }
10114:             }
10115:         }
10116:         foreach my $part_id (@{$partids}) {
10117:             if ($recorded{$part_id} eq '') {
10118:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10119:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10120:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10121:                     }
10122:                 }
10123:             }
10124:             $record .= $recorded{$part_id};
10125:         }
10126:     }
10127:     return ($counter,$record);
10128: }
10129: 
10130: #-------- end of section for handling grading scantron forms -------
10131: #
10132: #-------------------------------------------------------------------
10133: 
10134: #-------------------------- Menu interface -------------------------
10135: #
10136: #--- Href with symb and command ---
10137: 
10138: sub href_symb_cmd {
10139:     my ($symb,$cmd)=@_;
10140:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10141: }
10142: 
10143: sub grading_menu {
10144:     my ($request,$symb) = @_;
10145:     if (!$symb) {return '';}
10146: 
10147:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10148:                   'command'=>'individual');
10149: 
10150:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10151: 
10152:     $fields{'command'}='ungraded';
10153:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10154: 
10155:     $fields{'command'}='table';
10156:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10157: 
10158:     $fields{'command'}='all_for_one';
10159:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10160: 
10161:     $fields{'command'}='downloadfilesselect';
10162:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10163:     
10164:     $fields{'command'} = 'csvform';
10165:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10166:     
10167:     $fields{'command'} = 'processclicker';
10168:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10169:     
10170:     $fields{'command'} = 'scantron_selectphase';
10171:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10172: 
10173:     $fields{'command'} = 'initialverifyreceipt';
10174:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10175: 
10176:     my %permissions;
10177:     if ($perm{'mgr'}) {
10178:         $permissions{'either'} = 'F';
10179:         $permissions{'mgr'} = 'F';
10180:     }
10181:     if ($perm{'vgr'}) {
10182:         $permissions{'either'} = 'F';
10183:         $permissions{'vgr'} = 'F';
10184:     }
10185: 
10186:     my @menu = ({	categorytitle=>'Hand Grading',
10187:             items =>[
10188:                         {       linktext => 'Select individual students to grade',
10189:                                 url => $url1a,
10190:                                 permission => $permissions{'either'},
10191:                                 icon => 'grade_students.png',
10192:                                 linktitle => 'Grade current resource for a selection of students.'
10193:                         },
10194:                         {       linktext => 'Grade ungraded submissions',
10195:                                 url => $url1b,
10196:                                 permission => $permissions{'either'},
10197:                                 icon => 'ungrade_sub.png',
10198:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10199:                         },
10200: 
10201:                         {       linktext => 'Grading table',
10202:                                 url => $url1c,
10203:                                 permission => $permissions{'either'},
10204:                                 icon => 'grading_table.png',
10205:                                 linktitle => 'Grade current resource for all students.'
10206:                         },
10207:                         {       linktext => 'Grade page/folder for one student',
10208:                                 url => $url1d,
10209:                                 permission => $permissions{'either'},
10210:                                 icon => 'grade_PageFolder.png',
10211:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10212:                         },
10213:                         {       linktext => 'Download submitted files',
10214:                                 url => $url1e,
10215:                                 permission => $permissions{'either'},
10216:                                 icon => 'download_sub.png',
10217:                                 linktitle => 'Download all files submitted by students.'
10218:                         }]},
10219:                          { categorytitle=>'Automated Grading',
10220:                items =>[
10221: 
10222:                 	    {	linktext => 'Upload Scores',
10223:                     		url => $url2,
10224:                     		permission => $permissions{'mgr'},
10225:                     		icon => 'uploadscores.png',
10226:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10227:                 	    },
10228:                 	    {	linktext => 'Process Clicker',
10229:                     		url => $url3,
10230:                     		permission => $permissions{'mgr'},
10231:                     		icon => 'addClickerInfoFile.png',
10232:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10233:                 	    },
10234:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10235:                     		url => $url4,
10236:                     		permission => $permissions{'mgr'},
10237:                     		icon => 'bubblesheet.png',
10238:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10239:                 	    },
10240:                             {   linktext => 'Verify Receipt Number',
10241:                                 url => $url5,
10242:                                 permission => $permissions{'either'},
10243:                                 icon => 'receipt_number.png',
10244:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10245:                             }
10246: 
10247:                     ]
10248:             });
10249: 
10250:     # Create the menu
10251:     my $Str;
10252:     $Str .= '<form method="post" action="" name="gradingMenu">';
10253:     $Str .= '<input type="hidden" name="command" value="" />'.
10254:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10255: 
10256:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10257:     return $Str;    
10258: }
10259: 
10260: sub ungraded {
10261:     my ($request)=@_;
10262:     &submit_options($request);
10263: }
10264: 
10265: sub submit_options_sequence {
10266:     my ($request,$symb) = @_;
10267:     if (!$symb) {return '';}
10268:     &commonJSfunctions($request);
10269:     my $result;
10270: 
10271:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10272:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10273:     $result.=&selectfield(0).
10274:             '<input type="hidden" name="command" value="pickStudentPage" />
10275:             <div>
10276:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10277:             </div>
10278:         </div>
10279:   </form>';
10280:     return $result;
10281: }
10282: 
10283: sub submit_options_table {
10284:     my ($request,$symb) = @_;
10285:     if (!$symb) {return '';}
10286:     &commonJSfunctions($request);
10287:     my $is_tool = ($symb =~ /ext\.tool$/);
10288:     my $result;
10289: 
10290:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10291:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10292: 
10293:     $result.=&selectfield(1,$is_tool).
10294:             '<input type="hidden" name="command" value="viewgrades" />
10295:             <div>
10296:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10297:             </div>
10298:         </div>
10299:   </form>';
10300:     return $result;
10301: }
10302: 
10303: sub submit_options_download {
10304:     my ($request,$symb) = @_;
10305:     if (!$symb) {return '';}
10306: 
10307:     my $res_error;
10308:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10309:         &response_type($symb,\$res_error);
10310:     if ($res_error) {
10311:         $request->print(&mt('An error occurred retrieving response types'));
10312:         return;
10313:     }
10314:     unless ($numessay) {
10315:         $request->print(&mt('No essayresponse items found'));
10316:         return;
10317:     }
10318:     my $table;
10319:     if (ref($partlist) eq 'ARRAY') {
10320:         if (scalar(@$partlist) > 1 ) {
10321:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10322:         }
10323:     }
10324: 
10325:     my $is_tool = ($symb =~ /ext\.tool$/);
10326:     &commonJSfunctions($request);
10327: 
10328:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10329:         $table."\n".
10330:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10331:     $result.='
10332: <h2>
10333:   '.&mt('Select Students for whom to Download Submitted Files').'
10334: </h2>'.&selectfield(1,$is_tool).'
10335:                 <input type="hidden" name="command" value="downloadfileslink" />
10336:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10337:             </div>
10338:           </div>
10339: 
10340: 
10341:   </form>';
10342:     return $result;
10343: }
10344: 
10345: #--- Displays the submissions first page -------
10346: sub submit_options {
10347:     my ($request,$symb) = @_;
10348:     if (!$symb) {return '';}
10349: 
10350:     my $is_tool = ($symb =~ /ext\.tool$/);
10351:     &commonJSfunctions($request);
10352:     my $result;
10353: 
10354:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10355: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10356:     $result.=&selectfield(1,$is_tool).'
10357:                 <input type="hidden" name="command" value="submission" />
10358:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10359:             </div>
10360:           </div>
10361:   </form>';
10362:     return $result;
10363: }
10364: 
10365: sub selectfield {
10366:    my ($full,$is_tool)=@_;
10367:    my %options;
10368:    if ($is_tool) {
10369:        %options =
10370:            (&transtatus_options,
10371:             'select_form_order' => ['yes','incorrect','all']);
10372:    } else {
10373:        %options =
10374:            (&substatus_options,
10375:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10376:    }
10377: 
10378:   #
10379:   # PrepareClasslist() needs to be called to avoid getting a sections list
10380:   # for a different course from the @Sections global in lonstatistics.pm,
10381:   # populated by an earlier request.
10382:   #
10383:    &Apache::lonstatistics::PrepareClasslist();
10384: 
10385:    my $result='<div class="LC_columnSection">
10386: 
10387:     <fieldset>
10388:       <legend>
10389:        '.&mt('Sections').'
10390:       </legend>
10391:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10392:     </fieldset>
10393: 
10394:     <fieldset>
10395:       <legend>
10396:         '.&mt('Groups').'
10397:       </legend>
10398:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10399:     </fieldset>
10400:  
10401:     <fieldset>
10402:       <legend>
10403:         '.&mt('Access Status').'
10404:       </legend>
10405:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10406:     </fieldset>';
10407:     if ($full) {
10408:         my $heading = &mt('Submission Status');
10409:         if ($is_tool) {
10410:             $heading = &mt('Transaction Status');
10411:         }
10412:         $result.='
10413:     <fieldset>
10414:       <legend>
10415:         '.$heading.'
10416:       </legend>'.
10417:        &Apache::loncommon::select_form('all','submitonly',\%options).
10418:    '</fieldset>';
10419:     }
10420:     $result.='</div><br />';
10421:     return $result;
10422: }
10423: 
10424: sub substatus_options {
10425:     return &Apache::lonlocal::texthash(
10426:                                       'yes'       => 'with submissions',
10427:                                       'queued'    => 'in grading queue',
10428:                                       'graded'    => 'with ungraded submissions',
10429:                                       'incorrect' => 'with incorrect submissions',
10430:                                       'all'       => 'with any status',
10431:                                       );
10432: }
10433: 
10434: sub transtatus_options {
10435:     return &Apache::lonlocal::texthash(
10436:                                        'yes'       => 'with score transactions',
10437:                                        'incorrect' => 'with less than full credit',
10438:                                        'all'       => 'with any status',
10439:                                       );
10440: }
10441: 
10442: sub reset_perm {
10443:     undef(%perm);
10444: }
10445: 
10446: sub init_perm {
10447:     &reset_perm();
10448:     foreach my $test_perm ('vgr','mgr','opa') {
10449: 
10450: 	my $scope = $env{'request.course.id'};
10451: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10452: 
10453: 	    $scope .= '/'.$env{'request.course.sec'};
10454: 	    if ( $perm{$test_perm}=
10455: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10456: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10457: 	    } else {
10458: 		delete($perm{$test_perm});
10459: 	    }
10460: 	}
10461:     }
10462: }
10463: 
10464: sub init_old_essays {
10465:     my ($symb,$apath,$adom,$aname) = @_;
10466:     if ($symb ne '') {
10467:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10468:         if (keys(%essays) > 0) {
10469:             $old_essays{$symb} = \%essays;
10470:         }
10471:     }
10472:     return;
10473: }
10474: 
10475: sub reset_old_essays {
10476:     undef(%old_essays);
10477: }
10478: 
10479: sub gather_clicker_ids {
10480:     my %clicker_ids;
10481: 
10482:     my $classlist = &Apache::loncoursedata::get_classlist();
10483: 
10484:     # Set up a couple variables.
10485:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10486:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10487:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10488: 
10489:     foreach my $student (keys(%$classlist)) {
10490:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10491:         my $username = $classlist->{$student}->[$username_idx];
10492:         my $domain   = $classlist->{$student}->[$domain_idx];
10493:         my $clickers =
10494: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10495:         foreach my $id (split(/\,/,$clickers)) {
10496:             $id=~s/^[\#0]+//;
10497:             $id=~s/[\-\:]//g;
10498:             if (exists($clicker_ids{$id})) {
10499: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10500:             } else {
10501: 		$clicker_ids{$id}=$username.':'.$domain;
10502:             }
10503:         }
10504:     }
10505:     return %clicker_ids;
10506: }
10507: 
10508: sub gather_adv_clicker_ids {
10509:     my %clicker_ids;
10510:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10511:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10512:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10513:     foreach my $element (sort(keys(%coursepersonnel))) {
10514:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10515:             my ($puname,$pudom)=split(/\:/,$person);
10516:             my $clickers =
10517: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10518:             foreach my $id (split(/\,/,$clickers)) {
10519: 		$id=~s/^[\#0]+//;
10520:                 $id=~s/[\-\:]//g;
10521: 		if (exists($clicker_ids{$id})) {
10522: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10523: 		} else {
10524: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10525: 		}
10526:             }
10527:         }
10528:     }
10529:     return %clicker_ids;
10530: }
10531: 
10532: sub clicker_grading_parameters {
10533:     return ('gradingmechanism' => 'scalar',
10534:             'upfiletype' => 'scalar',
10535:             'specificid' => 'scalar',
10536:             'pcorrect' => 'scalar',
10537:             'pincorrect' => 'scalar');
10538: }
10539: 
10540: sub process_clicker {
10541:     my ($r,$symb)=@_;
10542:     if (!$symb) {return '';}
10543:     my $result=&checkforfile_js();
10544:     $result.=&Apache::loncommon::start_data_table().
10545:              &Apache::loncommon::start_data_table_header_row().
10546:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10547:              &Apache::loncommon::end_data_table_header_row().
10548:              &Apache::loncommon::start_data_table_row()."<td>\n";
10549: # Attempt to restore parameters from last session, set defaults if not present
10550:     my %Saveable_Parameters=&clicker_grading_parameters();
10551:     &Apache::loncommon::restore_course_settings('grades_clicker',
10552:                                                  \%Saveable_Parameters);
10553:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10554:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10555:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10556:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10557: 
10558:     my %checked;
10559:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10560:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10561:           $checked{$gradingmechanism}=' checked="checked"';
10562:        }
10563:     }
10564: 
10565:     my $upload=&mt("Evaluate File");
10566:     my $type=&mt("Type");
10567:     my $attendance=&mt("Award points just for participation");
10568:     my $personnel=&mt("Correctness determined from response by course personnel");
10569:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10570:     my $given=&mt("Correctness determined from given list of answers").' '.
10571:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10572:     my $pcorrect=&mt("Percentage points for correct solution");
10573:     my $pincorrect=&mt("Percentage points for incorrect solution");
10574:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10575:                                                    {'iclicker' => 'i>clicker',
10576:                                                     'interwrite' => 'interwrite PRS',
10577:                                                     'turning' => 'Turning Technologies'});
10578:     $symb = &Apache::lonenc::check_encrypt($symb);
10579:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10580: function sanitycheck() {
10581: // Accept only integer percentages
10582:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10583:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10584: // Find out grading choice
10585:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10586:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10587:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10588:       }
10589:    }
10590: // By default, new choice equals user selection
10591:    newgradingchoice=gradingchoice;
10592: // Not good to give more points for false answers than correct ones
10593:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10594:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10595:    }
10596: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10597:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10598:       document.forms.gradesupload.pcorrect.value=100;
10599:       document.forms.gradesupload.pincorrect.value=100;
10600:    }
10601: // If the values are different, cannot be attendance only
10602:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10603:        (gradingchoice=='attendance')) {
10604:        newgradingchoice='personnel';
10605:    }
10606: // Change grading choice to new one
10607:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10608:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10609:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10610:       } else {
10611:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10612:       }
10613:    }
10614: // Remember the old state
10615:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10616: }
10617: ENDUPFORM
10618:     $result.= <<ENDUPFORM;
10619: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10620: <input type="hidden" name="symb" value="$symb" />
10621: <input type="hidden" name="command" value="processclickerfile" />
10622: <input type="file" name="upfile" size="50" />
10623: <br /><label>$type: $selectform</label>
10624: ENDUPFORM
10625:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10626:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10627:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10628: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10629: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10630: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10631: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10632: <br />&nbsp;&nbsp;&nbsp;
10633: <input type="text" name="givenanswer" size="50" />
10634: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10635: ENDGRADINGFORM
10636:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10637:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10638:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10639: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10640: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10641: </form>
10642: ENDPERCFORM
10643:     $result.='</td>'.
10644:              &Apache::loncommon::end_data_table_row().
10645:              &Apache::loncommon::end_data_table();
10646:     return $result;
10647: }
10648: 
10649: sub process_clicker_file {
10650:     my ($r,$symb) = @_;
10651:     if (!$symb) {return '';}
10652: 
10653:     my %Saveable_Parameters=&clicker_grading_parameters();
10654:     &Apache::loncommon::store_course_settings('grades_clicker',
10655:                                               \%Saveable_Parameters);
10656:     my $result='';
10657:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10658: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10659: 	return $result;
10660:     }
10661:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10662:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10663:         return $result;
10664:     }
10665:     my $foundgiven=0;
10666:     if ($env{'form.gradingmechanism'} eq 'given') {
10667:         $env{'form.givenanswer'}=~s/^\s*//gs;
10668:         $env{'form.givenanswer'}=~s/\s*$//gs;
10669:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10670:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10671:         my @answers=split(/\,/,$env{'form.givenanswer'});
10672:         $foundgiven=$#answers+1;
10673:     }
10674:     my %clicker_ids=&gather_clicker_ids();
10675:     my %correct_ids;
10676:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10677: 	%correct_ids=&gather_adv_clicker_ids();
10678:     }
10679:     if ($env{'form.gradingmechanism'} eq 'specific') {
10680: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10681: 	   $correct_id=~tr/a-z/A-Z/;
10682: 	   $correct_id=~s/\s//gs;
10683: 	   $correct_id=~s/^[\#0]+//;
10684:            $correct_id=~s/[\-\:]//g;
10685:            if ($correct_id) {
10686: 	      $correct_ids{$correct_id}='specified';
10687:            }
10688:         }
10689:     }
10690:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10691: 	$result.=&mt('Score based on attendance only');
10692:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10693:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10694:     } else {
10695: 	my $number=0;
10696: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10697: 	foreach my $id (sort(keys(%correct_ids))) {
10698: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10699: 	    if ($correct_ids{$id} eq 'specified') {
10700: 		$result.=&mt('specified');
10701: 	    } else {
10702: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10703: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10704: 	    }
10705: 	    $number++;
10706: 	}
10707:         $result.="</p>\n";
10708:         if ($number==0) {
10709:             $result .=
10710:                  &Apache::lonhtmlcommon::confirm_success(
10711:                      &mt('No IDs found to determine correct answer'),1);
10712:             return $result;
10713:         }
10714:     }
10715:     if (length($env{'form.upfile'}) < 2) {
10716:         $result .=
10717:             &Apache::lonhtmlcommon::confirm_success(
10718:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10719:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10720:         return $result;
10721:     }
10722:     my $mimetype;
10723:     if ($env{'form.upfiletype'} eq 'iclicker') {
10724:         my $mm = new File::MMagic;
10725:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10726:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10727:             $result.= '<p>'.
10728:                 &Apache::lonhtmlcommon::confirm_success(
10729:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10730:             return $result;
10731:         }
10732:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10733:         $result .= '<p>'.
10734:             &Apache::lonhtmlcommon::confirm_success(
10735:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10736:         return $result;
10737:     }
10738: 
10739: # Were able to get all the info needed, now analyze the file
10740: 
10741:     $result.=&Apache::loncommon::studentbrowser_javascript();
10742:     $symb = &Apache::lonenc::check_encrypt($symb);
10743:     $result.=&Apache::loncommon::start_data_table().
10744:              &Apache::loncommon::start_data_table_header_row().
10745:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10746:              &Apache::loncommon::end_data_table_header_row().
10747:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10748: <td>
10749: <form method="post" action="/adm/grades" name="clickeranalysis">
10750: <input type="hidden" name="symb" value="$symb" />
10751: <input type="hidden" name="command" value="assignclickergrades" />
10752: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10753: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10754: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10755: ENDHEADER
10756:     if ($env{'form.gradingmechanism'} eq 'given') {
10757:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10758:     } 
10759:     my %responses;
10760:     my @questiontitles;
10761:     my $errormsg='';
10762:     my $number=0;
10763:     if ($env{'form.upfiletype'} eq 'iclicker') {
10764:         if ($mimetype eq 'text/plain') {
10765:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10766:         } elsif ($mimetype eq 'text/html') {
10767:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10768:         }
10769:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10770:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10771:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10772:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10773:     }
10774:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10775:              '<input type="hidden" name="number" value="'.$number.'" />'.
10776:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10777:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10778:              '<br />';
10779:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10780:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10781:        return $result;
10782:     } 
10783: # Remember Question Titles
10784: # FIXME: Possibly need delimiter other than ":"
10785:     for (my $i=0;$i<$number;$i++) {
10786:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10787:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10788:     }
10789:     my $correct_count=0;
10790:     my $student_count=0;
10791:     my $unknown_count=0;
10792: # Match answers with usernames
10793: # FIXME: Possibly need delimiter other than ":"
10794:     foreach my $id (keys(%responses)) {
10795:        if ($correct_ids{$id}) {
10796:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10797:           $correct_count++;
10798:        } elsif ($clicker_ids{$id}) {
10799:           if ($clicker_ids{$id}=~/\,/) {
10800: # More than one user with the same clicker!
10801:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10802:                            &Apache::loncommon::start_data_table_row()."<td>".
10803:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10804:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10805:                            "<select name='multi".$id."'>";
10806:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10807:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10808:              }
10809:              $result.='</select>';
10810:              $unknown_count++;
10811:           } else {
10812: # Good: found one and only one user with the right clicker
10813:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10814:              $student_count++;
10815:           }
10816:        } else {
10817:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10818:                            &Apache::loncommon::start_data_table_row()."<td>".
10819:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10820:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10821:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10822:                    "\n".&mt("Domain").": ".
10823:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10824:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10825:           $unknown_count++;
10826:        }
10827:     }
10828:     $result.='<hr />'.
10829:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10830:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10831:        if ($correct_count==0) {
10832:           $errormsg.="Found no correct answers for grading!";
10833:        } elsif ($correct_count>1) {
10834:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10835:        }
10836:     }
10837:     if ($number<1) {
10838:        $errormsg.="Found no questions.";
10839:     }
10840:     if ($errormsg) {
10841:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10842:     } else {
10843:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10844:     }
10845:     $result.='</form></td>'.
10846:              &Apache::loncommon::end_data_table_row().
10847:              &Apache::loncommon::end_data_table();
10848:     return $result;
10849: }
10850: 
10851: sub iclicker_eval {
10852:     my ($questiontitles,$responses)=@_;
10853:     my $number=0;
10854:     my $errormsg='';
10855:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10856:         my %components=&Apache::loncommon::record_sep($line);
10857:         my @entries=map {$components{$_}} (sort(keys(%components)));
10858: 	if ($entries[0] eq 'Question') {
10859: 	    for (my $i=3;$i<$#entries;$i+=6) {
10860: 		$$questiontitles[$number]=$entries[$i];
10861: 		$number++;
10862: 	    }
10863: 	}
10864: 	if ($entries[0]=~/^\#/) {
10865: 	    my $id=$entries[0];
10866: 	    my @idresponses;
10867: 	    $id=~s/^[\#0]+//;
10868: 	    for (my $i=0;$i<$number;$i++) {
10869: 		my $idx=3+$i*6;
10870:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10871: 		push(@idresponses,$entries[$idx]);
10872: 	    }
10873: 	    $$responses{$id}=join(',',@idresponses);
10874: 	}
10875:     }
10876:     return ($errormsg,$number);
10877: }
10878: 
10879: sub iclickerxml_eval {
10880:     my ($questiontitles,$responses)=@_;
10881:     my $number=0;
10882:     my $errormsg='';
10883:     my @state;
10884:     my %respbyid;
10885:     my $p = HTML::Parser->new
10886:     (
10887:         xml_mode => 1,
10888:         start_h =>
10889:             [sub {
10890:                  my ($tagname,$attr) = @_;
10891:                  push(@state,$tagname);
10892:                  if ("@state" eq "ssn p") {
10893:                      my $title = $attr->{qn};
10894:                      $title =~ s/(^\s+|\s+$)//g;
10895:                      $questiontitles->[$number]=$title;
10896:                  } elsif ("@state" eq "ssn p v") {
10897:                      my $id = $attr->{id};
10898:                      my $entry = $attr->{ans};
10899:                      $id=~s/^[\#0]+//;
10900:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10901:                      $respbyid{$id}[$number] = $entry;
10902:                  }
10903:             }, "tagname, attr"],
10904:          end_h =>
10905:                [sub {
10906:                    my ($tagname) = @_;
10907:                    if ("@state" eq "ssn p") {
10908:                        $number++;
10909:                    }
10910:                    pop(@state);
10911:                 }, "tagname"],
10912:     );
10913: 
10914:     $p->parse($env{'form.upfile'});
10915:     $p->eof;
10916:     foreach my $id (keys(%respbyid)) {
10917:         $responses->{$id}=join(',',@{$respbyid{$id}});
10918:     }
10919:     return ($errormsg,$number);
10920: }
10921: 
10922: sub interwrite_eval {
10923:     my ($questiontitles,$responses)=@_;
10924:     my $number=0;
10925:     my $errormsg='';
10926:     my $skipline=1;
10927:     my $questionnumber=0;
10928:     my %idresponses=();
10929:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10930:         my %components=&Apache::loncommon::record_sep($line);
10931:         my @entries=map {$components{$_}} (sort(keys(%components)));
10932:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10933:         if ($entries[1] eq 'Response') { $skipline=1; }
10934:         next if $skipline;
10935:         if ($entries[0]!=$questionnumber) {
10936:            $questionnumber=$entries[0];
10937:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10938:            $number++;
10939:         }
10940:         my $id=$entries[4];
10941:         $id=~s/^[\#0]+//;
10942:         $id=~s/^v\d*\://i;
10943:         $id=~s/[\-\:]//g;
10944:         $idresponses{$id}[$number]=$entries[6];
10945:     }
10946:     foreach my $id (keys(%idresponses)) {
10947:        $$responses{$id}=join(',',@{$idresponses{$id}});
10948:        $$responses{$id}=~s/^\s*\,//;
10949:     }
10950:     return ($errormsg,$number);
10951: }
10952: 
10953: sub turning_eval {
10954:     my ($questiontitles,$responses)=@_;
10955:     my $number=0;
10956:     my $errormsg='';
10957:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10958:         my %components=&Apache::loncommon::record_sep($line);
10959:         my @entries=map {$components{$_}} (sort(keys(%components)));
10960:         if ($#entries>$number) { $number=$#entries; }
10961:         my $id=$entries[0];
10962:         my @idresponses;
10963:         $id=~s/^[\#0]+//;
10964:         unless ($id) { next; }
10965:         for (my $idx=1;$idx<=$#entries;$idx++) {
10966:             $entries[$idx]=~s/\,/\;/g;
10967:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10968:             push(@idresponses,$entries[$idx]);
10969:         }
10970:         $$responses{$id}=join(',',@idresponses);
10971:     }
10972:     for (my $i=1; $i<=$number; $i++) {
10973:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10974:     }
10975:     return ($errormsg,$number);
10976: }
10977: 
10978: sub assign_clicker_grades {
10979:     my ($r,$symb) = @_;
10980:     if (!$symb) {return '';}
10981: # See which part we are saving to
10982:     my $res_error;
10983:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10984:     if ($res_error) {
10985:         return &navmap_errormsg();
10986:     }
10987: # FIXME: This should probably look for the first handgradeable part
10988:     my $part=$$partlist[0];
10989: # Start screen output
10990:     my $result = &Apache::loncommon::start_data_table(). 
10991:                  &Apache::loncommon::start_data_table_header_row().
10992:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10993:                  &Apache::loncommon::end_data_table_header_row().
10994:                  &Apache::loncommon::start_data_table_row().'<td>';
10995: # Get correct result
10996: # FIXME: Possibly need delimiter other than ":"
10997:     my @correct=();
10998:     my $gradingmechanism=$env{'form.gradingmechanism'};
10999:     my $number=$env{'form.number'};
11000:     if ($gradingmechanism ne 'attendance') {
11001:        foreach my $key (keys(%env)) {
11002:           if ($key=~/^form\.correct\:/) {
11003:              my @input=split(/\,/,$env{$key});
11004:              for (my $i=0;$i<=$#input;$i++) {
11005:                  if (($correct[$i]) && ($input[$i]) &&
11006:                      ($correct[$i] ne $input[$i])) {
11007:                     $result.='<br /><span class="LC_warning">'.
11008:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11009:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11010:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11011:                     $correct[$i]=$input[$i];
11012:                  }
11013:              }
11014:           }
11015:        }
11016:        for (my $i=0;$i<$number;$i++) {
11017:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11018:              $result.='<br /><span class="LC_error">'.
11019:                       &mt('No correct result given for question "[_1]"!',
11020:                           $env{'form.question:'.$i}).'</span>';
11021:           }
11022:        }
11023:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11024:     }
11025: # Start grading
11026:     my $pcorrect=$env{'form.pcorrect'};
11027:     my $pincorrect=$env{'form.pincorrect'};
11028:     my $storecount=0;
11029:     my %users=();
11030:     foreach my $key (keys(%env)) {
11031:        my $user='';
11032:        if ($key=~/^form\.student\:(.*)$/) {
11033:           $user=$1;
11034:        }
11035:        if ($key=~/^form\.unknown\:(.*)$/) {
11036:           my $id=$1;
11037:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11038:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11039:           } elsif ($env{'form.multi'.$id}) {
11040:              $user=$env{'form.multi'.$id};
11041:           }
11042:        }
11043:        if ($user) {
11044:           if ($users{$user}) {
11045:              $result.='<br /><span class="LC_warning">'.
11046:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11047:                       '</span><br />';
11048:           }
11049:           $users{$user}=1;
11050:           my @answer=split(/\,/,$env{$key});
11051:           my $sum=0;
11052:           my $realnumber=$number;
11053:           for (my $i=0;$i<$number;$i++) {
11054:              if  ($correct[$i] eq '-') {
11055:                 $realnumber--;
11056:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11057:                 if ($gradingmechanism eq 'attendance') {
11058:                    $sum+=$pcorrect;
11059:                 } elsif ($correct[$i] eq '*') {
11060:                    $sum+=$pcorrect;
11061:                 } else {
11062: # We actually grade if correct or not
11063:                    my $increment=$pincorrect;
11064: # Special case: numerical answer "0"
11065:                    if ($correct[$i] eq '0') {
11066:                       if ($answer[$i]=~/^[0\.]+$/) {
11067:                          $increment=$pcorrect;
11068:                       }
11069: # General numerical answer, both evaluate to something non-zero
11070:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11071:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11072:                          $increment=$pcorrect;
11073:                       }
11074: # Must be just alphanumeric
11075:                    } elsif ($answer[$i] eq $correct[$i]) {
11076:                       $increment=$pcorrect;
11077:                    }
11078:                    $sum+=$increment;
11079:                 }
11080:              }
11081:           }
11082:           my $ave=$sum/(100*$realnumber);
11083: # Store
11084:           my ($username,$domain)=split(/\:/,$user);
11085:           my %grades=();
11086:           $grades{"resource.$part.solved"}='correct_by_override';
11087:           $grades{"resource.$part.awarded"}=$ave;
11088:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11089:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11090:                                                  $env{'request.course.id'},
11091:                                                  $domain,$username);
11092:           if ($returncode ne 'ok') {
11093:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11094:           } else {
11095:              $storecount++;
11096:           }
11097:        }
11098:     }
11099: # We are done
11100:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11101:              '</td>'.
11102:              &Apache::loncommon::end_data_table_row().
11103:              &Apache::loncommon::end_data_table();
11104:     return $result;
11105: }
11106: 
11107: sub navmap_errormsg {
11108:     return '<div class="LC_error">'.
11109:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11110:            &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>').
11111:            '</div>';
11112: }
11113: 
11114: sub startpage {
11115:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11116:     my %args;
11117:     if ($onload) {
11118:          my %loaditems = (
11119:                         'onload' => $onload,
11120:                       );
11121:          $args{'add_entries'} = \%loaditems;
11122:     }
11123:     if ($nomenu) {
11124:         $args{'only_body'} = 1;
11125:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11126:     } else {
11127:         if ($env{'request.course.id'}) {
11128:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11129:         }
11130:         $args{'bread_crumbs'} = $crumbs;
11131:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11132:     }
11133:     unless ($nodisplayflag) {
11134:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11135:     }
11136: }
11137: 
11138: sub select_problem {
11139:     my ($r)=@_;
11140:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11141:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
11142:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11143:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11144: }
11145: 
11146: sub handler {
11147:     my $request=$_[0];
11148:     &reset_caches();
11149:     if ($request->header_only) {
11150:         &Apache::loncommon::content_type($request,'text/html');
11151:         $request->send_http_header;
11152:         return OK;
11153:     }
11154:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11155: 
11156: # see what command we need to execute
11157:  
11158:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11159:     my $command=$commands[0];
11160: 
11161:     &init_perm();
11162:     if (!$env{'request.course.id'}) {
11163:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11164:                 ($command =~ /^scantronupload/)) {
11165:             # Not in a course.
11166:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11167:             return HTTP_NOT_ACCEPTABLE;
11168:         }
11169:     } elsif (!%perm) {
11170:         $request->internal_redirect('/adm/quickgrades');
11171:         return OK;
11172:     }
11173:     &Apache::loncommon::content_type($request,'text/html');
11174:     $request->send_http_header;
11175: 
11176:     if ($#commands > 0) {
11177: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11178:     }
11179: 
11180: # see what the symb is
11181: 
11182:     my $symb=$env{'form.symb'};
11183:     unless ($symb) {
11184:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11185:        $symb=&Apache::lonnet::symbread($url);
11186:     }
11187:     &Apache::lonenc::check_decrypt(\$symb);
11188: 
11189:     $ssi_error = 0;
11190:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11191: #
11192: # Not called from a resource, but inside a course
11193: #
11194:         &startpage($request,undef,[],1,1);
11195:         &select_problem($request);
11196:     } else {
11197:         if ($command eq 'submission' && $perm{'vgr'}) {
11198:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11199:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11200:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11201:                     &choose_task_version_form($symb,$env{'form.student'},
11202:                                               $env{'form.userdom'});
11203:             }
11204:             my $divforres;
11205:             if ($env{'form.student'} eq '') {
11206:                 $js .= &part_selector_js();
11207:                 $onload = "toggleParts('gradesub');";
11208:             } else {
11209:                 $divforres = 1;
11210:             }
11211:             my $head_extra = $js;
11212:             unless ($env{'form.vProb'} eq 'no') {
11213:                 my $csslinks = &Apache::loncommon::css_links($symb);
11214:                 if ($csslinks) {
11215:                     $head_extra .= "\n$csslinks";
11216:                 }
11217:             }
11218:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11219:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11220:             if ($versionform) {
11221:                 if ($divforres) {
11222:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11223:                 }
11224:                 $request->print($versionform);
11225:             }
11226:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11227:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11228:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11229:                 &choose_task_version_form($symb,$env{'form.student'},
11230:                                           $env{'form.userdom'},
11231:                                           $env{'form.inhibitmenu'});
11232:             my $head_extra = $js;
11233:             unless ($env{'form.vProb'} eq 'no') {
11234:                 my $csslinks = &Apache::loncommon::css_links($symb);
11235:                 if ($csslinks) {
11236:                     $head_extra .= "\n$csslinks";
11237:                 }
11238:             }
11239:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11240:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11241:             if ($versionform) {
11242:                 $request->print($versionform);
11243:             }
11244:             $request->print('<br clear="all" />');
11245:             $request->print(&show_previous_task_version($request,$symb));
11246:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11247:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11248:                                        {href=>'',text=>'Select student'}],1,1);
11249:             &pickStudentPage($request,$symb);
11250:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11251:             my $csslinks;
11252:             unless ($env{'form.vProb'} eq 'no') {
11253:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11254:             }
11255:             &startpage($request,$symb,
11256:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11257:                                        {href=>'',text=>'Select student'},
11258:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11259:             &displayPage($request,$symb);
11260:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11261:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11262:                                        {href=>'',text=>'Select student'},
11263:                                        {href=>'',text=>'Grade student'},
11264:                                        {href=>'',text=>'Store grades'}],1,1);
11265:             &updateGradeByPage($request,$symb);
11266:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11267:             my $csslinks;
11268:             unless ($env{'form.vProb'} eq 'no') {
11269:                 $csslinks = &Apache::loncommon::css_links($symb);
11270:             }
11271:             &startpage($request,$symb,[{href=>'',text=>'...'},
11272:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11273:             &processGroup($request,$symb);
11274:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11275:             &startpage($request,$symb);
11276:             $request->print(&grading_menu($request,$symb));
11277:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
11278:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11279:             $request->print(&submit_options($request,$symb));
11280:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11281:             my $js = &part_selector_js();
11282:             my $onload = "toggleParts('gradesub');";
11283:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11284:                        undef,undef,undef,undef,undef,$js,$onload);
11285:             $request->print(&listStudents($request,$symb,'graded'));
11286:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11287:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11288:             $request->print(&submit_options_table($request,$symb));
11289:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11290:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11291:             $request->print(&submit_options_sequence($request,$symb));
11292:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11293:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11294:             $request->print(&viewgrades($request,$symb));
11295:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11296:             &startpage($request,$symb,[{href=>'',text=>'...'},
11297:                                        {href=>'',text=>'Store grades'}]);
11298:             $request->print(&processHandGrade($request,$symb));
11299:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11300:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11301:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11302:                                                                              text=>"Modify grades"},
11303:                                        {href=>'', text=>"Store grades"}]);
11304:             $request->print(&editgrades($request,$symb));
11305:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11306:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11307:             $request->print(&initialverifyreceipt($request,$symb));
11308:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
11309:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11310:                                        {href=>'',text=>'Verification Result'}]);
11311:             $request->print(&verifyreceipt($request,$symb));
11312:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11313:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11314:             $request->print(&process_clicker($request,$symb));
11315:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11316:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11317:                                        {href=>'', text=>'Process clicker file'}]);
11318:             $request->print(&process_clicker_file($request,$symb));
11319:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11320:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11321:                                        {href=>'', text=>'Process clicker file'},
11322:                                        {href=>'', text=>'Store grades'}]);
11323:             $request->print(&assign_clicker_grades($request,$symb));
11324:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
11325:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11326:             $request->print(&upcsvScores_form($request,$symb));
11327:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11328:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11329:             $request->print(&csvupload($request,$symb));
11330:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11331:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11332:             $request->print(&csvuploadmap($request,$symb));
11333:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11334:             if ($env{'form.associate'} ne 'Reverse Association') {
11335:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11336:                 $request->print(&csvuploadoptions($request,$symb));
11337:             } else {
11338:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11339:                     $env{'form.upfile_associate'} = 'reverse';
11340:                 } else {
11341:                     $env{'form.upfile_associate'} = 'forward';
11342:                 }
11343:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11344:                 $request->print(&csvuploadmap($request,$symb));
11345:             }
11346:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11347:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11348:             $request->print(&csvuploadassign($request,$symb));
11349:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11350:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11351:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11352:             $request->print(&scantron_selectphase($request,undef,$symb));
11353:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11354:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11355:             $request->print(&scantron_do_warning($request,$symb));
11356:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11357:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11358:             $request->print(&scantron_validate_file($request,$symb));
11359:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11360:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11361:             $request->print(&scantron_process_students($request,$symb));
11362:         } elsif ($command eq 'scantronupload' &&
11363:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11364:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11365:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11366:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11367:             $request->print(&scantron_upload_scantron_data($request,$symb));
11368:         } elsif ($command eq 'scantronupload_save' &&
11369:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11370:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11371:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11372:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11373:         } elsif ($command eq 'scantron_download' &&
11374:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11375:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11376:             $request->print(&scantron_download_scantron_data($request,$symb));
11377:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11378:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11379:             $request->print(&checkscantron_results($request,$symb));
11380:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11381:             my $js = &part_selector_js();
11382:             my $onload = "toggleParts('gradingMenu');";
11383:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11384:                        undef,undef,undef,undef,undef,$js,$onload);
11385:             $request->print(&submit_options_download($request,$symb));
11386:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11387:             &startpage($request,$symb,
11388:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11389:     {href=>'', text=>'Download submitted files'}],
11390:                undef,undef,undef,undef,undef,undef,undef,1);
11391:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11392:             &submit_download_link($request,$symb);
11393:         } elsif ($command) {
11394:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11395:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11396:         }
11397:     }
11398:     if ($ssi_error) {
11399: 	&ssi_print_error($request);
11400:     }
11401:     $request->print(&Apache::loncommon::end_page());
11402:     &reset_caches();
11403:     return OK;
11404: }
11405: 
11406: 1;
11407: 
11408: __END__;
11409: 
11410: 
11411: =head1 NAME
11412: 
11413: Apache::grades
11414: 
11415: =head1 SYNOPSIS
11416: 
11417: Handles the viewing of grades.
11418: 
11419: This is part of the LearningOnline Network with CAPA project
11420: described at http://www.lon-capa.org.
11421: 
11422: =head1 OVERVIEW
11423: 
11424: Do an ssi with retries:
11425: While I'd love to factor out this with the vesrion in lonprintout,
11426: 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
11427: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11428: 
11429: At least the logic that drives this has been pulled out into loncommon.
11430: 
11431: 
11432: 
11433: ssi_with_retries - Does the server side include of a resource.
11434:                      if the ssi call returns an error we'll retry it up to
11435:                      the number of times requested by the caller.
11436:                      If we still have a problem, no text is appended to the
11437:                      output and we set some global variables.
11438:                      to indicate to the caller an SSI error occurred.  
11439:                      All of this is supposed to deal with the issues described
11440:                      in LON-CAPA BZ 5631 see:
11441:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11442:                      by informing the user that this happened.
11443: 
11444: Parameters:
11445:   resource   - The resource to include.  This is passed directly, without
11446:                interpretation to lonnet::ssi.
11447:   form       - The form hash parameters that guide the interpretation of the resource
11448:                
11449:   retries    - Number of retries allowed before giving up completely.
11450: Returns:
11451:   On success, returns the rendered resource identified by the resource parameter.
11452: Side Effects:
11453:   The following global variables can be set:
11454:    ssi_error                - If an unrecoverable error occurred this becomes true.
11455:                               It is up to the caller to initialize this to false
11456:                               if desired.
11457:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11458:                               of the resource that could not be rendered by the ssi
11459:                               call.
11460:    ssi_error_message   - The error string fetched from the ssi response
11461:                               in the event of an error.
11462: 
11463: 
11464: =head1 HANDLER SUBROUTINE
11465: 
11466: ssi_with_retries()
11467: 
11468: =head1 SUBROUTINES
11469: 
11470: =over
11471: 
11472: =item scantron_get_correction() : 
11473: 
11474:    Builds the interface screen to interact with the operator to fix a
11475:    specific error condition in a specific scanline
11476: 
11477:  Arguments:
11478:     $r           - Apache request object
11479:     $i           - number of the current scanline
11480:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11481:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11482:     $line        - full contents of the current scanline
11483:     $error       - error condition, valid values are
11484:                    'incorrectCODE', 'duplicateCODE',
11485:                    'doublebubble', 'missingbubble',
11486:                    'duplicateID', 'incorrectID'
11487:     $arg         - extra information needed
11488:        For errors:
11489:          - duplicateID   - paper number that this studentID was seen before on
11490:          - duplicateCODE - array ref of the paper numbers this CODE was
11491:                            seen on before
11492:          - incorrectCODE - current incorrect CODE 
11493:          - doublebubble  - array ref of the bubble lines that have double
11494:                            bubble errors
11495:          - missingbubble - array ref of the bubble lines that have missing
11496:                            bubble errors
11497: 
11498:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
11499:    $randompick  - True if exam folder (or a sub-folder) has randompick set
11500:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11501:                      for current line to question number used for same question
11502:                      in "Master Seqence" (as seen by Course Coordinator).
11503:    $startline   - Reference to hash where key is question number (0 is first)
11504:                   and value is number of first bubble line for current student
11505:                   or code-based randompick and/or randomorder.
11506: 
11507: 
11508: =item  scantron_get_maxbubble() : 
11509: 
11510:    Arguments:
11511:        $nav_error  - Reference to scalar which is a flag to indicate a
11512:                       failure to retrieve a navmap object.
11513:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11514:        calling routine should trap the error condition and display the warning
11515:        found in &navmap_errormsg().
11516: 
11517:        $scantron_config - Reference to bubblesheet format configuration hash.
11518: 
11519:    Returns the maximum number of bubble lines that are expected to
11520:    occur. Does this by walking the selected sequence rendering the
11521:    resource and then checking &Apache::lonxml::get_problem_counter()
11522:    for what the current value of the problem counter is.
11523: 
11524:    Caches the results to $env{'form.scantron_maxbubble'},
11525:    $env{'form.scantron.bubble_lines.n'}, 
11526:    $env{'form.scantron.first_bubble_line.n'} and
11527:    $env{"form.scantron.sub_bubblelines.n"}
11528:    which are the total number of bubble lines, the number of bubble
11529:    lines for response n and number of the first bubble line for response n,
11530:    and a comma separated list of numbers of bubble lines for sub-questions
11531:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11532: 
11533: 
11534: =item  scantron_validate_missingbubbles() : 
11535: 
11536:    Validates all scanlines in the selected file to not have any
11537:     answers that don't have bubbles that have not been verified
11538:     to be bubble free.
11539: 
11540: =item  scantron_process_students() : 
11541: 
11542:    Routine that does the actual grading of the bubblesheet information.
11543: 
11544:    The parsed scanline hash is added to %env 
11545: 
11546:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11547:    foreach resource , with the form data of
11548: 
11549: 	'submitted'     =>'scantron' 
11550: 	'grade_target'  =>'grade',
11551: 	'grade_username'=> username of student
11552: 	'grade_domain'  => domain of student
11553: 	'grade_courseid'=> of course
11554: 	'grade_symb'    => symb of resource to grade
11555: 
11556:     This triggers a grading pass. The problem grading code takes care
11557:     of converting the bubbled letter information (now in %env) into a
11558:     valid submission.
11559: 
11560: =item  scantron_upload_scantron_data() :
11561: 
11562:     Creates the screen for adding a new bubblesheet data file to a course.
11563: 
11564: =item  scantron_upload_scantron_data_save() : 
11565: 
11566:    Adds a provided bubble information data file to the course if user
11567:    has the correct privileges to do so. 
11568: 
11569: =item  valid_file() :
11570: 
11571:    Validates that the requested bubble data file exists in the course.
11572: 
11573: =item  scantron_download_scantron_data() : 
11574: 
11575:    Shows a list of the three internal files (original, corrected,
11576:    skipped) for a specific bubblesheet data file that exists in the
11577:    course.
11578: 
11579: =item  scantron_validate_ID() : 
11580: 
11581:    Validates all scanlines in the selected file to not have any
11582:    invalid or underspecified student/employee IDs
11583: 
11584: =item navmap_errormsg() :
11585: 
11586:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11587:    Should be called whenever the request to instantiate a navmap object fails.  
11588: 
11589: =back
11590: 
11591: =cut

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