File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.60.2.2: download - view: text, annotated - select for diffs
Fri Mar 10 20:23:34 2023 UTC (14 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.791, 1.792

    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.2 2023/03/10 20:23:34 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::bridgetask();
   48: use Apache::lontexconvert();
   49: use HTML::Parser();
   50: use File::MMagic;
   51: use String::Similarity;
   52: use LONCAPA;
   53: 
   54: use POSIX qw(floor);
   55: 
   56: 
   57: 
   58: my %perm=();
   59: my %old_essays=();
   60: 
   61: #  These variables are used to recover from ssi errors
   62: 
   63: my $ssi_retries = 5;
   64: my $ssi_error;
   65: my $ssi_error_resource;
   66: my $ssi_error_message;
   67: 
   68: 
   69: sub ssi_with_retries {
   70:     my ($resource, $retries, %form) = @_;
   71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   72:     if ($response->is_error) {
   73: 	$ssi_error          = 1;
   74: 	$ssi_error_resource = $resource;
   75: 	$ssi_error_message  = $response->code . " " . $response->message;
   76:     }
   77: 
   78:     return $content;
   79: 
   80: }
   81: #
   82: #  Prodcuces an ssi retry failure error message to the user:
   83: #
   84: 
   85: sub ssi_print_error {
   86:     my ($r) = @_;
   87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   88:     $r->print('
   89: <br />
   90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   91: <p>
   92: '.&mt('Unable to retrieve a resource from a server:').'<br />
   93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   94: '.&mt('Error:').' '.$ssi_error_message.'
   95: </p>
   96: <p>'.
   97: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   99: '</p>');
  100:     return;
  101: }
  102: 
  103: #
  104: # --- Retrieve the parts from the metadata file.---
  105: # Returns an array of everything that the resources stores away
  106: #
  107: 
  108: sub getpartlist {
  109:     my ($symb,$errorref) = @_;
  110: 
  111:     my $navmap   = Apache::lonnavmaps::navmap->new();
  112:     unless (ref($navmap)) {
  113:         if (ref($errorref)) { 
  114:             $$errorref = 'navmap';
  115:             return;
  116:         }
  117:     }
  118:     my $res      = $navmap->getBySymb($symb);
  119:     my $partlist = $res->parts();
  120:     my $url      = $res->src();
  121:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  122: 
  123:     my @stores;
  124:     foreach my $part (@{ $partlist }) {
  125: 	foreach my $key (@metakeys) {
  126: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  127: 	}
  128:     }
  129:     return @stores;
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: #--- Count responseIDs, essayresponse items, and dropbox items ---
  147: #--- Sets response_error pointer to "1" if navmaps object broken ---
  148: sub response_type {
  149:     my ($symb,$response_error) = @_;
  150: 
  151:     my $navmap = Apache::lonnavmaps::navmap->new();
  152:     unless (ref($navmap)) {
  153:         if (ref($response_error)) {
  154:             $$response_error = 1;
  155:         }
  156:         return;
  157:     }
  158:     my $res = $navmap->getBySymb($symb);
  159:     unless (ref($res)) {
  160:         $$response_error = 1;
  161:         return;
  162:     }
  163:     my $partlist = $res->parts();
  164:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  165:     my %vPart = 
  166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  167:     my (%response_types,%handgrade);
  168:     foreach my $part (@{ $partlist }) {
  169: 	next if (%vPart && !exists($vPart{$part}));
  170: 
  171: 	my @types = $res->responseType($part);
  172: 	my @ids = $res->responseIds($part);
  173: 	for (my $i=0; $i < scalar(@ids); $i++) {
  174:             $numresp ++;
  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  176:             if ($types[$i] eq 'essay') {
  177:                 $numessay ++;
  178:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  179:                     $numdropbox ++;
  180:                 }
  181:             }
  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
  183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  184: 				     '.handgrade',$symb);
  185: 	}
  186:     }
  187:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  188: }
  189: 
  190: sub flatten_responseType {
  191:     my ($responseType) = @_;
  192:     my @part_response_id =
  193: 	map { 
  194: 	    my $part = $_;
  195: 	    map {
  196: 		[$part,$_]
  197: 		} sort(keys(%{ $responseType->{$part} }));
  198: 	} sort(keys(%$responseType));
  199:     return @part_response_id;
  200: }
  201: 
  202: sub get_display_part {
  203:     my ($partID,$symb)=@_;
  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  205:     if (defined($display) and $display ne '') {
  206:         $display.= ' (<span class="LC_internal_info">'
  207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  208:     } else {
  209: 	$display=$partID;
  210:     }
  211:     return $display;
  212: }
  213: 
  214: #--- Show parts and response type
  215: sub showResourceInfo {
  216:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  217:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  218:         return '<br clear="all">';
  219:     }
  220:     my $coltitle = &mt('Problem Part Shown');
  221:     if ($checkboxes) {
  222:         $coltitle = &mt('Problem Part');
  223:     } else {
  224:         my $checkedparts = 0;
  225:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  226:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  227:                 $checkedparts ++;
  228:             }
  229:         }
  230:         if ($checkedparts == scalar(@{$partlist})) {
  231:             return '<br clear="all">';
  232:         }
  233:         if ($uploads) {
  234:             $coltitle = &mt('Problem Part Selected');
  235:         }
  236:     }
  237:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  238:     if ($checkboxes) {
  239:         my $legend = &mt('Parts to display');
  240:         if ($uploads) {
  241:             $legend = &mt('Part(s) with dropbox');
  242:         }
  243:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  244:                    '<span class="LC_nobreak">'.
  245:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  246:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  247:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  248:                    &mt('Selected parts').'</label></span>'.
  249:                    '<div id="LC_partselector" style="display:none">';
  250:     }
  251:     $result .= &Apache::loncommon::start_data_table()
  252:               .&Apache::loncommon::start_data_table_header_row();
  253:     if ($checkboxes) {
  254:         $result .= '<th>'.&mt('Display?').'</th>';
  255:     }
  256:     $result .= '<th>'.$coltitle.'</th>'
  257:               .'<th>'.&mt('Res. ID').'</th>'
  258:               .'<th>'.&mt('Type').'</th>'
  259:               .&Apache::loncommon::end_data_table_header_row();
  260:     my %partsseen;
  261:     foreach my $partID (sort(keys(%$responseType))) {
  262:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  263:             my $responsetype = $responseType->{$partID}->{$resID};
  264:             if ($uploads) {
  265:                 next unless ($responsetype eq 'essay');
  266:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  267:             }
  268:             my $display_part=&get_display_part($partID,$symb);
  269:             if (exists($partsseen{$partID})) {
  270:                 $result.=&Apache::loncommon::continue_data_table_row();
  271:             } else {
  272:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  273:                 $result.=&Apache::loncommon::start_data_table_row().
  274:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  275:                 if ($checkboxes) {
  276:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  277:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  278:                 } else {
  279:                     $result.=$display_part.'</td>';
  280:                 }
  281:             }
  282:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  283:                     .'<td>'.&mt($responsetype).'</td>'
  284:                     .&Apache::loncommon::end_data_table_row();
  285:         }
  286:     }
  287:     $result.=&Apache::loncommon::end_data_table();
  288:     if ($checkboxes) {
  289:         $result .= '</div></fieldset>';
  290:     }
  291:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  292:     if (!keys(%partsseen)) {
  293:         $result = '';
  294:         if ($uploads) {
  295:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  296:                    '<p class="LC_info">'.
  297:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  298:                    '</p>';
  299:         } else {
  300:             return '<br clear="all" />';
  301:         }
  302:     }  
  303:     return $result;
  304: }
  305: 
  306: sub part_selector_js {
  307:     my $js = <<"END";
  308: function toggleParts(formname) {
  309:     if (document.getElementById('LC_partselector')) {
  310:         var index = '';
  311:         if (document.forms.length) {
  312:             for (var i=0; i<document.forms.length; i++) {
  313:                 if (document.forms[i].name == formname) {
  314:                     index = i;
  315:                     break;
  316:                 }
  317:             }
  318:         }
  319:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  320:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  321:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  322:                    var val = document.forms[index].elements['chooseparts'][i].value;
  323:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  324:                         document.getElementById('LC_partselector').style.display = 'block';
  325:                     } else {
  326:                         document.getElementById('LC_partselector').style.display = 'none';
  327:                     }
  328:                 }
  329:             }
  330:         }
  331:     }
  332: }
  333: END
  334:     return &Apache::lonhtmlcommon::scripttag($js);
  335: }
  336: 
  337: sub reset_caches {
  338:     &reset_analyze_cache();
  339:     &reset_perm();
  340:     &reset_old_essays();
  341: }
  342: 
  343: {
  344:     my %analyze_cache;
  345:     my %analyze_cache_formkeys;
  346: 
  347:     sub reset_analyze_cache {
  348: 	undef(%analyze_cache);
  349:         undef(%analyze_cache_formkeys);
  350:     }
  351: 
  352:     sub get_analyze {
  353: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  354: 	my $key = "$symb\0$uname\0$udom";
  355:         if ($type eq 'randomizetry') {
  356:             if ($trial ne '') {
  357:                 $key .= "\0".$trial;
  358:             }
  359:         }
  360: 	if (exists($analyze_cache{$key})) {
  361:             my $getupdate = 0;
  362:             if (ref($add_to_hash) eq 'HASH') {
  363:                 foreach my $item (keys(%{$add_to_hash})) {
  364:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  365:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  366:                             $getupdate = 1;
  367:                             last;
  368:                         }
  369:                     } else {
  370:                         $getupdate = 1;
  371:                     }
  372:                 }
  373:             }
  374:             if (!$getupdate) {
  375:                 return $analyze_cache{$key};
  376:             }
  377:         }
  378: 
  379: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  380: 	$url=&Apache::lonnet::clutter($url);
  381:         my %form = ('grade_target'      => 'analyze',
  382:                     'grade_domain'      => $udom,
  383:                     'grade_symb'        => $symb,
  384:                     'grade_courseid'    =>  $env{'request.course.id'},
  385:                     'grade_username'    => $uname,
  386:                     'grade_noincrement' => $no_increment);
  387:         if ($bubbles_per_row ne '') {
  388:             $form{'bubbles_per_row'} = $bubbles_per_row;
  389:         }
  390:         if ($type eq 'randomizetry') {
  391:             $form{'grade_questiontype'} = $type;
  392:             if ($rndseed ne '') {
  393:                 $form{'grade_rndseed'} = $rndseed;
  394:             }
  395:         }
  396:         if (ref($add_to_hash)) {
  397:             %form = (%form,%{$add_to_hash});
  398:         }
  399: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  400: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  401: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  402:         if (ref($add_to_hash) eq 'HASH') {
  403:             $analyze_cache_formkeys{$key} = $add_to_hash;
  404:         } else {
  405:             $analyze_cache_formkeys{$key} = {};
  406:         }
  407: 	return $analyze_cache{$key} = \%analyze;
  408:     }
  409: 
  410:     sub get_order {
  411: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  412: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  413: 	return $analyze->{"$partid.$respid.shown"};
  414:     }
  415: 
  416:     sub get_radiobutton_correct_foil {
  417: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  418: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  419:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  420:         if (ref($foils) eq 'ARRAY') {
  421: 	    foreach my $foil (@{$foils}) {
  422: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  423: 		    return $foil;
  424: 	        }
  425: 	    }
  426: 	}
  427:     }
  428: 
  429:     sub scantron_partids_tograde {
  430:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  431:         my (%analysis,@parts);
  432:         if (ref($resource)) {
  433:             my $symb = $resource->symb();
  434:             my $add_to_form;
  435:             if ($check_for_randomlist) {
  436:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  437:             }
  438:             if ($scancode) {
  439:                 if (ref($add_to_form) eq 'HASH') {
  440:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  441:                 } else {
  442:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  443:                 }
  444:             }
  445:             my $analyze =
  446:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  447:                              undef,undef,undef,$bubbles_per_row);
  448:             if (ref($analyze) eq 'HASH') {
  449:                 %analysis = %{$analyze};
  450:             }
  451:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  452:                 foreach my $part (@{$analysis{'parts'}}) {
  453:                     my ($id,$respid) = split(/\./,$part);
  454:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  455:                         push(@parts,$part);
  456:                     }
  457:                 }
  458:             }
  459:         }
  460:         return (\%analysis,\@parts);
  461:     }
  462: 
  463: }
  464: 
  465: #--- Clean response type for display
  466: #--- Currently filters option/rank/radiobutton/match/essay/Task
  467: #        response types only.
  468: sub cleanRecord {
  469:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  470: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  471:     my $grayFont = '<span class="LC_internal_info">';
  472:     if ($response =~ /^(option|rank)$/) {
  473: 	my %answer=&Apache::lonnet::str2hash($answer);
  474:         my @answer = %answer;
  475:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  476: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  477: 	my ($toprow,$bottomrow);
  478: 	foreach my $foil (@$order) {
  479: 	    if ($grading{$foil} == 1) {
  480: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  481: 	    } else {
  482: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  483: 	    }
  484: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  485: 	}
  486: 	return '<blockquote><table border="1">'.
  487: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  488: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  489: 	    $bottomrow.'</tr></table></blockquote>';
  490:     } elsif ($response eq 'match') {
  491: 	my %answer=&Apache::lonnet::str2hash($answer);
  492:         my @answer = %answer;
  493:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  494: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  495: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  496: 	my ($toprow,$middlerow,$bottomrow);
  497: 	foreach my $foil (@$order) {
  498: 	    my $item=shift(@items);
  499: 	    if ($grading{$foil} == 1) {
  500: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  501: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  502: 	    } else {
  503: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  504: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  505: 	    }
  506: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  507: 	}
  508: 	return '<blockquote><table border="1">'.
  509: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  510: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  511: 	    $middlerow.'</tr>'.
  512: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  513: 	    $bottomrow.'</tr></table></blockquote>';
  514:     } elsif ($response eq 'radiobutton') {
  515: 	my %answer=&Apache::lonnet::str2hash($answer);
  516:         my @answer = %answer;
  517:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  518: 	my ($toprow,$bottomrow);
  519: 	my $correct = 
  520: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  521: 	foreach my $foil (@$order) {
  522: 	    if (exists($answer{$foil})) {
  523: 		if ($foil eq $correct) {
  524: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  525: 		} else {
  526: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  527: 		}
  528: 	    } else {
  529: 		$toprow.='<td>'.&mt('false').'</td>';
  530: 	    }
  531: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  532: 	}
  533: 	return '<blockquote><table border="1">'.
  534: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  535: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  536: 	    $bottomrow.'</tr></table></blockquote>';
  537:     } elsif ($response eq 'essay') {
  538: 	if (! exists ($env{'form.'.$symb})) {
  539: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  540: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  541: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  542: 
  543: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  544: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  545: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  546: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  547: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  548: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  549: 	}
  550:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  551: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  552:     } elsif ( $response eq 'organic') {
  553:         my $result=&mt('Smile representation: [_1]',
  554:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  555: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  556: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  557: 	return $result;
  558:     } elsif ( $response eq 'Task') {
  559: 	if ( $answer eq 'SUBMITTED') {
  560: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  561: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  562: 	    return $result;
  563: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  564: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  565: 			       keys(%{$record}));
  566: 	    return join('<br />',($version,@matches));
  567: 			       
  568: 			       
  569: 	} else {
  570: 	    my $result =
  571: 		'<p>'
  572: 		.&mt('Overall result: [_1]',
  573: 		     $record->{$version."resource.$respid.$partid.status"})
  574: 		.'</p>';
  575: 	    
  576: 	    $result .= '<ul>';
  577: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  578: 			     keys(%{$record}));
  579: 	    foreach my $grade (sort(@grade)) {
  580: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  581: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  582: 				     $dim, $record->{$grade}).
  583: 			  '</li>';
  584: 	    }
  585: 	    $result.='</ul>';
  586: 	    return $result;
  587: 	}
  588:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  589:         # Respect multiple input fields, see Bug #5409 
  590: 	$answer = 
  591: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  592: 							      $answer);
  593: 	return $answer;
  594:     }
  595:     return &HTML::Entities::encode($answer, '"<>&');
  596: }
  597: 
  598: #-- A couple of common js functions
  599: sub commonJSfunctions {
  600:     my $request = shift;
  601:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  602:     function radioSelection(radioButton) {
  603: 	var selection=null;
  604: 	if (radioButton.length > 1) {
  605: 	    for (var i=0; i<radioButton.length; i++) {
  606: 		if (radioButton[i].checked) {
  607: 		    return radioButton[i].value;
  608: 		}
  609: 	    }
  610: 	} else {
  611: 	    if (radioButton.checked) return radioButton.value;
  612: 	}
  613: 	return selection;
  614:     }
  615: 
  616:     function pullDownSelection(selectOne) {
  617: 	var selection="";
  618: 	if (selectOne.length > 1) {
  619: 	    for (var i=0; i<selectOne.length; i++) {
  620: 		if (selectOne[i].selected) {
  621: 		    return selectOne[i].value;
  622: 		}
  623: 	    }
  624: 	} else {
  625:             // only one value it must be the selected one
  626: 	    return selectOne.value;
  627: 	}
  628:     }
  629: COMMONJSFUNCTIONS
  630: }
  631: 
  632: #--- Dumps the class list with usernames,list of sections,
  633: #--- section, ids and fullnames for each user.
  634: sub getclasslist {
  635:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  636:     my @getsec;
  637:     my @getgroup;
  638:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  639:     if (!ref($getsec)) {
  640: 	if ($getsec ne '' && $getsec ne 'all') {
  641: 	    @getsec=($getsec);
  642: 	}
  643:     } else {
  644: 	@getsec=@{$getsec};
  645:     }
  646:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  647:     if (!ref($getgroup)) {
  648: 	if ($getgroup ne '' && $getgroup ne 'all') {
  649: 	    @getgroup=($getgroup);
  650: 	}
  651:     } else {
  652: 	@getgroup=@{$getgroup};
  653:     }
  654:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  655: 
  656:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  657:     # Bail out if we were unable to get the classlist
  658:     return if (! defined($classlist));
  659:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  660:     #
  661:     my %sections;
  662:     my %fullnames;
  663:     my ($cdom,$cnum,$partlist);
  664:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  665:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  666:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  667:         my $res_error;
  668:         ($partlist) = &response_type($symb,\$res_error);
  669:     }
  670:     foreach my $student (keys(%$classlist)) {
  671:         my $end      = 
  672:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  673:         my $start    = 
  674:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  675:         my $id       = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  677:         my $section  = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  679:         my $fullname = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  681:         my $status   = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  683:         my $group   = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  685: 	# filter students according to status selected
  686: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  687: 	    if (!($stu_status =~ $status)) {
  688: 		delete($classlist->{$student});
  689: 		next;
  690: 	    }
  691: 	}
  692: 	# filter students according to groups selected
  693: 	my @stu_groups = split(/,/,$group);
  694: 	if (@getgroup) {
  695: 	    my $exclude = 1;
  696: 	    foreach my $grp (@getgroup) {
  697: 	        foreach my $stu_group (@stu_groups) {
  698: 	            if ($stu_group eq $grp) {
  699: 	                $exclude = 0;
  700:     	            } 
  701: 	        }
  702:     	        if (($grp eq 'none') && !$group) {
  703:         	    $exclude = 0;
  704:         	}
  705: 	    }
  706: 	    if ($exclude) {
  707: 	        delete($classlist->{$student});
  708: 		next;
  709: 	    }
  710: 	}
  711:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  712:             my $udom =
  713:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  714:             my $uname =
  715:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  716:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  717:                 if ($submitonly eq 'queued') {
  718:                     my %queue_status =
  719:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  720:                                                                 $udom,$uname);
  721:                     if (!defined($queue_status{'gradingqueue'})) {
  722:                         delete($classlist->{$student});
  723:                         next;
  724:                     }
  725:                 } else {
  726:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  727:                     my $submitted = 0;
  728:                     my $graded = 0;
  729:                     my $incorrect = 0;
  730:                     foreach (keys(%status)) {
  731:                         $submitted = 1 if ($status{$_} ne 'nothing');
  732:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  733:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  734: 
  735:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  736:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  737:                             $submitted = 0;
  738:                         }
  739:                     }
  740:                     if (!$submitted && ($submitonly eq 'yes' ||
  741:                                         $submitonly eq 'incorrect' ||
  742:                                         $submitonly eq 'graded')) {
  743:                         delete($classlist->{$student});
  744:                         next;
  745:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  746:                         delete($classlist->{$student});
  747:                         next;
  748:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  749:                         delete($classlist->{$student});
  750:                         next;
  751:                     }
  752:                 }
  753:             }
  754:         }
  755: 	$section = ($section ne '' ? $section : 'none');
  756: 	if (&canview($section)) {
  757: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  758: 		$sections{$section}++;
  759: 		if ($classlist->{$student}) {
  760: 		    $fullnames{$student}=$fullname;
  761: 		}
  762: 	    } else {
  763: 		delete($classlist->{$student});
  764: 	    }
  765: 	} else {
  766: 	    delete($classlist->{$student});
  767: 	}
  768:     }
  769:     my @sections = sort(keys(%sections));
  770:     return ($classlist,\@sections,\%fullnames);
  771: }
  772: 
  773: sub canmodify {
  774:     my ($sec)=@_;
  775:     if ($perm{'mgr'}) {
  776: 	if (!defined($perm{'mgr_section'})) {
  777: 	    # can modify whole class
  778: 	    return 1;
  779: 	} else {
  780: 	    if ($sec eq $perm{'mgr_section'}) {
  781: 		#can modify the requested section
  782: 		return 1;
  783: 	    } else {
  784: 		# can't modify the requested section
  785: 		return 0;
  786: 	    }
  787: 	}
  788:     }
  789:     #can't modify
  790:     return 0;
  791: }
  792: 
  793: sub canview {
  794:     my ($sec)=@_;
  795:     if ($perm{'vgr'}) {
  796: 	if (!defined($perm{'vgr_section'})) {
  797: 	    # can view whole class
  798: 	    return 1;
  799: 	} else {
  800: 	    if ($sec eq $perm{'vgr_section'}) {
  801: 		#can view the requested section
  802: 		return 1;
  803: 	    } else {
  804: 		# can't view the requested section
  805: 		return 0;
  806: 	    }
  807: 	}
  808:     }
  809:     #can't view
  810:     return 0;
  811: }
  812: 
  813: #--- Retrieve the grade status of a student for all the parts
  814: sub student_gradeStatus {
  815:     my ($symb,$udom,$uname,$partlist) = @_;
  816:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  817:     my %partstatus = ();
  818:     foreach (@$partlist) {
  819: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  820: 	$status              = 'nothing' if ($status eq '');
  821: 	$partstatus{$_}      = $status;
  822: 	my $subkey           = "resource.$_.submitted_by";
  823: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  824:     }
  825:     return %partstatus;
  826: }
  827: 
  828: # hidden form and javascript that calls the form
  829: # Use by verifyscript and viewgrades
  830: # Shows a student's view of problem and submission
  831: sub jscriptNform {
  832:     my ($symb) = @_;
  833:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  834:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  835: 	'    function viewOneStudent(user,domain) {'."\n".
  836: 	'	document.onestudent.student.value = user;'."\n".
  837: 	'	document.onestudent.userdom.value = domain;'."\n".
  838: 	'	document.onestudent.submit();'."\n".
  839: 	'    }'."\n".
  840: 	"\n");
  841:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  842: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  843: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  844: 	'<input type="hidden" name="command" value="submission" />'."\n".
  845: 	'<input type="hidden" name="student" value="" />'."\n".
  846: 	'<input type="hidden" name="userdom" value="" />'."\n".
  847: 	'</form>'."\n";
  848:     return $jscript;
  849: }
  850: 
  851: 
  852: 
  853: # Given the score (as a number [0-1] and the weight) what is the final
  854: # point value? This function will round to the nearest tenth, third,
  855: # or quarter if one of those is within the tolerance of .00001.
  856: sub compute_points {
  857:     my ($score, $weight) = @_;
  858:     
  859:     my $tolerance = .00001;
  860:     my $points = $score * $weight;
  861: 
  862:     # Check for nearness to 1/x.
  863:     my $check_for_nearness = sub {
  864:         my ($factor) = @_;
  865:         my $num = ($points * $factor) + $tolerance;
  866:         my $floored_num = floor($num);
  867:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  868:             return $floored_num / $factor;
  869:         }
  870:         return $points;
  871:     };
  872: 
  873:     $points = $check_for_nearness->(10);
  874:     $points = $check_for_nearness->(3);
  875:     $points = $check_for_nearness->(4);
  876:     
  877:     return $points;
  878: }
  879: 
  880: #------------------ End of general use routines --------------------
  881: 
  882: #
  883: # Find most similar essay
  884: #
  885: 
  886: sub most_similar {
  887:     my ($uname,$udom,$symb,$uessay)=@_;
  888: 
  889:     unless ($symb) { return ''; }
  890: 
  891:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  892: 
  893: # ignore spaces and punctuation
  894: 
  895:     $uessay=~s/\W+/ /gs;
  896: 
  897: # ignore empty submissions (occuring when only files are sent)
  898: 
  899:     unless ($uessay=~/\w+/s) { return ''; }
  900: 
  901: # these will be returned. Do not care if not at least 50 percent similar
  902:     my $limit=0.6;
  903:     my $sname='';
  904:     my $sdom='';
  905:     my $scrsid='';
  906:     my $sessay='';
  907: # go through all essays ...
  908:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  909: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  910: # ... except the same student
  911:         next if (($tname eq $uname) && ($tdom eq $udom));
  912: 	my $tessay=$old_essays{$symb}{$tkey};
  913: 	$tessay=~s/\W+/ /gs;
  914: # String similarity gives up if not even limit
  915: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  916: # Found one
  917: 	if ($tsimilar>$limit) {
  918: 	    $limit=$tsimilar;
  919: 	    $sname=$tname;
  920: 	    $sdom=$tdom;
  921: 	    $scrsid=$tcrsid;
  922: 	    $sessay=$old_essays{$symb}{$tkey};
  923: 	}
  924:     }
  925:     if ($limit>0.6) {
  926:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  927:     } else {
  928:        return ('','','','',0);
  929:     }
  930: }
  931: 
  932: #-------------------------------------------------------------------
  933: 
  934: #------------------------------------ Receipt Verification Routines
  935: #
  936: 
  937: sub initialverifyreceipt {
  938:    my ($request,$symb) = @_;
  939:    &commonJSfunctions($request);
  940:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  941:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  942:         '-<input type="text" name="receipt" size="4" />'.
  943:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  944:         '<input type="hidden" name="command" value="verify" />'.
  945:         "</form>\n";
  946: }
  947: 
  948: #--- Check whether a receipt number is valid.---
  949: sub verifyreceipt {
  950:     my ($request,$symb) = @_;
  951: 
  952:     my $courseid = $env{'request.course.id'};
  953:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  954: 	$env{'form.receipt'};
  955:     $receipt     =~ s/[^\-\d]//g;
  956: 
  957:     my $title =
  958: 	'<h3><span class="LC_info">'.
  959: 	&mt('Verifying Receipt Number [_1]',$receipt).
  960: 	'</span></h3>'."\n";
  961: 
  962:     my ($string,$contents,$matches) = ('','',0);
  963:     my (undef,undef,$fullname) = &getclasslist('all','0');
  964:     
  965:     my $receiptparts=0;
  966:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  967: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  968:     my $parts=['0'];
  969:     if ($receiptparts) {
  970:         my $res_error; 
  971:         ($parts)=&response_type($symb,\$res_error);
  972:         if ($res_error) {
  973:             return &navmap_errormsg();
  974:         } 
  975:     }
  976:     
  977:     my $header = 
  978: 	&Apache::loncommon::start_data_table().
  979: 	&Apache::loncommon::start_data_table_header_row().
  980: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  981: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  982: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  983:     if ($receiptparts) {
  984: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  985:     }
  986:     $header.=
  987: 	&Apache::loncommon::end_data_table_header_row();
  988: 
  989:     foreach (sort 
  990: 	     {
  991: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  992: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  993: 		 }
  994: 		 return $a cmp $b;
  995: 	     } (keys(%$fullname))) {
  996: 	my ($uname,$udom)=split(/\:/);
  997: 	foreach my $part (@$parts) {
  998: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  999: 		$contents.=
 1000: 		    &Apache::loncommon::start_data_table_row().
 1001: 		    '<td>&nbsp;'."\n".
 1002: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1003: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1004: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1005: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1006: 		if ($receiptparts) {
 1007: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1008: 		}
 1009: 		$contents.= 
 1010: 		    &Apache::loncommon::end_data_table_row()."\n";
 1011: 		
 1012: 		$matches++;
 1013: 	    }
 1014: 	}
 1015:     }
 1016:     if ($matches == 0) {
 1017:         $string = $title
 1018:                  .'<p class="LC_warning">'
 1019:                  .&mt('No match found for the above receipt number.')
 1020:                  .'</p>';
 1021:     } else {
 1022: 	$string = &jscriptNform($symb).$title.
 1023: 	    '<p>'.
 1024: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1025: 	    '</p>'.
 1026: 	    $header.
 1027: 	    $contents.
 1028: 	    &Apache::loncommon::end_data_table()."\n";
 1029:     }
 1030:     return $string;
 1031: }
 1032: 
 1033: #--- This is called by a number of programs.
 1034: #--- Called from the Grading Menu - View/Grade an individual student
 1035: #--- Also called directly when one clicks on the subm button 
 1036: #    on the problem page.
 1037: sub listStudents {
 1038:     my ($request,$symb,$submitonly,$divforres) = @_;
 1039: 
 1040:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1041:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1042:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1043:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1044:     unless ($submitonly) {
 1045:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1046:     }
 1047: 
 1048:     my $result='';
 1049:     my $res_error;
 1050:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1051: 
 1052:     my $table;
 1053:     if (ref($partlist) eq 'ARRAY') {
 1054:         if (scalar(@$partlist) > 1 ) {
 1055:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1056:         } elsif ($divforres) {
 1057:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1058:         } else {
 1059:             $table = '<br clear="all" />';
 1060:         }
 1061:     }
 1062: 
 1063:     my %js_lt = &Apache::lonlocal::texthash (
 1064: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1065: 		'single'   => 'Please select the student before clicking on the Next button.',
 1066: 	     );
 1067:     &js_escape(\%js_lt);
 1068:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1069:     function checkSelect(checkBox) {
 1070: 	var ctr=0;
 1071: 	var sense="";
 1072: 	if (checkBox.length > 1) {
 1073: 	    for (var i=0; i<checkBox.length; i++) {
 1074: 		if (checkBox[i].checked) {
 1075: 		    ctr++;
 1076: 		}
 1077: 	    }
 1078: 	    sense = '$js_lt{'multiple'}';
 1079: 	} else {
 1080: 	    if (checkBox.checked) {
 1081: 		ctr = 1;
 1082: 	    }
 1083: 	    sense = '$js_lt{'single'}';
 1084: 	}
 1085: 	if (ctr == 0) {
 1086: 	    alert(sense);
 1087: 	    return false;
 1088: 	}
 1089: 	document.gradesub.submit();
 1090:     }
 1091: 
 1092:     function reLoadList(formname) {
 1093: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1094: 	formname.command.value = 'submission';
 1095: 	formname.submit();
 1096:     }
 1097: LISTJAVASCRIPT
 1098: 
 1099:     &commonJSfunctions($request);
 1100:     $request->print($result);
 1101: 
 1102:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1103: 	"\n".$table;
 1104: 
 1105:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1106:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1107:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1108:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1109:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1110:                   .&Apache::lonhtmlcommon::row_closure();
 1111:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1112:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1113:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1114:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1115:                   .&Apache::lonhtmlcommon::row_closure();
 1116: 
 1117:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1118:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1119:     $env{'form.Status'} = $saveStatus;
 1120:     my %optiontext = &Apache::lonlocal::texthash (
 1121:                           lastonly => 'last submission',
 1122:                           last     => 'last submission with details',
 1123:                           datesub  => 'all submissions',
 1124:                           all      => 'all submissions with details',
 1125:                       );
 1126:     my $submission_options =
 1127:         '<span class="LC_nobreak">'.
 1128:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1129:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1130:         '<span class="LC_nobreak">'.
 1131:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1132:         $optiontext{'last'}.' </label></span>'."\n".
 1133:         '<span class="LC_nobreak">'.
 1134:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1135:         $optiontext{'datesub'}.'</label></span>'."\n".
 1136:         '<span class="LC_nobreak">'.
 1137:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1138:         $optiontext{'all'}.'</label></span>';
 1139:     my ($compmsg,$nocompmsg);
 1140:     $nocompmsg = ' checked="checked"';
 1141:     if ($numessay) {
 1142:         $compmsg = $nocompmsg;
 1143:         $nocompmsg = '';
 1144:     }
 1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
 1146:                   .$submission_options;
 1147: # Check if any gradable
 1148:     my $showmore;
 1149:     if ($perm{'mgr'}) {
 1150:         my @sections;
 1151:         if ($env{'request.course.sec'} ne '') {
 1152:             @sections = ($env{'request.course.sec'});
 1153:         } elsif ($env{'form.section'} eq '') {
 1154:             @sections = ('all');
 1155:         } else {
 1156:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1157:         }
 1158:         if (grep(/^all$/,@sections)) {
 1159:             $showmore = 1;
 1160:         } else {
 1161:             foreach my $sec (@sections) {
 1162:                 if (&canmodify($sec)) {
 1163:                     $showmore = 1;
 1164:                     last;
 1165:                 }
 1166:             }
 1167:         }
 1168:     }
 1169: 
 1170:     if ($showmore) {
 1171:         $gradeTable .=
 1172:                    &Apache::lonhtmlcommon::row_closure()
 1173:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1174:                   .'<span class="LC_nobreak">'
 1175:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1176:                   .&mt('No').('&nbsp;'x2).'</label>'
 1177:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1178:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1179:                   .&Apache::lonhtmlcommon::row_closure();
 1180: 
 1181:         $gradeTable .= 
 1182:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1183:                   .'<select name="increment">'
 1184:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1185:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1186:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1187:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1188:                   .'</select>';
 1189:     }
 1190:     $gradeTable .= 
 1191:         &build_section_inputs().
 1192: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1194: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1195:     if (exists($env{'form.Status'})) {
 1196: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
 1197:     } else {
 1198:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1199:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1200:                       .&Apache::lonhtmlcommon::StatusOptions(
 1201:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1202:     }
 1203:     if ($numessay) {
 1204:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1205:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1206:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1207:     }
 1208:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1209:                   .&Apache::lonhtmlcommon::end_pick_box();
 1210: 
 1211:     $gradeTable .= '<p>'
 1212:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1213:                   .'<input type="hidden" name="command" value="processGroup" />'
 1214:                   .'</p>';
 1215: 
 1216: # checkall buttons
 1217:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1218:     $gradeTable.='<input type="button" '."\n".
 1219:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1220:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1221:     $gradeTable.=&check_buttons();
 1222:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1223:     $gradeTable.= &Apache::loncommon::start_data_table().
 1224: 	&Apache::loncommon::start_data_table_header_row();
 1225:     my $loop = 0;
 1226:     while ($loop < 2) {
 1227: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1228: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1229: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1230: 	    foreach my $part (sort(@$partlist)) {
 1231: 		my $display_part=
 1232: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1233: 		$gradeTable.=
 1234: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1235: 	    }
 1236: 	} elsif ($submitonly eq 'queued') {
 1237: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1238: 	}
 1239: 	$loop++;
 1240: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1241:     }
 1242:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1243: 
 1244:     my $ctr = 0;
 1245:     foreach my $student (sort 
 1246: 			 {
 1247: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1248: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1249: 			     }
 1250: 			     return $a cmp $b;
 1251: 			 }
 1252: 			 (keys(%$fullname))) {
 1253: 	my ($uname,$udom) = split(/:/,$student);
 1254: 
 1255: 	my %status = ();
 1256: 
 1257: 	if ($submitonly eq 'queued') {
 1258: 	    my %queue_status = 
 1259: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1260: 							$udom,$uname);
 1261: 	    next if (!defined($queue_status{'gradingqueue'}));
 1262: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1263: 	}
 1264: 
 1265: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1266: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1267: 	    my $submitted = 0;
 1268: 	    my $graded = 0;
 1269: 	    my $incorrect = 0;
 1270: 	    foreach (keys(%status)) {
 1271: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1272: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1273: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1274: 		
 1275: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1276: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1277: 		    $submitted = 0;
 1278: 		    my ($part)=split(/\./,$partid);
 1279: 		    $gradeTable.='<input type="hidden" name="'.
 1280: 			$student.':'.$part.':submitted_by" value="'.
 1281: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1282: 		}
 1283: 	    }
 1284: 	    
 1285: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1286: 				     $submitonly eq 'incorrect' ||
 1287: 				     $submitonly eq 'graded'));
 1288: 	    next if (!$graded && ($submitonly eq 'graded'));
 1289: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1290: 	}
 1291: 
 1292: 	$ctr++;
 1293: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1294:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1295: 	if ( $perm{'vgr'} eq 'F' ) {
 1296: 	    if ($ctr%2 ==1) {
 1297: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1298: 	    }
 1299: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1300:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1301:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1302: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1303: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1304: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1305: 
 1306: 	    if ($submitonly ne 'all') {
 1307: 		foreach (sort(keys(%status))) {
 1308: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1309: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1310: 		}
 1311: 	    }
 1312: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1313: 	    if ($ctr%2 ==0) {
 1314: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1315: 	    }
 1316: 	}
 1317:     }
 1318:     if ($ctr%2 ==1) {
 1319: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1320: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1321: 		foreach (@$partlist) {
 1322: 		    $gradeTable.='<td>&nbsp;</td>';
 1323: 		}
 1324: 	    } elsif ($submitonly eq 'queued') {
 1325: 		$gradeTable.='<td>&nbsp;</td>';
 1326: 	    }
 1327: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1328:     }
 1329: 
 1330:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1331:         '<input type="button" '.
 1332:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1333:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1334:     if ($ctr == 0) {
 1335: 	my $num_students=(scalar(keys(%$fullname)));
 1336: 	if ($num_students eq 0) {
 1337: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1338: 	} else {
 1339: 	    my $submissions='submissions';
 1340: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1341: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1342: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1343: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1344: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1345: 		    $num_students).
 1346: 		'</span><br />';
 1347: 	}
 1348:     } elsif ($ctr == 1) {
 1349: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1350:     }
 1351:     $request->print($gradeTable);
 1352:     return '';
 1353: }
 1354: 
 1355: #---- Called from the listStudents routine
 1356: 
 1357: sub check_script {
 1358:     my ($form,$type) = @_;
 1359:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1360:     function checkall() {
 1361:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1362:             ele = document.forms.'.$form.'.elements[i];
 1363:             if (ele.name == "'.$type.'") {
 1364:             document.forms.'.$form.'.elements[i].checked=true;
 1365:                                        }
 1366:         }
 1367:     }
 1368: 
 1369:     function checksec() {
 1370:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1371:             ele = document.forms.'.$form.'.elements[i];
 1372:            string = document.forms.'.$form.'.chksec.value;
 1373:            if
 1374:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1375:               document.forms.'.$form.'.elements[i].checked=true;
 1376:             }
 1377:         }
 1378:     }
 1379: 
 1380: 
 1381:     function uncheckall() {
 1382:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1383:             ele = document.forms.'.$form.'.elements[i];
 1384:             if (ele.name == "'.$type.'") {
 1385:             document.forms.'.$form.'.elements[i].checked=false;
 1386:                                        }
 1387:         }
 1388:     }
 1389: 
 1390: '."\n");
 1391:     return $chkallscript;
 1392: }
 1393: 
 1394: sub check_buttons {
 1395:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1396:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1397:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1398:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1399:     return $buttons;
 1400: }
 1401: 
 1402: #     Displays the submissions for one student or a group of students
 1403: sub processGroup {
 1404:     my ($request,$symb) = @_;
 1405:     my $ctr        = 0;
 1406:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1407:     my $total      = scalar(@stuchecked)-1;
 1408: 
 1409:     foreach my $student (@stuchecked) {
 1410: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1411: 	$env{'form.student'}        = $uname;
 1412: 	$env{'form.userdom'}        = $udom;
 1413: 	$env{'form.fullname'}       = $fullname;
 1414: 	&submission($request,$ctr,$total,$symb);
 1415: 	$ctr++;
 1416:     }
 1417:     return '';
 1418: }
 1419: 
 1420: #------------------------------------------------------------------------------------
 1421: #
 1422: #-------------------------- Next few routines handles grading by student, essentially
 1423: #                           handles essay response type problem/part
 1424: #
 1425: #--- Javascript to handle the submission page functionality ---
 1426: sub sub_page_js {
 1427:     my $request = shift;
 1428:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1429:     &js_escape(\$alertmsg);
 1430:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1431:     function updateRadio(formname,id,weight) {
 1432: 	var gradeBox = formname["GD_BOX"+id];
 1433: 	var radioButton = formname["RADVAL"+id];
 1434: 	var oldpts = formname["oldpts"+id].value;
 1435: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1436: 	gradeBox.value = pts;
 1437: 	var resetbox = false;
 1438: 	if (isNaN(pts) || pts < 0) {
 1439: 	    alert("$alertmsg"+pts);
 1440: 	    for (var i=0; i<radioButton.length; i++) {
 1441: 		if (radioButton[i].checked) {
 1442: 		    gradeBox.value = i;
 1443: 		    resetbox = true;
 1444: 		}
 1445: 	    }
 1446: 	    if (!resetbox) {
 1447: 		formtextbox.value = "";
 1448: 	    }
 1449: 	    return;
 1450: 	}
 1451: 
 1452: 	if (pts > weight) {
 1453: 	    var resp = confirm("You entered a value ("+pts+
 1454: 			       ") greater than the weight for the part. Accept?");
 1455: 	    if (resp == false) {
 1456: 		gradeBox.value = oldpts;
 1457: 		return;
 1458: 	    }
 1459: 	}
 1460: 
 1461: 	for (var i=0; i<radioButton.length; i++) {
 1462: 	    radioButton[i].checked=false;
 1463: 	    if (pts == i && pts != "") {
 1464: 		radioButton[i].checked=true;
 1465: 	    }
 1466: 	}
 1467: 	updateSelect(formname,id);
 1468: 	formname["stores"+id].value = "0";
 1469:     }
 1470: 
 1471:     function writeBox(formname,id,pts) {
 1472: 	var gradeBox = formname["GD_BOX"+id];
 1473: 	if (checkSolved(formname,id) == 'update') {
 1474: 	    gradeBox.value = pts;
 1475: 	} else {
 1476: 	    var oldpts = formname["oldpts"+id].value;
 1477: 	    gradeBox.value = oldpts;
 1478: 	    var radioButton = formname["RADVAL"+id];
 1479: 	    for (var i=0; i<radioButton.length; i++) {
 1480: 		radioButton[i].checked=false;
 1481: 		if (i == oldpts) {
 1482: 		    radioButton[i].checked=true;
 1483: 		}
 1484: 	    }
 1485: 	}
 1486: 	formname["stores"+id].value = "0";
 1487: 	updateSelect(formname,id);
 1488: 	return;
 1489:     }
 1490: 
 1491:     function clearRadBox(formname,id) {
 1492: 	if (checkSolved(formname,id) == 'noupdate') {
 1493: 	    updateSelect(formname,id);
 1494: 	    return;
 1495: 	}
 1496: 	gradeSelect = formname["GD_SEL"+id];
 1497: 	for (var i=0; i<gradeSelect.length; i++) {
 1498: 	    if (gradeSelect[i].selected) {
 1499: 		var selectx=i;
 1500: 	    }
 1501: 	}
 1502: 	var stores = formname["stores"+id];
 1503: 	if (selectx == stores.value) { return };
 1504: 	var gradeBox = formname["GD_BOX"+id];
 1505: 	gradeBox.value = "";
 1506: 	var radioButton = formname["RADVAL"+id];
 1507: 	for (var i=0; i<radioButton.length; i++) {
 1508: 	    radioButton[i].checked=false;
 1509: 	}
 1510: 	stores.value = selectx;
 1511:     }
 1512: 
 1513:     function checkSolved(formname,id) {
 1514: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1515: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1516: 	    if (!reply) {return "noupdate";}
 1517: 	    formname.overRideScore.value = 'yes';
 1518: 	}
 1519: 	return "update";
 1520:     }
 1521: 
 1522:     function updateSelect(formname,id) {
 1523: 	formname["GD_SEL"+id][0].selected = true;
 1524: 	return;
 1525:     }
 1526: 
 1527: //=========== Check that a point is assigned for all the parts  ============
 1528:     function checksubmit(formname,val,total,parttot) {
 1529: 	formname.gradeOpt.value = val;
 1530: 	if (val == "Save & Next") {
 1531: 	    for (i=0;i<=total;i++) {
 1532: 		for (j=0;j<parttot;j++) {
 1533: 		    var partid = formname["partid"+i+"_"+j].value;
 1534: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1535: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1536: 			if (points == "") {
 1537: 			    var name = formname["name"+i].value;
 1538: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1539: 			    var resp = confirm("You did not assign a score for "+studentID+
 1540: 					       ", part "+partid+". Continue?");
 1541: 			    if (resp == false) {
 1542: 				formname["GD_BOX"+i+"_"+partid].focus();
 1543: 				return false;
 1544: 			    }
 1545: 			}
 1546: 		    }
 1547: 		}
 1548: 	    }
 1549: 	}
 1550: 	formname.submit();
 1551:     }
 1552: 
 1553: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1554:     function checkSubmitPage(formname,total) {
 1555: 	noscore = new Array(100);
 1556: 	var ptr = 0;
 1557: 	for (i=1;i<total;i++) {
 1558: 	    var partid = formname["q_"+i].value;
 1559: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1560: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1561: 		var status = formname["solved"+i+"_"+partid].value;
 1562: 		if (points == "" && status != "correct_by_student") {
 1563: 		    noscore[ptr] = i;
 1564: 		    ptr++;
 1565: 		}
 1566: 	    }
 1567: 	}
 1568: 	if (ptr != 0) {
 1569: 	    var sense = ptr == 1 ? ": " : "s: ";
 1570: 	    var prolist = "";
 1571: 	    if (ptr == 1) {
 1572: 		prolist = noscore[0];
 1573: 	    } else {
 1574: 		var i = 0;
 1575: 		while (i < ptr-1) {
 1576: 		    prolist += noscore[i]+", ";
 1577: 		    i++;
 1578: 		}
 1579: 		prolist += "and "+noscore[i];
 1580: 	    }
 1581: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1582: 	    if (resp == false) {
 1583: 		return false;
 1584: 	    }
 1585: 	}
 1586: 
 1587: 	formname.submit();
 1588:     }
 1589: SUBJAVASCRIPT
 1590: }
 1591: 
 1592: #--- javascript for grading message center
 1593: sub sub_grademessage_js {
 1594:     my $request = shift;
 1595:     my $iconpath = $request->dir_config('lonIconsURL');
 1596:     &commonJSfunctions($request);
 1597: 
 1598:     my $inner_js_msg_central= (<<INNERJS);
 1599: <script type="text/javascript">
 1600:     function checkInput() {
 1601:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1602:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1603:       var usrctr = document.msgcenter.usrctr.value;
 1604:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1605:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1606: 
 1607:       var msgchk = "";
 1608:       if (document.msgcenter.subchk.checked) {
 1609:          msgchk = "msgsub,";
 1610:       }
 1611:       var includemsg = 0;
 1612:       for (var i=1; i<=nmsg; i++) {
 1613:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1614:           var frmmsg = document.msgcenter["msg"+i];
 1615:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1616:           var showflg = opener.document.SCORE["shownOnce"+i];
 1617:           showflg.value = "1";
 1618:           var chkbox = document.msgcenter["msgn"+i];
 1619:           if (chkbox.checked) {
 1620:              msgchk += "savemsg"+i+",";
 1621:              includemsg = 1;
 1622:           }
 1623:       }
 1624:       if (document.msgcenter.newmsgchk.checked) {
 1625:          msgchk += "newmsg"+usrctr;
 1626:          includemsg = 1;
 1627:       }
 1628:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1629:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1630:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1631:       includemsg.value = msgchk;
 1632: 
 1633:       self.close()
 1634: 
 1635:     }
 1636: </script>
 1637: INNERJS
 1638: 
 1639:     my $start_page_msg_central =
 1640:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1641: 				       {'js_ready'  => 1,
 1642: 					'only_body' => 1,
 1643: 					'bgcolor'   =>'#FFFFFF',});
 1644:     my $end_page_msg_central =
 1645: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1646: 
 1647: 
 1648:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1649:     $docopen=~s/^document\.//;
 1650: 
 1651:     my %html_js_lt = &Apache::lonlocal::texthash(
 1652:                 comp => 'Compose Message for: ',
 1653:                 incl => 'Include',
 1654:                 type => 'Type',
 1655:                 subj => 'Subject',
 1656:                 mesa => 'Message',
 1657:                 new  => 'New',
 1658:                 save => 'Save',
 1659:                 canc => 'Cancel',
 1660:              );
 1661:     &html_escape(\%html_js_lt);
 1662:     &js_escape(\%html_js_lt);
 1663:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1664: 
 1665: //===================== Script to view submitted by ==================
 1666:   function viewSubmitter(submitter) {
 1667:     document.SCORE.refresh.value = "on";
 1668:     document.SCORE.NCT.value = "1";
 1669:     document.SCORE.unamedom0.value = submitter;
 1670:     document.SCORE.submit();
 1671:     return;
 1672:   }
 1673: 
 1674: //====================== Script for composing message ==============
 1675:    // preload images
 1676:    img1 = new Image();
 1677:    img1.src = "$iconpath/mailbkgrd.gif";
 1678:    img2 = new Image();
 1679:    img2.src = "$iconpath/mailto.gif";
 1680: 
 1681:   function msgCenter(msgform,usrctr,fullname) {
 1682:     var Nmsg  = msgform.savemsgN.value;
 1683:     savedMsgHeader(Nmsg,usrctr,fullname);
 1684:     var subject = msgform.msgsub.value;
 1685:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1686:     re = /msgsub/;
 1687:     var shwsel = "";
 1688:     if (re.test(msgchk)) { shwsel = "checked" }
 1689:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1690:     displaySubject(checkEntities(subject),shwsel);
 1691:     for (var i=1; i<=Nmsg; i++) {
 1692: 	var testmsg = "savemsg"+i+",";
 1693: 	re = new RegExp(testmsg,"g");
 1694: 	shwsel = "";
 1695: 	if (re.test(msgchk)) { shwsel = "checked" }
 1696: 	var message = document.SCORE["savemsg"+i].value;
 1697: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1698: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1699: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1700:     }
 1701:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1702:     shwsel = "";
 1703:     re = /newmsg/;
 1704:     if (re.test(msgchk)) { shwsel = "checked" }
 1705:     newMsg(newmsg,shwsel);
 1706:     msgTail(); 
 1707:     return;
 1708:   }
 1709: 
 1710:   function checkEntities(strx) {
 1711:     if (strx.length == 0) return strx;
 1712:     var orgStr = ["&", "<", ">", '"']; 
 1713:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1714:     var counter = 0;
 1715:     while (counter < 4) {
 1716: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1717: 	counter++;
 1718:     }
 1719:     return strx;
 1720:   }
 1721: 
 1722:   function strReplace(strx, orgStr, newStr) {
 1723:     return strx.split(orgStr).join(newStr);
 1724:   }
 1725: 
 1726:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1727:     var height = 70*Nmsg+250;
 1728:     if (height > 600) {
 1729: 	height = 600;
 1730:     }
 1731:     var xpos = (screen.width-600)/2;
 1732:     xpos = (xpos < 0) ? '0' : xpos;
 1733:     var ypos = (screen.height-height)/2-30;
 1734:     ypos = (ypos < 0) ? '0' : ypos;
 1735: 
 1736:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1737:     pWin.focus();
 1738:     pDoc = pWin.document;
 1739:     pDoc.$docopen;
 1740:     pDoc.write('$start_page_msg_central');
 1741: 
 1742:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1743:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1744:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1745: 
 1746:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1747:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1748: }
 1749:     function displaySubject(msg,shwsel) {
 1750:     pDoc = pWin.document;
 1751:     pDoc.write("<tr>");
 1752:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1753:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1754:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1755: }
 1756: 
 1757:   function displaySavedMsg(ctr,msg,shwsel) {
 1758:     pDoc = pWin.document;
 1759:     pDoc.write("<tr>");
 1760:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1761:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1762:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1763: }
 1764: 
 1765:   function newMsg(newmsg,shwsel) {
 1766:     pDoc = pWin.document;
 1767:     pDoc.write("<tr>");
 1768:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1769:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1770:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1771: }
 1772: 
 1773:   function msgTail() {
 1774:     pDoc = pWin.document;
 1775:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1776:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1777:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1778:     pDoc.write("<\\/form>");
 1779:     pDoc.write('$end_page_msg_central');
 1780:     pDoc.close();
 1781: }
 1782: 
 1783: SUBJAVASCRIPT
 1784: }
 1785: 
 1786: #--- javascript for essay type problem --
 1787: sub sub_page_kw_js {
 1788:     my $request = shift;
 1789: 
 1790:     unless ($env{'form.compmsg'}) {
 1791:         &commonJSfunctions($request);
 1792:     }
 1793: 
 1794:     my $inner_js_highlight_central= (<<INNERJS);
 1795: <script type="text/javascript">
 1796:     function updateChoice(flag) {
 1797:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1798:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1799:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1800:       opener.document.SCORE.refresh.value = "on";
 1801:       if (opener.document.SCORE.keywords.value!=""){
 1802:          opener.document.SCORE.submit();
 1803:       }
 1804:       self.close()
 1805:     }
 1806: </script>
 1807: INNERJS
 1808: 
 1809:     my $start_page_highlight_central =
 1810:         &Apache::loncommon::start_page('Highlight Central',
 1811:                                        $inner_js_highlight_central,
 1812:                                        {'js_ready'  => 1,
 1813:                                         'only_body' => 1,
 1814:                                         'bgcolor'   =>'#FFFFFF',});
 1815:     my $end_page_highlight_central =
 1816:         &Apache::loncommon::end_page({'js_ready' => 1});
 1817: 
 1818:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1819:     $docopen=~s/^document\.//;
 1820: 
 1821:     my %js_lt = &Apache::lonlocal::texthash(
 1822:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1823:                 plse => 'Please select a word or group of words from document and then click this link.',
 1824:                 adds => 'Add selection to keyword list? Edit if desired.',
 1825:                 col1 => 'red',
 1826:                 col2 => 'green',
 1827:                 col3 => 'blue',
 1828:                 siz1 => 'normal',
 1829:                 siz2 => '+1',
 1830:                 siz3 => '+2',
 1831:                 sty1 => 'normal',
 1832:                 sty2 => 'italic',
 1833:                 sty3 => 'bold',
 1834:              );
 1835:     my %html_js_lt = &Apache::lonlocal::texthash(
 1836:                 save => 'Save',
 1837:                 canc => 'Cancel',
 1838:                 kehi => 'Keyword Highlight Options',
 1839:                 txtc => 'Text Color',
 1840:                 font => 'Font Size',
 1841:                 fnst => 'Font Style',
 1842:              );
 1843:     &js_escape(\%js_lt);
 1844:     &html_escape(\%html_js_lt);
 1845:     &js_escape(\%html_js_lt);
 1846:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1847: 
 1848: //===================== Show list of keywords ====================
 1849:   function keywords(formname) {
 1850:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1851:     if (nret==null) return;
 1852:     formname.keywords.value = nret;
 1853: 
 1854:     if (formname.keywords.value != "") {
 1855:         formname.refresh.value = "on";
 1856:         formname.submit();
 1857:     }
 1858:     return;
 1859:   }
 1860: 
 1861: //===================== Script to add keyword(s) ==================
 1862:   function getSel() {
 1863:     if (document.getSelection) txt = document.getSelection();
 1864:     else if (document.selection) txt = document.selection.createRange().text;
 1865:     else return;
 1866:     if (typeof(txt) != 'string') {
 1867:         txt = String(txt);
 1868:     }
 1869:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1870:     if (cleantxt=="") {
 1871:         alert("$js_lt{'plse'}");
 1872:         return;
 1873:     }
 1874:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1875:     if (nret==null) return;
 1876:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1877:     if (document.SCORE.keywords.value != "") {
 1878:         document.SCORE.refresh.value = "on";
 1879:         document.SCORE.submit();
 1880:     }
 1881:     return;
 1882:   }
 1883: 
 1884: //====================== Script for keyword highlight options ==============
 1885:   function kwhighlight() {
 1886:     var kwclr    = document.SCORE.kwclr.value;
 1887:     var kwsize   = document.SCORE.kwsize.value;
 1888:     var kwstyle  = document.SCORE.kwstyle.value;
 1889:     var redsel = "";
 1890:     var grnsel = "";
 1891:     var blusel = "";
 1892:     var txtcol1 = "$js_lt{'col1'}";
 1893:     var txtcol2 = "$js_lt{'col2'}";
 1894:     var txtcol3 = "$js_lt{'col3'}";
 1895:     var txtsiz1 = "$js_lt{'siz1'}";
 1896:     var txtsiz2 = "$js_lt{'siz2'}";
 1897:     var txtsiz3 = "$js_lt{'siz3'}";
 1898:     var txtsty1 = "$js_lt{'sty1'}";
 1899:     var txtsty2 = "$js_lt{'sty2'}";
 1900:     var txtsty3 = "$js_lt{'sty3'}";
 1901:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1902:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1903:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1904:     var sznsel = "";
 1905:     var sz1sel = "";
 1906:     var sz2sel = "";
 1907:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1908:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1909:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1910:     var synsel = "";
 1911:     var syisel = "";
 1912:     var sybsel = "";
 1913:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1914:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1915:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1916:     highlightCentral();
 1917:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1918:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1919:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1920:     highlightend();
 1921:     return;
 1922:   }
 1923: 
 1924:   function highlightCentral() {
 1925: //    if (window.hwdWin) window.hwdWin.close();
 1926:     var xpos = (screen.width-400)/2;
 1927:     xpos = (xpos < 0) ? '0' : xpos;
 1928:     var ypos = (screen.height-330)/2-30;
 1929:     ypos = (ypos < 0) ? '0' : ypos;
 1930: 
 1931:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1932:     hwdWin.focus();
 1933:     var hDoc = hwdWin.document;
 1934:     hDoc.$docopen;
 1935:     hDoc.write('$start_page_highlight_central');
 1936:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1937:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1938: 
 1939:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1940:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1941:   }
 1942: 
 1943:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1944:     var hDoc = hwdWin.document;
 1945:     hDoc.write("<tr>");
 1946:     hDoc.write("<td align=\\"left\\">");
 1947:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1948:     hDoc.write("<td align=\\"left\\">");
 1949:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1950:     hDoc.write("<td align=\\"left\\">");
 1951:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1952:     hDoc.write("<\\/tr>");
 1953:   }
 1954: 
 1955:   function highlightend() { 
 1956:     var hDoc = hwdWin.document;
 1957:     hDoc.write("<\\/table><br \\/>");
 1958:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1959:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1960:     hDoc.write("<\\/form>");
 1961:     hDoc.write('$end_page_highlight_central');
 1962:     hDoc.close();
 1963:   }
 1964: 
 1965: SUBJAVASCRIPT
 1966: }
 1967: 
 1968: sub get_increment {
 1969:     my $increment = $env{'form.increment'};
 1970:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1971:         $increment != .1) {
 1972:         $increment = 1;
 1973:     }
 1974:     return $increment;
 1975: }
 1976: 
 1977: sub gradeBox_start {
 1978:     return (
 1979:         &Apache::loncommon::start_data_table()
 1980:        .&Apache::loncommon::start_data_table_header_row()
 1981:        .'<th>'.&mt('Part').'</th>'
 1982:        .'<th>'.&mt('Points').'</th>'
 1983:        .'<th>&nbsp;</th>'
 1984:        .'<th>'.&mt('Assign Grade').'</th>'
 1985:        .'<th>'.&mt('Weight').'</th>'
 1986:        .'<th>'.&mt('Grade Status').'</th>'
 1987:        .&Apache::loncommon::end_data_table_header_row()
 1988:     );
 1989: }
 1990: 
 1991: sub gradeBox_end {
 1992:     return (
 1993:         &Apache::loncommon::end_data_table()
 1994:     );
 1995: }
 1996: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1997: sub gradeBox {
 1998:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1999:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2000: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2001:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2002:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2003:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2004:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2005:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2006: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2007:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2008:     my $display_part= &get_display_part($partid,$symb);
 2009:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2010: 				       [$partid]);
 2011:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2012:     if ($last_resets{$partid}) {
 2013:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2014:     }
 2015:     my $result=&Apache::loncommon::start_data_table_row();
 2016:     my $ctr = 0;
 2017:     my $thisweight = 0;
 2018:     my $increment = &get_increment();
 2019: 
 2020:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2021:     while ($thisweight<=$wgt) {
 2022: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2023:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2024: 	    $thisweight.')" value="'.$thisweight.'" '.
 2025: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2026: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2027:         $thisweight += $increment;
 2028: 	$ctr++;
 2029:     }
 2030:     $radio.='</tr></table>';
 2031: 
 2032:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2033: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2034: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2035: 	$wgt.')" /></td>'."\n";
 2036:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2037: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2038: 	' </td>'."\n";
 2039:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2040: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2041:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2042: 	$line.='<option></option>'.
 2043: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2044:     } else {
 2045: 	$line.='<option selected="selected"></option>'.
 2046: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2047:     }
 2048:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2049: 
 2050: 
 2051:     $result .= 
 2052: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2053:     $result.=&Apache::loncommon::end_data_table_row();
 2054:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2055:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2056: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2057: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2058: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2059:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2060:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2061:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2062:         $aggtries.'" />'."\n";
 2063:     my $res_error;
 2064:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2065:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2066:     if ($res_error) {
 2067:         return &navmap_errormsg();
 2068:     }
 2069:     return $result;
 2070: }
 2071: 
 2072: sub handback_box {
 2073:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2074:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2075:     return unless ($numessay);
 2076:     my (@respids);
 2077:     my @part_response_id = &flatten_responseType($responseType);
 2078:     foreach my $part_response_id (@part_response_id) {
 2079:     	my ($part,$resp) = @{ $part_response_id };
 2080:         if ($part eq $partid) {
 2081:             push(@respids,$resp);
 2082:         }
 2083:     }
 2084:     my $result;
 2085:     foreach my $respid (@respids) {
 2086: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2087: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2088: 	next if (!@$files);
 2089: 	my $file_counter = 0;
 2090: 	foreach my $file (@$files) {
 2091: 	    if ($file =~ /\/portfolio\//) {
 2092:                 $file_counter++;
 2093:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2094:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 2095:     	        $file_disp = "$name.$ext";
 2096:     	        $file = $file_path.$file_disp;
 2097:     	        $result.=&mt('Return commented version of [_1] to student.',
 2098:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2099:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2100:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2101: 	    }
 2102: 	}
 2103:         if ($file_counter) {
 2104:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2105:                        '<span class="LC_info">'.
 2106:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2107:         }
 2108:     }
 2109:     return $result;    
 2110: }
 2111: 
 2112: sub show_problem {
 2113:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2114:     my $rendered;
 2115:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2116:     &Apache::lonxml::remember_problem_counter();
 2117:     if ($mode eq 'both' or $mode eq 'text') {
 2118: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2119: 						       $env{'request.course.id'},
 2120: 						       undef,\%form);
 2121:     }
 2122:     if ($removeform) {
 2123: 	$rendered=~s|<form(.*?)>||g;
 2124: 	$rendered=~s|</form>||g;
 2125: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2126:     }
 2127:     my $companswer;
 2128:     if ($mode eq 'both' or $mode eq 'answer') {
 2129: 	&Apache::lonxml::restore_problem_counter();
 2130: 	$companswer=
 2131: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2132: 						    $env{'request.course.id'},
 2133: 						    %form);
 2134:     }
 2135:     if ($removeform) {
 2136: 	$companswer=~s|<form(.*?)>||g;
 2137: 	$companswer=~s|</form>||g;
 2138: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2139:     }
 2140:     my $renderheading = &mt('View of the problem');
 2141:     my $answerheading = &mt('Correct answer');
 2142:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2143:         my $stu_fullname = $env{'form.fullname'};
 2144:         if ($stu_fullname eq '') {
 2145:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2146:         }
 2147:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2148:         if ($forwhom ne '') {
 2149:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2150:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2151:         }
 2152:     }
 2153:     $rendered=
 2154:         '<div class="LC_Box">'
 2155:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2156:        .$rendered
 2157:        .'</div>';
 2158:     $companswer=
 2159:         '<div class="LC_Box">'
 2160:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2161:        .$companswer
 2162:        .'</div>';
 2163:     my $result;
 2164:     if ($mode eq 'both') {
 2165:         $result=$rendered.$companswer;
 2166:     } elsif ($mode eq 'text') {
 2167:         $result=$rendered;
 2168:     } elsif ($mode eq 'answer') {
 2169:         $result=$companswer;
 2170:     }
 2171:     return $result;
 2172: }
 2173: 
 2174: sub files_exist {
 2175:     my ($r, $symb) = @_;
 2176:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2177:     foreach my $student (@students) {
 2178:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2179:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2180: 					      $udom,$uname);
 2181:         my ($string)= &get_last_submission(\%record);
 2182:         foreach my $submission (@$string) {
 2183:             my ($partid,$respid) =
 2184: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2185:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2186: 					   \%record);
 2187:             return 1 if (@$files);
 2188:         }
 2189:     }
 2190:     return 0;
 2191: }
 2192: 
 2193: sub download_all_link {
 2194:     my ($r,$symb) = @_;
 2195:     unless (&files_exist($r, $symb)) {
 2196:         $r->print(&mt('There are currently no submitted documents.'));
 2197:         return;
 2198:     }
 2199:     my $all_students = 
 2200: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2201: 
 2202:     my $parts =
 2203: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2204: 
 2205:     my $identifier = &Apache::loncommon::get_cgi_id();
 2206:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2207:                              'cgi.'.$identifier.'.symb' => $symb,
 2208:                              'cgi.'.$identifier.'.parts' => $parts,});
 2209:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2210: 	      &mt('Download All Submitted Documents').'</a>');
 2211:     return;
 2212: }
 2213: 
 2214: sub submit_download_link {
 2215:     my ($request,$symb) = @_;
 2216:     if (!$symb) { return ''; }
 2217:     my $res_error;
 2218:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2219:         &response_type($symb,\$res_error);
 2220:     if ($res_error) {
 2221:         $request->print(&mt('An error occurred retrieving response types'));
 2222:         return;
 2223:     }
 2224:     unless ($numessay) {
 2225:         $request->print(&mt('No essayresponse items found'));
 2226:         return;
 2227:     }
 2228:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2229:     if (@chosenparts) {
 2230:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2231:                                           undef,undef,1));
 2232:     }
 2233:     if ($numessay) {
 2234:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2235:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2236:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2237:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2238:         if (ref($fullname) eq 'HASH') {
 2239:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2240:             if (@students) {
 2241:                 @{$env{'form.stuinfo'}} = @students;
 2242:                 if ($numdropbox) {
 2243:                     &download_all_link($request,$symb);
 2244:                 } else {
 2245:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2246:                 }
 2247: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2248: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2249:             } else {
 2250:                 $request->print(&mt('No students match the criteria you selected'));
 2251:             }
 2252:         } else {
 2253:             $request->print(&mt('Could not retrieve student information'));
 2254:         }
 2255:     } else {
 2256:         $request->print(&mt('No essayresponse items found'));
 2257:     }
 2258:     return;
 2259: }
 2260: 
 2261: sub build_section_inputs {
 2262:     my $section_inputs;
 2263:     if ($env{'form.section'} eq '') {
 2264:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2265:     } else {
 2266:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2267:         foreach my $section (@sections) {
 2268:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2269:         }
 2270:     }
 2271:     return $section_inputs;
 2272: }
 2273: 
 2274: # --------------------------- show submissions of a student, option to grade 
 2275: sub submission {
 2276:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2277:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2278:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2279:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2280:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2281: 
 2282:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2283:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2284:     my ($essayurl,%coursedesc_by_cid);
 2285: 
 2286:     if (!&canview($usec)) {
 2287:         $request->print(
 2288:             '<span class="LC_warning">'.
 2289:             &mt('Unable to view requested student.').
 2290:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2291:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2292:             '</span>');
 2293: 	return;
 2294:     }
 2295: 
 2296:     my $res_error;
 2297:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2298:         &response_type($symb,\$res_error);
 2299:     if ($res_error) {
 2300:         $request->print(&navmap_errormsg());
 2301:         return;
 2302:     }
 2303: 
 2304:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2305:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2306:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2307:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2308:         $env{'form.compmsg'} = 1;
 2309:     }
 2310:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2311:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2312: 	'" src="'.$request->dir_config('lonIconsURL').
 2313: 	'/check.gif" height="16" border="0" />';
 2314: 
 2315:     # header info
 2316:     if ($counter == 0) {
 2317:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2318:         if (@chosenparts) {
 2319:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2320:         } elsif ($divforres) {
 2321:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2322:         } else {
 2323:             $request->print('<br clear="all" />');
 2324:         }
 2325: 	&sub_page_js($request);
 2326:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2327: 	&sub_page_kw_js($request) if ($numessay);
 2328: 
 2329: 	# option to display problem, only once else it cause problems 
 2330:         # with the form later since the problem has a form.
 2331: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2332: 	    my $mode;
 2333: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2334: 		$mode='both';
 2335: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2336: 		$mode='text';
 2337: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2338: 		$mode='answer';
 2339: 	    }
 2340: 	    &Apache::lonxml::clear_problem_counter();
 2341: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2342: 	}
 2343: 
 2344: 	my %keyhash = ();
 2345: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2346: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2347: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2348: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2349: 	}
 2350: 	# kwclr is the only variable that is guaranteed not to be blank
 2351: 	# if this subroutine has been called once.
 2352: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2353: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2354: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2355: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2356: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2357: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2358: 	}
 2359: 	if ($env{'form.compmsg'}) {
 2360: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2361: 		$keyhash{$symb.'_subject'} : $probtitle;
 2362: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2363: 	}
 2364: 
 2365: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2366: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2367: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2368: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2369: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2370: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2371: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2372: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2373: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2374: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2375: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2376: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2377: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2378: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2379: 			&build_section_inputs().
 2380: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2381: 			'<input type="hidden" name="NCT"'.
 2382: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2383: 	if ($env{'form.compmsg'}) {
 2384: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2385: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2386: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2387: 	}
 2388: 	if ($numessay) {
 2389: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2390: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2391: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2392: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2393: 	}
 2394: 
 2395: 	my ($cts,$prnmsg) = (1,'');
 2396: 	while ($cts <= $env{'form.savemsgN'}) {
 2397: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2398: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2399: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2400: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2401: 		'" />'."\n".
 2402: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2403: 	    $cts++;
 2404: 	}
 2405: 	$request->print($prnmsg);
 2406: 
 2407: 	if ($numessay) {
 2408: 
 2409:             my %lt = &Apache::lonlocal::texthash(
 2410:                           keyh => 'Keyword Highlighting for Essays',
 2411:                           keyw => 'Keyword Options',
 2412:                           list => 'List',
 2413:                           past => 'Paste Selection to List',
 2414:                           high => 'Highlight Attribute',
 2415:                      );
 2416: #
 2417: # Print out the keyword options line
 2418: #
 2419: 	    $request->print(
 2420:                 '<div class="LC_columnSection">'
 2421:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2422:                .&Apache::lonhtmlcommon::funclist_from_array(
 2423:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2424:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2425:  class="page">'.$lt{'past'}.'</a>',
 2426:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2427:                     {legend => $lt{'keyw'}})
 2428:                .'</fieldset></div>'
 2429:             );
 2430: 
 2431: #
 2432: # Load the other essays for similarity check
 2433: #
 2434:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2435:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2436:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2437:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2438:                 if ($cdom ne '' && $cnum ne '') {
 2439:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2440:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2441:                         my $apath = $1.'_'.$id;
 2442:                         $apath=~s/\W/\_/gs;
 2443:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2444:                     }
 2445:                 }
 2446:             } else {
 2447: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2448: 	        $apath=&escape($apath);
 2449: 	        $apath=~s/\W/\_/gs;
 2450:                 &init_old_essays($symb,$apath,$adom,$aname);
 2451:             }
 2452:         }
 2453:     }
 2454: 
 2455: # This is where output for one specific student would start
 2456:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2457:     $request->print(
 2458:         "\n\n"
 2459:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2460:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2461:        ."\n"
 2462:     );
 2463: 
 2464:     # Show additional functions if allowed
 2465:     if ($perm{'vgr'}) {
 2466:         $request->print(
 2467:             &Apache::loncommon::track_student_link(
 2468:                 'View recent activity',
 2469:                 $uname,$udom,'check')
 2470:            .' '
 2471:         );
 2472:     }
 2473:     if ($perm{'opa'}) {
 2474:         $request->print(
 2475:             &Apache::loncommon::pprmlink(
 2476:                 &mt('Set/Change parameters'),
 2477:                 $uname,$udom,$symb,'check'));
 2478:     }
 2479: 
 2480:     # Show Problem
 2481:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2482: 	my $mode;
 2483: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2484: 	    $mode='both';
 2485: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2486: 	    $mode='text';
 2487: 	} elsif ($env{'form.vAns'} eq 'all') {
 2488: 	    $mode='answer';
 2489: 	}
 2490: 	&Apache::lonxml::clear_problem_counter();
 2491: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2492:     }
 2493: 
 2494:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2495: 
 2496:     # Display student info
 2497:     $request->print(($counter == 0 ? '' : '<br />'));
 2498: 
 2499:     my $result='<div class="LC_Box">'
 2500:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2501:     $result.='<input type="hidden" name="name'.$counter.
 2502:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2503:     if ($numresp > $numessay) {
 2504:         $result.='<p class="LC_info">'
 2505:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2506:                 ."</p>\n";
 2507:     }
 2508: 
 2509:     # If any part of the problem is an essayresponse, then check for collaborators
 2510:     my $fullname;
 2511:     my $col_fullnames = [];
 2512:     if ($numessay) {
 2513: 	(my $sub_result,$fullname,$col_fullnames)=
 2514: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2515: 				 $counter);
 2516: 	$result.=$sub_result;
 2517:     }
 2518:     $request->print($result."\n");
 2519: 
 2520:     # print student answer/submission
 2521:     # Options are (1) Last submission only
 2522:     #             (2) Last submission (with detailed information for that submission)
 2523:     #             (3) All transactions (by date)
 2524:     #             (4) The whole record (with detailed information for all transactions)
 2525: 
 2526:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) = &get_last_submission(\%record);
 2527: 
 2528:     my $lastsubonly;
 2529: 
 2530:     if ($timestamp eq '') {
 2531:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>'; 
 2532:     } else {
 2533:         my ($shownsubmdate,$showngradedate);
 2534:         if ($lastsubmittime && $lastgradetime) {
 2535:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
 2536:             if ($lastgradetime > $lastsubmittime) {
 2537:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
 2538:              }
 2539:         } else {
 2540:             $shownsubmdate = $timestamp;
 2541:         }
 2542:         $lastsubonly =
 2543:             '<div class="LC_grade_submissions_body">'
 2544:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
 2545:         if ($showngradedate) {
 2546:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
 2547:         }
 2548: 
 2549: 	my %seenparts;
 2550: 	my @part_response_id = &flatten_responseType($responseType);
 2551: 	foreach my $part (@part_response_id) {
 2552: 	    my ($partid,$respid) = @{ $part };
 2553: 	    my $display_part=&get_display_part($partid,$symb);
 2554: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2555: 		if (exists($seenparts{$partid})) { next; }
 2556: 		$seenparts{$partid}=1;
 2557:                 $request->print(
 2558:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2559:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2560:                                '<a href="javascript:viewSubmitter(\''.
 2561:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2562:                                '\');" target="_self">'.
 2563:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2564:                     '<br />');
 2565: 		next;
 2566: 	    }
 2567: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2568: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2569:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2570:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2571:                     ' <span class="LC_internal_info">'.
 2572:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2573:                     '</span>&nbsp; &nbsp;'.
 2574: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2575: 		next;
 2576: 	    }
 2577: 	    foreach my $submission (@$string) {
 2578: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2579: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2580: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2581: 		# Similarity check
 2582:                 my $similar='';
 2583:                 my ($type,$trial,$rndseed);
 2584:                 if ($hide eq 'rand') {
 2585:                     $type = 'randomizetry';
 2586:                     $trial = $record{"resource.$partid.tries"};
 2587:                     $rndseed = $record{"resource.$partid.rndseed"};
 2588:                 }
 2589: 		if ($env{'form.checkPlag'}) {
 2590: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2591: 		        &most_similar($uname,$udom,$symb,$subval);
 2592: 		    if ($osim) {
 2593: 		        $osim=int($osim*100.0);
 2594:                         if ($hide eq 'anon') {
 2595:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2596:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2597:                         } else {
 2598: 			    $similar='<hr />';
 2599:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2600:                                 $similar .= '<h3><span class="LC_warning">'.
 2601:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2602:                                                 $osim,
 2603:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2604:                                             '</span></h3>';
 2605:                             } elsif ($ocrsid ne '') {
 2606:                                 my %old_course_desc;
 2607:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2608:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2609:                                 } else {
 2610:                                     my $args;
 2611:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2612:                                         $args = {'one_time' => 1};
 2613:                                     }
 2614:                                     %old_course_desc =
 2615:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2616:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2617:                                 }
 2618:                                 $similar .=
 2619:                                     '<h3><span class="LC_warning">'.
 2620: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2621: 				        $osim,
 2622: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2623: 				        $old_course_desc{'description'},
 2624: 				        $old_course_desc{'num'},
 2625: 				        $old_course_desc{'domain'}).
 2626: 				    '</span></h3>';
 2627:                             } else {
 2628:                                 $similar .=
 2629:                                     '<h3><span class="LC_warning">'.
 2630:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2631:                                         $osim,
 2632:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2633:                                     '</span></h3>';
 2634:                             }
 2635:                             $similar .= '<blockquote><i>'.
 2636:                                         &keywords_highlight($oessay).
 2637:                                         '</i></blockquote><hr />';
 2638: 		        }
 2639:                     }
 2640:                 }
 2641: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2642:                                      undef,$type,$trial,$rndseed);
 2643:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2644:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2645:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2646: 		    my $display_part=&get_display_part($partid,$symb);
 2647:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2648:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2649:                         ' <span class="LC_internal_info">'.
 2650:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2651:                         '</span>&nbsp; &nbsp;';
 2652: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2653: 		    if (@$files) {
 2654:                         if ($hide eq 'anon') {
 2655:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2656:                         } else {
 2657:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2658:                                          .'<br /><span class="LC_warning">';
 2659:                             if(@$files == 1) {
 2660:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2661:                             } else {
 2662:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2663:                             }
 2664:                             $lastsubonly .= '</span>';
 2665:                             foreach my $file (@$files) {
 2666:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2667:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2668:                             }
 2669:                         }
 2670: 			$lastsubonly.='<br />';
 2671: 		    }
 2672:                     if ($hide eq 'anon') {
 2673:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2674:                     } else {
 2675:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2676:                         if ($draft) {
 2677:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2678:                         }
 2679:                         $subval =
 2680: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2681: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2682:                         if ($responsetype eq 'essay') {
 2683:                             $subval =~ s{\n}{<br />}g;
 2684:                         }
 2685:                         $lastsubonly.=$subval."\n";
 2686:                     }
 2687:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2688: 		    $lastsubonly.='</div>';
 2689: 		}
 2690: 	    }
 2691: 	}
 2692: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2693:     }
 2694:     $request->print($lastsubonly);
 2695:     if ($env{'form.lastSub'} eq 'datesub') {
 2696:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2697: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2698:     }
 2699:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2700:         my $identifier = (&canmodify($usec)? $counter : '');
 2701: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2702: 								 $env{'request.course.id'},
 2703: 								 $last,'.submission',
 2704: 								 'Apache::grades::keywords_highlight',
 2705:                                                                  $usec,$identifier));
 2706:     }
 2707:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2708: 	.$udom.'" />'."\n");
 2709:     # return if view submission with no grading option
 2710:     if (!&canmodify($usec)) {
 2711:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2712:         return;
 2713:     } else {
 2714: 	$request->print('</div>'."\n");
 2715:     }
 2716: 
 2717:     # grading message center
 2718: 
 2719:     if ($env{'form.compmsg'}) {
 2720:         my $result='<div class="LC_Box">'.
 2721:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2722:                    '<div class="LC_grade_message_center_body">';
 2723:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2724:         my $msgfor = $givenn.' '.$lastname;
 2725:         if (scalar(@$col_fullnames) > 0) {
 2726:             my $lastone = pop(@$col_fullnames);
 2727:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2728:         }
 2729:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2730:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2731:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2732: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2733:                  ',\''.$msgfor.'\');" target="_self">'.
 2734:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2735:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2736:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2737:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2738:                  '<br />&nbsp;('.
 2739:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2740: 	         '</div></div>';
 2741:         $request->print($result);
 2742:     }
 2743: 
 2744:     my %seen = ();
 2745:     my @partlist;
 2746:     my @gradePartRespid;
 2747:     my @part_response_id = &flatten_responseType($responseType);
 2748:     $request->print(
 2749:         '<div class="LC_Box">'
 2750:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2751:     );
 2752:     $request->print(&gradeBox_start());
 2753:     foreach my $part_response_id (@part_response_id) {
 2754:     	my ($partid,$respid) = @{ $part_response_id };
 2755: 	my $part_resp = join('_',@{ $part_response_id });
 2756: 	next if ($seen{$partid} > 0);
 2757: 	$seen{$partid}++;
 2758: 	push(@partlist,$partid);
 2759: 	push(@gradePartRespid,$partid.'.'.$respid);
 2760: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2761:     }
 2762:     $request->print(&gradeBox_end()); # </div>
 2763:     $request->print('</div>');
 2764: 
 2765:     $request->print('<div class="LC_grade_info_links">');
 2766:     $request->print('</div>');
 2767: 
 2768:     $result='<input type="hidden" name="partlist'.$counter.
 2769: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2770:     $result.='<input type="hidden" name="gradePartRespid'.
 2771: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2772:     my $ctr = 0;
 2773:     while ($ctr < scalar(@partlist)) {
 2774: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2775: 	    $partlist[$ctr].'" />'."\n";
 2776: 	$ctr++;
 2777:     }
 2778:     $request->print($result.''."\n");
 2779: 
 2780: # Done with printing info for one student
 2781: 
 2782:     $request->print('</div>');#LC_grade_show_user
 2783: 
 2784: 
 2785:     # print end of form
 2786:     if ($counter == $total) {
 2787:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2788: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2789: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2790: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2791: 	my $ntstu ='<select name="NTSTU">'.
 2792: 	    '<option>1</option><option>2</option>'.
 2793: 	    '<option>3</option><option>5</option>'.
 2794: 	    '<option>7</option><option>10</option></select>'."\n";
 2795: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2796: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2797:         $endform.=&mt('[_1]student(s)',$ntstu);
 2798: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2799: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2800: 	    '<input type="button" value="'.&mt('Next').'" '.
 2801: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2802:         $endform.='<span class="LC_warning">'.
 2803:                   &mt('(Next and Previous (student) do not save the scores.)').
 2804:                   '</span>'."\n" ;
 2805:         $endform.="<input type='hidden' value='".&get_increment().
 2806:             "' name='increment' />";
 2807: 	$endform.='</td></tr></table></form>';
 2808: 	$request->print($endform);
 2809:     }
 2810:     return '';
 2811: }
 2812: 
 2813: sub check_collaborators {
 2814:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2815:     my ($result,@col_fullnames);
 2816:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2817:     foreach my $part (keys(%$handgrade)) {
 2818: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2819: 					'.maxcollaborators',
 2820: 					$symb,$udom,$uname);
 2821: 	next if ($ncol <= 0);
 2822: 	$part =~ s/\_/\./g;
 2823: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2824: 	my (@good_collaborators, @bad_collaborators);
 2825: 	foreach my $possible_collaborator
 2826: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2827: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2828: 	    next if ($possible_collaborator eq '');
 2829: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2830: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2831: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2832: 	    # Doing this grep allows 'fuzzy' specification
 2833: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2834: 			       keys(%$classlist));
 2835: 	    if (! scalar(@matches)) {
 2836: 		push(@bad_collaborators, $possible_collaborator);
 2837: 	    } else {
 2838: 		push(@good_collaborators, @matches);
 2839: 	    }
 2840: 	}
 2841: 	if (scalar(@good_collaborators) != 0) {
 2842: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2843: 	    foreach my $name (@good_collaborators) {
 2844: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2845: 		push(@col_fullnames, $givenn.' '.$lastname);
 2846: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2847: 	    }
 2848: 	    $result.='</ol><br />'."\n";
 2849: 	    my ($part)=split(/\./,$part);
 2850: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2851: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2852: 		"\n";
 2853: 	}
 2854: 	if (scalar(@bad_collaborators) > 0) {
 2855: 	    $result.='<div class="LC_warning">';
 2856: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2857: 	    $result .= '</div>';
 2858: 	}         
 2859: 	if (scalar(@bad_collaborators > $ncol)) {
 2860: 	    $result .= '<div class="LC_warning">';
 2861: 	    $result .= &mt('This student has submitted too many '.
 2862: 		'collaborators.  Maximum is [_1].',$ncol);
 2863: 	    $result .= '</div>';
 2864: 	}
 2865:     }
 2866:     return ($result,$fullname,\@col_fullnames);
 2867: }
 2868: 
 2869: #--- Retrieve the last submission for all the parts
 2870: sub get_last_submission {
 2871:     my ($returnhash)=@_;
 2872:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
 2873:     if ($$returnhash{'version'}) {
 2874: 	my %lasthash=();
 2875:         my %prevsolved=();
 2876:         my %solved=();
 2877: 	my $version;
 2878: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2879:             my %handgraded = ();
 2880: 	    foreach my $key (sort(split(/\:/,
 2881: 					$$returnhash{$version.':keys'}))) {
 2882: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2883:                 if ($key =~ /\.([^.]+)\.regrader$/) {
 2884:                     $handgraded{$1} = 1;
 2885:                 } elsif ($key =~ /\.portfiles$/) {
 2886:                     if (($$returnhash{$version.':'.$key} ne '') &&
 2887:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
 2888:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2889:                     }
 2890:                 } elsif ($key =~ /\.submission$/) {
 2891:                     if ($$returnhash{$version.':'.$key} ne '') {
 2892:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2893:                     }
 2894:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
 2895:                     $prevsolved{$1} = $solved{$1};
 2896:                     $solved{$1} = $lasthash{$key};
 2897:                 }
 2898:             foreach my $partid (keys(%handgraded)) {
 2899:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
 2900:                     (($solved{$partid} eq 'incorrect_by_override') ||
 2901:                      ($solved{$partid} eq 'correct_by_override'))) {
 2902:                     $lastgradetime = $$returnhash{$version.':timestamp'};
 2903:                 }
 2904:                 if ($solved{$partid} ne '') {
 2905:                     $prevsolved{$partid} = $solved{$partid};
 2906:                 }
 2907:             }
 2908: 	    $timestamp = 
 2909: 		&Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2910: 	}
 2911:         my (%typeparts,%randombytry);
 2912:         my $showsurv = 
 2913:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2914:         foreach my $key (sort(keys(%lasthash))) {
 2915:             if ($key =~ /\.type$/) {
 2916:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2917:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2918:                     ($lasthash{$key} eq 'randomizetry')) {
 2919:                     my ($ign,@parts) = split(/\./,$key);
 2920:                     pop(@parts);
 2921:                     my $id = join('.',@parts);
 2922:                     if ($lasthash{$key} eq 'randomizetry') {
 2923:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2924:                     } else {
 2925:                         unless ($showsurv) {
 2926:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2927:                         }
 2928:                     }
 2929:                     delete($lasthash{$key});
 2930:                 }
 2931:             }
 2932:         }
 2933:         my @hidden = keys(%typeparts);
 2934:         my @randomize = keys(%randombytry);
 2935: 	foreach my $key (keys(%lasthash)) {
 2936: 	    next if ($key !~ /\.submission$/);
 2937:             my $hide;
 2938:             if (@hidden) {
 2939:                 foreach my $id (@hidden) {
 2940:                     if ($key =~ /^\Q$id\E/) {
 2941:                         $hide = 'anon';
 2942:                         last;
 2943:                     }
 2944:                 }
 2945:             }
 2946:             unless ($hide) {
 2947:                 if (@randomize) {
 2948:                     foreach my $id (@randomize) {
 2949:                         if ($key =~ /^\Q$id\E/) {
 2950:                             $hide = 'rand';
 2951:                             last;
 2952:                         }
 2953:                     }
 2954:                 }
 2955:             }
 2956: 	    my ($partid,$foo) = split(/submission$/,$key);
 2957: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2958:             push(@string, join(':', $key, $hide, $draft, (
 2959:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2960:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2961: 	}
 2962:     }
 2963:     if (!@string) {
 2964: 	$string[0] =
 2965: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2966:     }
 2967:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
 2968: }
 2969: 
 2970: #--- High light keywords, with style choosen by user.
 2971: sub keywords_highlight {
 2972:     my $string    = shift;
 2973:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2974:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2975:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2976:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2977:     foreach my $keyword (@keylist) {
 2978: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2979:     }
 2980:     return $string;
 2981: }
 2982: 
 2983: # For Tasks provide a mechanism to display previous version for one specific student
 2984: 
 2985: sub show_previous_task_version {
 2986:     my ($request,$symb) = @_;
 2987:     if ($symb eq '') {
 2988:         $request->print(
 2989:             '<span class="LC_error">'.
 2990:             &mt('Unable to handle ambiguous references.').
 2991:             '</span>');
 2992:         return '';
 2993:     }
 2994:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2995:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2996:     if (!&canview($usec)) {
 2997:         $request->print('<span class="LC_warning">'.
 2998:                         &mt('Unable to view previous version for requested student.').
 2999:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 3000:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3001:                         '</span>');
 3002:         return;
 3003:     }
 3004:     my $mode = 'both';
 3005:     my $isTask = ($symb =~/\.task$/);
 3006:     if ($isTask) {
 3007:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3008:             if ($env{'form.fullname'} eq '') {
 3009:                 $env{'form.fullname'} =
 3010:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3011:             }
 3012:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3013:             $request->print("\n\n".
 3014:                             '<div class="LC_grade_show_user">'.
 3015:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3016:                             '</h2>'."\n");
 3017:             &Apache::lonxml::clear_problem_counter();
 3018:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3019:                             {'previousversion' => $env{'form.previousversion'} }));
 3020:             $request->print("\n</div>");
 3021:         }
 3022:     }
 3023:     return;
 3024: }
 3025: 
 3026: sub choose_task_version_form {
 3027:     my ($symb,$uname,$udom,$nomenu) = @_;
 3028:     my $isTask = ($symb =~/\.task$/);
 3029:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3030:     if ($isTask) {
 3031:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3032:                                               $udom,$uname);
 3033:         if (($record{'resource.0.version'} eq '') ||
 3034:             ($record{'resource.0.version'} < 2)) {
 3035:             return ($record{'resource.0.version'},
 3036:                     $record{'resource.0.version'},$result,$js);
 3037:         } else {
 3038:             $current = $record{'resource.0.version'};
 3039:         }
 3040:         if ($env{'form.previousversion'}) {
 3041:             $displayed = $env{'form.previousversion'};
 3042:             $rowtitle = &mt('Choose another version:')
 3043:         } else {
 3044:             $displayed = $current;
 3045:             $rowtitle = &mt('Show earlier version:');
 3046:         }
 3047:         $result = '<div class="LC_left_float">';
 3048:         my $list;
 3049:         my $numversions = 0;
 3050:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3051:             if ($i == $current) {
 3052:                 if (!$env{'form.previousversion'} || $nomenu) {
 3053:                     next;
 3054:                 } else {
 3055:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3056:                     $numversions ++;
 3057:                 }
 3058:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3059:                 unless ($i == $env{'form.previousversion'}) {
 3060:                     $numversions ++;
 3061:                 }
 3062:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3063:             }
 3064:         }
 3065:         if ($numversions) {
 3066:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3067:             $result .=
 3068:                 '<form name="getprev" method="post" action=""'.
 3069:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3070:                 &Apache::loncommon::start_data_table().
 3071:                 &Apache::loncommon::start_data_table_row().
 3072:                 '<th align="left">'.$rowtitle.'</th>'.
 3073:                 '<td><select name="version">'.
 3074:                 '<option>'.&mt('Select').'</option>'.
 3075:                 $list.
 3076:                 '</select></td>'.
 3077:                 &Apache::loncommon::end_data_table_row();
 3078:             unless ($nomenu) {
 3079:                 $result .= &Apache::loncommon::start_data_table_row().
 3080:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3081:                 '<td><span class="LC_nobreak">'.
 3082:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3083:                 &mt('Yes').'</label>'.
 3084:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3085:                 '</span></td>'.
 3086:                 &Apache::loncommon::end_data_table_row();
 3087:             }
 3088:             $result .=
 3089:                 &Apache::loncommon::start_data_table_row().
 3090:                 '<th align="left">&nbsp;</th>'.
 3091:                 '<td>'.
 3092:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3093:                 '</td>'.
 3094:                 &Apache::loncommon::end_data_table_row().
 3095:                 &Apache::loncommon::end_data_table().
 3096:                 '</form>';
 3097:             $js = &previous_display_javascript($nomenu,$current);
 3098:         } elsif ($displayed && $nomenu) {
 3099:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3100:         } else {
 3101:             $result .= &mt('No previous versions to show for this student');
 3102:         }
 3103:         $result .= '</div>';
 3104:     }
 3105:     return ($current,$displayed,$result,$js);
 3106: }
 3107: 
 3108: sub previous_display_javascript {
 3109:     my ($nomenu,$current) = @_;
 3110:     my $js = <<"JSONE";
 3111: <script type="text/javascript">
 3112: // <![CDATA[
 3113: function previousVersion(uname,udom,symb) {
 3114:     var current = '$current';
 3115:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3116:     var prevstr = new RegExp("^\\\\d+\$");
 3117:     if (!prevstr.test(version)) {
 3118:         return false;
 3119:     }
 3120:     var url = '';
 3121:     if (version == current) {
 3122:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3123:     } else {
 3124:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3125:     }
 3126: JSONE
 3127:     if ($nomenu) {
 3128:         $js .= <<"JSTWO";
 3129:     document.location.href = url;
 3130: JSTWO
 3131:     } else {
 3132:         $js .= <<"JSTHREE";
 3133:     var newwin = 0;
 3134:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3135:         if (document.getprev.prevwin[i].checked == true) {
 3136:             newwin = document.getprev.prevwin[i].value;
 3137:         }
 3138:     }
 3139:     if (newwin == 1) {
 3140:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3141:         url = url+'&inhibitmenu=yes';
 3142:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3143:             previousWin = window.open(url,'',options,1);
 3144:         } else {
 3145:             previousWin.location.href = url;
 3146:         }
 3147:         previousWin.focus();
 3148:         return false;
 3149:     } else {
 3150:         document.location.href = url;
 3151:         return false;
 3152:     }
 3153: JSTHREE
 3154:     }
 3155:     $js .= <<"ENDJS";
 3156:     return false;
 3157: }
 3158: // ]]>
 3159: </script>
 3160: ENDJS
 3161: 
 3162: }
 3163: 
 3164: #--- Called from submission routine
 3165: sub processHandGrade {
 3166:     my ($request,$symb) = @_;
 3167:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3168:     my $button = $env{'form.gradeOpt'};
 3169:     my $ngrade = $env{'form.NCT'};
 3170:     my $ntstu  = $env{'form.NTSTU'};
 3171:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3172:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3173:     my ($res_error,%queueable);
 3174:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3175:     if ($res_error) {
 3176:         $request->print(&navmap_errormsg());
 3177:         return;
 3178:     } else {
 3179:         foreach my $part (@{$partlist}) {
 3180:             if (ref($responseType->{$part}) eq 'HASH') {
 3181:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3182:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3183:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3184:                         $queueable{$part} = 1;
 3185:                         last;
 3186:                     }
 3187:                 }
 3188:             }
 3189:         }
 3190:     }
 3191: 
 3192:     if ($button eq 'Save & Next') {
 3193: 	my $ctr = 0;
 3194: 	while ($ctr < $ngrade) {
 3195: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3196: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3197:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3198: 	    if ($errorflag eq 'no_score') {
 3199: 		$ctr++;
 3200: 		next;
 3201: 	    }
 3202: 	    if ($errorflag eq 'not_allowed') {
 3203:                 $request->print(
 3204:                     '<span class="LC_error">'
 3205:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3206:                    .'</span>');
 3207: 		$ctr++;
 3208: 		next;
 3209: 	    }
 3210:             if ($numhidden) {
 3211:                 $request->print(
 3212:                     '<span class="LC_info">'
 3213:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3214:                    .'</span><br />');
 3215:             }
 3216: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3217: 	    my ($subject,$message,$msgstatus) = ('','','');
 3218: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3219:             my ($feedurl,$showsymb) =
 3220: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3221: 	    my $messagetail;
 3222: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3223: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3224: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3225: 		$subject.=' ['.$restitle.']';
 3226: 		my (@msgnum) = split(/,/,$includemsg);
 3227: 		foreach (@msgnum) {
 3228: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3229: 		}
 3230: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3231: 		if ($env{'form.withgrades'.$ctr}) {
 3232: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3233: 		    $messagetail = " for <a href=\"".
 3234: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3235: 		}
 3236: 		$msgstatus = 
 3237:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3238: 						     $message.$messagetail,
 3239:                                                      undef,$feedurl,undef,
 3240:                                                      undef,undef,$showsymb,
 3241:                                                      $restitle);
 3242: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3243: 				$msgstatus.'<br />');
 3244: 	    }
 3245: 	    if ($env{'form.collaborator'.$ctr}) {
 3246: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3247: 		foreach my $collabstr (@collabstrs) {
 3248: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3249: 		    foreach my $collaborator (@collaborators) {
 3250: 			my ($errorflag,$pts,$wgt) = 
 3251: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3252: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3253: 			if ($errorflag eq 'not_allowed') {
 3254: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3255: 			    next;
 3256: 			} elsif ($message ne '') {
 3257: 			    my ($baseurl,$showsymb) = 
 3258: 				&get_feedurl_and_symb($symb,$collaborator,
 3259: 						      $udom);
 3260: 			    if ($env{'form.withgrades'.$ctr}) {
 3261: 				$messagetail = " for <a href=\"".
 3262:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3263: 			    }
 3264: 			    $msgstatus = 
 3265: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3266: 			}
 3267: 		    }
 3268: 		}
 3269: 	    }
 3270: 	    $ctr++;
 3271: 	}
 3272:     }
 3273: 
 3274:     my %keyhash = ();
 3275:     if ($numessay) {
 3276: 	# Keywords sorted in alphabatical order
 3277: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3278: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3279: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3280: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3281: 	$env{'form.keywords'} = join(' ',@keywords);
 3282: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3283: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3284: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3285: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3286: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3287:     }
 3288: 
 3289:     if ($env{'form.compmsg'}) {
 3290: 	# message center - Order of message gets changed. Blank line is eliminated.
 3291: 	# New messages are saved in env for the next student.
 3292: 	# All messages are saved in nohist_handgrade.db
 3293: 	my ($ctr,$idx) = (1,1);
 3294: 	while ($ctr <= $env{'form.savemsgN'}) {
 3295: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3296: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3297: 		$idx++;
 3298: 	    }
 3299: 	    $ctr++;
 3300: 	}
 3301: 	$ctr = 0;
 3302: 	while ($ctr < $ngrade) {
 3303: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3304: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3305: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3306: 		$idx++;
 3307: 	    }
 3308: 	    $ctr++;
 3309: 	}
 3310: 	$env{'form.savemsgN'} = --$idx;
 3311: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3312:     }
 3313:     if (($numessay) || ($env{'form.compmsg'})) {
 3314: 	my $putresult = &Apache::lonnet::put
 3315: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3316:     }
 3317: 
 3318:     # Called by Save & Refresh from Highlight Attribute Window
 3319:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3320:     if ($env{'form.refresh'} eq 'on') {
 3321: 	my ($ctr,$total) = (0,0);
 3322: 	while ($ctr < $ngrade) {
 3323: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3324: 	    $ctr++;
 3325: 	}
 3326: 	$env{'form.NTSTU'}=$ngrade;
 3327: 	$ctr = 0;
 3328: 	while ($ctr < $total) {
 3329: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3330: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3331: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3332: 	    &submission($request,$ctr,$total-1,$symb);
 3333: 	    $ctr++;
 3334: 	}
 3335: 	return '';
 3336:     }
 3337: 
 3338:     # Get the next/previous one or group of students
 3339:     my $firststu = $env{'form.unamedom0'};
 3340:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3341:     my $ctr = 2;
 3342:     while ($laststu eq '') {
 3343: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3344: 	$ctr++;
 3345: 	$laststu = $firststu if ($ctr > $ngrade);
 3346:     }
 3347: 
 3348:     my (@parsedlist,@nextlist);
 3349:     my ($nextflg) = 0;
 3350:     foreach my $item (sort 
 3351: 	     {
 3352: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3353: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3354: 		 }
 3355: 		 return $a cmp $b;
 3356: 	     } (keys(%$fullname))) {
 3357: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3358: 	    push(@parsedlist,$item);
 3359: 	}
 3360: 	$nextflg = 1 if ($item eq $laststu);
 3361: 	if ($button eq 'Previous') {
 3362: 	    last if ($item eq $firststu);
 3363: 	    push(@parsedlist,$item);
 3364: 	}
 3365:     }
 3366:     $ctr = 0;
 3367:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3368:     foreach my $student (@parsedlist) {
 3369: 	my $submitonly=$env{'form.submitonly'};
 3370: 	my ($uname,$udom) = split(/:/,$student);
 3371: 	
 3372: 	if ($submitonly eq 'queued') {
 3373: 	    my %queue_status = 
 3374: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3375: 							$udom,$uname);
 3376: 	    next if (!defined($queue_status{'gradingqueue'}));
 3377: 	}
 3378: 
 3379: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3380: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3381: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3382: 	    my $submitted = 0;
 3383: 	    my $ungraded = 0;
 3384: 	    my $incorrect = 0;
 3385: 	    foreach my $item (keys(%status)) {
 3386: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3387: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3388: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3389: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3390: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3391: 		    $submitted = 0;
 3392: 		}
 3393: 	    }
 3394: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3395: 				     $submitonly eq 'incorrect' ||
 3396: 				     $submitonly eq 'graded'));
 3397: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3398: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3399: 	}
 3400: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3401: 	last if ($ctr == $ntstu);
 3402: 	$ctr++;
 3403:     }
 3404: 
 3405:     $ctr = 0;
 3406:     my $total = scalar(@nextlist)-1;
 3407: 
 3408:     foreach (sort(@nextlist)) {
 3409: 	my ($uname,$udom,$submitter) = split(/:/);
 3410: 	$env{'form.student'}  = $uname;
 3411: 	$env{'form.userdom'}  = $udom;
 3412: 	$env{'form.fullname'} = $$fullname{$_};
 3413: 	&submission($request,$ctr,$total,$symb);
 3414: 	$ctr++;
 3415:     }
 3416:     if ($total < 0) {
 3417:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3418: 	$request->print($the_end);
 3419:     }
 3420:     return '';
 3421: }
 3422: 
 3423: #---- Save the score and award for each student, if changed
 3424: sub saveHandGrade {
 3425:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3426:     my @version_parts;
 3427:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3428: 					   $env{'request.course.id'});
 3429:     if (!&canmodify($usec)) { return('not_allowed'); }
 3430:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3431:     my @parts_graded;
 3432:     my %newrecord  = ();
 3433:     my ($pts,$wgt,$totchg) = ('','',0);
 3434:     my %aggregate = ();
 3435:     my $aggregateflag = 0;
 3436:     if ($env{'form.HIDE'.$newflg}) {
 3437:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3438:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3439:         $totchg += $numchgs;
 3440:     }
 3441:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3442:     foreach my $new_part (@parts) {
 3443: 	#collaborator ($submi may vary for different parts
 3444: 	if ($submitter && $new_part ne $part) { next; }
 3445: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3446: 	if ($dropMenu eq 'excused') {
 3447: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3448: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3449: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3450: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3451: 		}
 3452: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3453: 	    }
 3454: 	} elsif ($dropMenu eq 'reset status'
 3455: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3456: 	    foreach my $key (keys(%record)) {
 3457: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3458: 	    }
 3459: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3460: 		"$env{'user.name'}:$env{'user.domain'}";
 3461:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3462: 
 3463:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3464: 					       [$new_part]);
 3465:             my $aggtries =$totaltries;
 3466:             if ($last_resets{$new_part}) {
 3467:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3468: 					   $new_part);
 3469:             }
 3470: 
 3471:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3472:             if ($aggtries > 0) {
 3473:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3474:                 $aggregateflag = 1;
 3475:             }
 3476: 	} elsif ($dropMenu eq '') {
 3477: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3478: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3479: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3480: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3481: 		next;
 3482: 	    }
 3483: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3484: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3485: 	    my $partial= $pts/$wgt;
 3486: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3487: 		#do not update score for part if not changed.
 3488:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3489: 		next;
 3490: 	    } else {
 3491: 	        push(@parts_graded,$new_part);
 3492: 	    }
 3493: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3494: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3495: 	    }
 3496: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3497: 	    if ($partial == 0) {
 3498: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3499: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3500: 		}
 3501: 	    } else {
 3502: 		if ($record{$reckey} ne 'correct_by_override') {
 3503: 		    $newrecord{$reckey} = 'correct_by_override';
 3504: 		}
 3505: 	    }	    
 3506: 	    if ($submitter && 
 3507: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3508: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3509: 	    }
 3510: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3511: 		"$env{'user.name'}:$env{'user.domain'}";
 3512: 	}
 3513: 	# unless problem has been graded, set flag to version the submitted files
 3514: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3515: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3516: 	        $dropMenu eq 'reset status')
 3517: 	   {
 3518: 	    push(@version_parts,$new_part);
 3519: 	}
 3520:     }
 3521:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3522:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3523: 
 3524:     if (%newrecord) {
 3525:         if (@version_parts) {
 3526:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3527:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3528: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3529: 	    foreach my $new_part (@version_parts) {
 3530: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3531: 				$new_part,\%newrecord);
 3532: 	    }
 3533:         }
 3534: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3535: 				$env{'request.course.id'},$domain,$stuname);
 3536: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3537: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3538:     }
 3539:     if ($aggregateflag) {
 3540:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3541: 			      $cdom,$cnum);
 3542:     }
 3543:     return ('',$pts,$wgt,$totchg);
 3544: }
 3545: 
 3546: sub makehidden {
 3547:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3548:     return unless (ref($record) eq 'HASH');
 3549:     my %modified;
 3550:     my $numchanged = 0;
 3551:     if (exists($record->{$version.':keys'})) {
 3552:         my $partsregexp = $parts;
 3553:         $partsregexp =~ s/,/|/g;
 3554:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3555:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3556:                  my $item = $1;
 3557:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3558:                      $modified{$key} = $record->{$version.':'.$key};
 3559:                  }
 3560:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3561:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3562:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3563:                 $modified{$key} = $record->{$version.':'.$key};
 3564:             }
 3565:         }
 3566:         if (keys(%modified)) {
 3567:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3568:                                           $domain,$stuname,$tolog) eq 'ok') {
 3569:                 $numchanged ++;
 3570:             }
 3571:         }
 3572:     }
 3573:     return $numchanged;
 3574: }
 3575: 
 3576: sub check_and_remove_from_queue {
 3577:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3578:     my @ungraded_parts;
 3579:     foreach my $part (@{$parts}) {
 3580: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3581: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3582: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3583: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3584: 		) {
 3585:             if ($queueable->{$part}) {
 3586: 	        push(@ungraded_parts, $part);
 3587:             }
 3588: 	}
 3589:     }
 3590:     if ( !@ungraded_parts ) {
 3591: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3592: 					       $cnum,$domain,$stuname);
 3593:     }
 3594: }
 3595: 
 3596: sub handback_files {
 3597:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3598:     my $portfolio_root = '/userfiles/portfolio';
 3599:     my $res_error;
 3600:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3601:     if ($res_error) {
 3602:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3603:         return;
 3604:     }
 3605:     my @handedback;
 3606:     my $file_msg;
 3607:     my @part_response_id = &flatten_responseType($responseType);
 3608:     foreach my $part_response_id (@part_response_id) {
 3609:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3610: 	my $part_resp = join('_',@{ $part_response_id });
 3611:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3612:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3613:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3614: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3615:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3616:                     my ($directory,$answer_file) = 
 3617:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3618:                     my ($answer_name,$answer_ver,$answer_ext) =
 3619: 		        &file_name_version_ext($answer_file);
 3620: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3621:                     my $getpropath = 1;
 3622:                     my ($dir_list,$listerror) =
 3623:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3624:                                                  $domain,$stuname,$getpropath);
 3625: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3626:                     # fix filename
 3627:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3628:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3629:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3630:             	                                $save_file_name);
 3631:                     if ($result !~ m|^/uploaded/|) {
 3632:                         $request->print('<br /><span class="LC_error">'.
 3633:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3634:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3635:                                         '</span>');
 3636:                     } else {
 3637:                         # mark the file as read only
 3638:                         push(@handedback,$save_file_name);
 3639: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3640: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3641: 			}
 3642:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3643: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3644: 
 3645:                     }
 3646:                     $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>'));
 3647:                 }
 3648:             }
 3649:         }
 3650:     }
 3651:     if (@handedback > 0) {
 3652:         $request->print('<br />');
 3653:         my @what = ($symb,$env{'request.course.id'},'handback');
 3654:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3655:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3656:         my ($subject,$message);
 3657:         if (scalar(@handedback) == 1) {
 3658:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3659:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3660:         } else {
 3661:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3662:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3663:         }
 3664:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3665:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3666:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3667:         my ($feedurl,$showsymb) =
 3668:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3669:         my $restitle = &Apache::lonnet::gettitle($symb);
 3670:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3671:         my $msgstatus =
 3672:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3673:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3674:                  $restitle);
 3675:         if ($msgstatus) {
 3676:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3677:         }
 3678:     }
 3679:     return;
 3680: }
 3681: 
 3682: sub get_feedurl_and_symb {
 3683:     my ($symb,$uname,$udom) = @_;
 3684:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3685:     $url = &Apache::lonnet::clutter($url);
 3686:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3687: 					$symb,$udom,$uname);
 3688:     if ($encrypturl =~ /^yes$/i) {
 3689: 	&Apache::lonenc::encrypted(\$url,1);
 3690: 	&Apache::lonenc::encrypted(\$symb,1);
 3691:     }
 3692:     return ($url,$symb);
 3693: }
 3694: 
 3695: sub get_submitted_files {
 3696:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3697:     my @files;
 3698:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3699:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3700:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3701:     	    push(@files,$file_url.$file);
 3702:         }
 3703:     }
 3704:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3705:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3706:     }
 3707:     return (\@files);
 3708: }
 3709: 
 3710: # ----------- Provides number of tries since last reset.
 3711: sub get_num_tries {
 3712:     my ($record,$last_reset,$part) = @_;
 3713:     my $timestamp = '';
 3714:     my $num_tries = 0;
 3715:     if ($$record{'version'}) {
 3716:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3717:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3718:                 $timestamp = $$record{$version.':timestamp'};
 3719:                 if ($timestamp > $last_reset) {
 3720:                     $num_tries ++;
 3721:                 } else {
 3722:                     last;
 3723:                 }
 3724:             }
 3725:         }
 3726:     }
 3727:     return $num_tries;
 3728: }
 3729: 
 3730: # ----------- Determine decrements required in aggregate totals 
 3731: sub decrement_aggs {
 3732:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3733:     my %decrement = (
 3734:                         attempts => 0,
 3735:                         users => 0,
 3736:                         correct => 0
 3737:                     );
 3738:     $decrement{'attempts'} = $aggtries;
 3739:     if ($solvedstatus =~ /^correct/) {
 3740:         $decrement{'correct'} = 1;
 3741:     }
 3742:     if ($aggtries == $totaltries) {
 3743:         $decrement{'users'} = 1;
 3744:     }
 3745:     foreach my $type (keys(%decrement)) {
 3746:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3747:     }
 3748:     return;
 3749: }
 3750: 
 3751: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3752: sub get_last_resets {
 3753:     my ($symb,$courseid,$partids) =@_;
 3754:     my %last_resets;
 3755:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3756:     my $cname = $env{'course.'.$courseid.'.num'};
 3757:     my @keys;
 3758:     foreach my $part (@{$partids}) {
 3759: 	push(@keys,"$symb\0$part\0resettime");
 3760:     }
 3761:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3762: 				     $cdom,$cname);
 3763:     foreach my $part (@{$partids}) {
 3764: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3765:     }
 3766:     return %last_resets;
 3767: }
 3768: 
 3769: # ----------- Handles creating versions for portfolio files as answers
 3770: sub version_portfiles {
 3771:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3772:     my $version_parts = join('|',@$v_flag);
 3773:     my @returned_keys;
 3774:     my $parts = join('|', @$parts_graded);
 3775:     my $portfolio_root = '/userfiles/portfolio';
 3776:     foreach my $key (keys(%$record)) {
 3777:         my $new_portfiles;
 3778:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3779:             my @versioned_portfiles;
 3780:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3781:             foreach my $file (@portfiles) {
 3782:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3783:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3784: 		my ($answer_name,$answer_ver,$answer_ext) =
 3785: 		    &file_name_version_ext($answer_file);
 3786:                 my $getpropath = 1;
 3787:                 my ($dir_list,$listerror) =
 3788:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3789:                                              $stu_name,$getpropath);
 3790:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3791:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3792:                 if ($new_answer ne 'problem getting file') {
 3793:                     push(@versioned_portfiles, $directory.$new_answer);
 3794:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3795:                         [$directory.$new_answer],
 3796:                         [$symb,$env{'request.course.id'},'graded']);
 3797:                 }
 3798:             }
 3799:             $$record{$key} = join(',',@versioned_portfiles);
 3800:             push(@returned_keys,$key);
 3801:         }
 3802:     } 
 3803:     return (@returned_keys);   
 3804: }
 3805: 
 3806: sub get_next_version {
 3807:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3808:     my $version;
 3809:     if (ref($dir_list) eq 'ARRAY') {
 3810:         foreach my $row (@{$dir_list}) {
 3811:             my ($file) = split(/\&/,$row,2);
 3812:             my ($file_name,$file_version,$file_ext) =
 3813: 	        &file_name_version_ext($file);
 3814:             if (($file_name eq $answer_name) && 
 3815: 	        ($file_ext eq $answer_ext)) {
 3816:                 # gets here if filename and extension match, 
 3817:                 # regardless of version
 3818:                 if ($file_version ne '') {
 3819:                     # a versioned file is found  so save it for later
 3820:                     if ($file_version > $version) {
 3821: 		        $version = $file_version;
 3822:                     }
 3823: 	        }
 3824:             }
 3825:         }
 3826:     }
 3827:     $version ++;
 3828:     return($version);
 3829: }
 3830: 
 3831: sub version_selected_portfile {
 3832:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3833:     my ($answer_name,$answer_ver,$answer_ext) =
 3834:         &file_name_version_ext($file_name);
 3835:     my $new_answer;
 3836:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3837:     if($env{'form.copy'} eq '-1') {
 3838:         $new_answer = 'problem getting file';
 3839:     } else {
 3840:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3841:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3842:                             $stu_name,$domain,'copy',
 3843: 		        '/portfolio'.$directory.$new_answer);
 3844:     }    
 3845:     return ($new_answer);
 3846: }
 3847: 
 3848: sub file_name_version_ext {
 3849:     my ($file)=@_;
 3850:     my @file_parts = split(/\./, $file);
 3851:     my ($name,$version,$ext);
 3852:     if (@file_parts > 1) {
 3853: 	$ext=pop(@file_parts);
 3854: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3855: 	    $version=pop(@file_parts);
 3856: 	}
 3857: 	$name=join('.',@file_parts);
 3858:     } else {
 3859: 	$name=join('.',@file_parts);
 3860:     }
 3861:     return($name,$version,$ext);
 3862: }
 3863: 
 3864: #--------------------------------------------------------------------------------------
 3865: #
 3866: #-------------------------- Next few routines handles grading by section or whole class
 3867: #
 3868: #--- Javascript to handle grading by section or whole class
 3869: sub viewgrades_js {
 3870:     my ($request) = shift;
 3871: 
 3872:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3873:     &js_escape(\$alertmsg);
 3874:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3875:    function writePoint(partid,weight,point) {
 3876: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3877: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3878: 	if (point == "textval") {
 3879: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3880: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3881: 		alert("$alertmsg"+parseFloat(point));
 3882: 		var resetbox = false;
 3883: 		for (var i=0; i<radioButton.length; i++) {
 3884: 		    if (radioButton[i].checked) {
 3885: 			textbox.value = i;
 3886: 			resetbox = true;
 3887: 		    }
 3888: 		}
 3889: 		if (!resetbox) {
 3890: 		    textbox.value = "";
 3891: 		}
 3892: 		return;
 3893: 	    }
 3894: 	    if (parseFloat(point) > parseFloat(weight)) {
 3895: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3896: 				   ") greater than the weight for the part. Accept?");
 3897: 		if (resp == false) {
 3898: 		    textbox.value = "";
 3899: 		    return;
 3900: 		}
 3901: 	    }
 3902: 	    for (var i=0; i<radioButton.length; i++) {
 3903: 		radioButton[i].checked=false;
 3904: 		if (parseFloat(point) == i) {
 3905: 		    radioButton[i].checked=true;
 3906: 		}
 3907: 	    }
 3908: 
 3909: 	} else {
 3910: 	    textbox.value = parseFloat(point);
 3911: 	}
 3912: 	for (i=0;i<document.classgrade.total.value;i++) {
 3913: 	    var user = document.classgrade["ctr"+i].value;
 3914: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3915: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3916: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3917: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3918: 	    if (saveval != "correct") {
 3919: 		scorename.value = point;
 3920: 		if (selname[0].selected != true) {
 3921: 		    selname[0].selected = true;
 3922: 		}
 3923: 	    }
 3924: 	}
 3925: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3926:     }
 3927: 
 3928:     function writeRadText(partid,weight) {
 3929: 	var selval   = document.classgrade["SELVAL_"+partid];
 3930: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3931:         var override = document.classgrade["FORCE_"+partid].checked;
 3932: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3933: 	if (selval[1].selected || selval[2].selected) {
 3934: 	    for (var i=0; i<radioButton.length; i++) {
 3935: 		radioButton[i].checked=false;
 3936: 
 3937: 	    }
 3938: 	    textbox.value = "";
 3939: 
 3940: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3941: 		var user = document.classgrade["ctr"+i].value;
 3942: 		user = user.replace(new RegExp(':', 'g'),"_");
 3943: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3944: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3945: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3946: 		if ((saveval != "correct") || override) {
 3947: 		    scorename.value = "";
 3948: 		    if (selval[1].selected) {
 3949: 			selname[1].selected = true;
 3950: 		    } else {
 3951: 			selname[2].selected = true;
 3952: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3953: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3954: 		    }
 3955: 		}
 3956: 	    }
 3957: 	} else {
 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") || override) {
 3965: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3966: 		    selname[0].selected = true;
 3967: 		}
 3968: 	    }
 3969: 	}	    
 3970:     }
 3971: 
 3972:     function changeSelect(partid,user) {
 3973: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3974: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3975: 	var point  = textbox.value;
 3976: 	var weight = document.classgrade["weight_"+partid].value;
 3977: 
 3978: 	if (isNaN(point) || parseFloat(point) < 0) {
 3979: 	    alert("$alertmsg"+parseFloat(point));
 3980: 	    textbox.value = "";
 3981: 	    return;
 3982: 	}
 3983: 	if (parseFloat(point) > parseFloat(weight)) {
 3984: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3985: 			       ") greater than the weight of the part. Accept?");
 3986: 	    if (resp == false) {
 3987: 		textbox.value = "";
 3988: 		return;
 3989: 	    }
 3990: 	}
 3991: 	selval[0].selected = true;
 3992:     }
 3993: 
 3994:     function changeOneScore(partid,user) {
 3995: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3996: 	if (selval[1].selected || selval[2].selected) {
 3997: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3998: 	    if (selval[2].selected) {
 3999: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 4000: 	    }
 4001:         }
 4002:     }
 4003: 
 4004:     function resetEntry(numpart) {
 4005: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 4006: 	    var partid = document.classgrade["partid_"+ctpart].value;
 4007: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 4008: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 4009: 	    var selval  = document.classgrade["SELVAL_"+partid];
 4010: 	    for (var i=0; i<radioButton.length; i++) {
 4011: 		radioButton[i].checked=false;
 4012: 
 4013: 	    }
 4014: 	    textbox.value = "";
 4015: 	    selval[0].selected = true;
 4016: 
 4017: 	    for (i=0;i<document.classgrade.total.value;i++) {
 4018: 		var user = document.classgrade["ctr"+i].value;
 4019: 		user = user.replace(new RegExp(':', 'g'),"_");
 4020: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 4021: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 4022: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 4023: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 4024: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 4025: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 4026: 		if (saveselval == "excused") {
 4027: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 4028: 		} else {
 4029: 		    if (selname[0].selected == false) {selname[0].selected = true};
 4030: 		}
 4031: 	    }
 4032: 	}
 4033:     }
 4034: 
 4035: VIEWJAVASCRIPT
 4036: }
 4037: 
 4038: #--- show scores for a section or whole class w/ option to change/update a score
 4039: sub viewgrades {
 4040:     my ($request,$symb) = @_;
 4041:     &viewgrades_js($request);
 4042: 
 4043:     #need to make sure we have the correct data for later EXT calls, 
 4044:     #thus invalidate the cache
 4045:     &Apache::lonnet::devalidatecourseresdata(
 4046:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4047:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4048:     &Apache::lonnet::clear_EXT_cache_status();
 4049: 
 4050:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 4051: 
 4052:     #view individual student submission form - called using Javascript viewOneStudent
 4053:     $result.=&jscriptNform($symb);
 4054: 
 4055:     #beginning of class grading form
 4056:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4057:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4058: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4059: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4060: 	&build_section_inputs().
 4061: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4062: 
 4063:     #retrieve selected groups
 4064:     my (@groups,$group_display);
 4065:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4066:     if (grep(/^all$/,@groups)) {
 4067:         @groups = ('all');
 4068:     } elsif (grep(/^none$/,@groups)) {
 4069:         @groups = ('none');
 4070:     } elsif (@groups > 0) {
 4071:         $group_display = join(', ',@groups);
 4072:     }
 4073: 
 4074:     my ($common_header,$specific_header,@sections,$section_display);
 4075:     if ($env{'request.course.sec'} ne '') {
 4076:         @sections = ($env{'request.course.sec'});
 4077:     } else {
 4078:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4079:     }
 4080: 
 4081: # Check if Save button should be usable
 4082:     my $disabled = ' disabled="disabled"';
 4083:     if ($perm{'mgr'}) {
 4084:         if (grep(/^all$/,@sections)) {
 4085:             undef($disabled);
 4086:         } else {
 4087:             foreach my $sec (@sections) {
 4088:                 if (&canmodify($sec)) {
 4089:                     undef($disabled);
 4090:                     last;
 4091:                 }
 4092:             }
 4093:         }
 4094:     }
 4095:     if (grep(/^all$/,@sections)) {
 4096:         @sections = ('all');
 4097:         if ($group_display) {
 4098:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4099:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4100:         } elsif (grep(/^none$/,@groups)) {
 4101:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4102:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4103:         } else {
 4104:             $common_header = &mt('Assign Common Grade to Class');
 4105:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4106:         }
 4107:     } elsif (grep(/^none$/,@sections)) {
 4108:         @sections = ('none');
 4109:         if ($group_display) {
 4110:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4111:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4112:         } elsif (grep(/^none$/,@groups)) {
 4113:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4114:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4115:         } else {
 4116:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4117:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4118:         }
 4119:     } else {
 4120:         $section_display = join (", ",@sections);
 4121:         if ($group_display) {
 4122:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4123:                                  $section_display,$group_display);
 4124:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4125:                                    $section_display,$group_display);
 4126:         } elsif (grep(/^none$/,@groups)) {
 4127:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4128:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4129:         } else {
 4130:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4131:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4132:         }
 4133:     }
 4134:     my %submit_types = &substatus_options();
 4135:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4136: 
 4137:     if ($env{'form.submitonly'} eq 'all') {
 4138:         $result.= '<h3>'.$common_header.'</h3>';
 4139:     } else {
 4140:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 4141:     }
 4142:     $result .= &Apache::loncommon::start_data_table();
 4143:     #radio buttons/text box for assigning points for a section or class.
 4144:     #handles different parts of a problem
 4145:     my $res_error;
 4146:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4147:     if ($res_error) {
 4148:         return &navmap_errormsg();
 4149:     }
 4150:     my %weight = ();
 4151:     my $ctsparts = 0;
 4152:     my %seen = ();
 4153:     my @part_response_id = &flatten_responseType($responseType);
 4154:     foreach my $part_response_id (@part_response_id) {
 4155:     	my ($partid,$respid) = @{ $part_response_id };
 4156: 	my $part_resp = join('_',@{ $part_response_id });
 4157: 	next if $seen{$partid};
 4158: 	$seen{$partid}++;
 4159: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4160: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4161: 
 4162: 	my $display_part=&get_display_part($partid,$symb);
 4163: 	my $radio.='<table border="0"><tr>';  
 4164: 	my $ctr = 0;
 4165: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4166: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4167: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4168: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4169: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4170: 	    $ctr++;
 4171: 	}
 4172: 	$radio.='</tr></table>';
 4173: 	my $line = '<input type="text" name="TEXTVAL_'.
 4174: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4175: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4176: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4177: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4178:                 '<select name="SELVAL_'.$partid.'" '.
 4179: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4180: 		$weight{$partid}.')"> '.
 4181: 	    '<option selected="selected"> </option>'.
 4182: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4183: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4184: 	    '</select></td>'.
 4185:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4186: 	$line.='<input type="hidden" name="partid_'.
 4187: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4188: 	$line.='<input type="hidden" name="weight_'.
 4189: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4190: 
 4191: 	$result.=
 4192: 	    &Apache::loncommon::start_data_table_row()."\n".
 4193: 	    '<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>'.
 4194: 	    &Apache::loncommon::end_data_table_row()."\n";
 4195: 	$ctsparts++;
 4196:     }
 4197:     $result.=&Apache::loncommon::end_data_table()."\n".
 4198: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4199:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4200: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4201: 
 4202:     #table listing all the students in a section/class
 4203:     #header of table
 4204:     if ($env{'form.submitonly'} eq 'all') { 
 4205:         $result.= '<h3>'.$specific_header.'</h3>';
 4206:     } else {
 4207:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 4208:     }
 4209:     $result.= &Apache::loncommon::start_data_table().
 4210: 	      &Apache::loncommon::start_data_table_header_row().
 4211: 	      '<th>'.&mt('No.').'</th>'.
 4212: 	      '<th>'.&nameUserString('header')."</th>\n";
 4213:     my $partserror;
 4214:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4215:     if ($partserror) {
 4216:         return &navmap_errormsg();
 4217:     }
 4218:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4219:     my @partids = ();
 4220:     foreach my $part (@parts) {
 4221: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4222:         my $narrowtext = &mt('Tries');
 4223: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4224: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 4225: 	my ($partid) = &split_part_type($part);
 4226:         push(@partids,$partid);
 4227: #
 4228: # FIXME: Looks like $display looks at English text
 4229: #
 4230: 	my $display_part=&get_display_part($partid,$symb);
 4231: 	if ($display =~ /^Partial Credit Factor/) {
 4232: 	    $result.='<th>'.
 4233:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4234:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4235: 	    next;
 4236: 	    
 4237: 	} else {
 4238: 	    if ($display =~ /Problem Status/) {
 4239: 		my $grade_status_mt = &mt('Grade Status');
 4240: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4241: 	    }
 4242: 	    my $part_mt = &mt('Part:');
 4243: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4244: 	}
 4245: 
 4246: 	$result.='<th>'.$display.'</th>'."\n";
 4247:     }
 4248:     $result.=&Apache::loncommon::end_data_table_header_row();
 4249: 
 4250:     my %last_resets = 
 4251: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4252: 
 4253:     #get info for each student
 4254:     #list all the students - with points and grade status
 4255:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4256:     my $ctr = 0;
 4257:     foreach (sort 
 4258: 	     {
 4259: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4260: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4261: 		 }
 4262: 		 return $a cmp $b;
 4263: 	     } (keys(%$fullname))) {
 4264: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4265: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 4266:     }
 4267:     $result.=&Apache::loncommon::end_data_table();
 4268:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4269:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4270: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4271:     if ($ctr == 0) {
 4272:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4273:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4274:                 '<span class="LC_warning">';
 4275:         if ($env{'form.submitonly'} eq 'all') {
 4276:             if (grep(/^all$/,@sections)) {
 4277:                 if (grep(/^all$/,@groups)) {
 4278:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4279:                                    $stu_status);
 4280:                 } elsif (grep(/^none$/,@groups)) {
 4281:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4282:                                    $stu_status);
 4283:                 } else {
 4284:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4285:                                    $group_display,$stu_status);
 4286:                 }
 4287:             } elsif (grep(/^none$/,@sections)) {
 4288:                 if (grep(/^all$/,@groups)) {
 4289:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4290:                                    $stu_status);
 4291:                 } elsif (grep(/^none$/,@groups)) {
 4292:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4293:                                    $stu_status);
 4294:                 } else {
 4295:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4296:                                    $group_display,$stu_status);
 4297:                 }
 4298:             } else {
 4299:                 if (grep(/^all$/,@groups)) {
 4300:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4301:                                    $section_display,$stu_status);
 4302:                 } elsif (grep(/^none$/,@groups)) {
 4303:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4304:                                    $section_display,$stu_status);
 4305:                 } else {
 4306:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4307:                                    $section_display,$group_display,$stu_status);
 4308:                 }
 4309:             }
 4310:         } else {
 4311:             if (grep(/^all$/,@sections)) {
 4312:                 if (grep(/^all$/,@groups)) {
 4313:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4314:                                    $stu_status,$submission_status);
 4315:                 } elsif (grep(/^none$/,@groups)) {
 4316:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4317:                                    $stu_status,$submission_status);
 4318:                 } else {
 4319:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4320:                                    $group_display,$stu_status,$submission_status);
 4321:                 }
 4322:             } elsif (grep(/^none$/,@sections)) {
 4323:                 if (grep(/^all$/,@groups)) {
 4324:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4325:                                    $stu_status,$submission_status);
 4326:                 } elsif (grep(/^none$/,@groups)) {
 4327:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4328:                                    $stu_status,$submission_status);
 4329:                 } else {
 4330:                     $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.',
 4331:                                    $group_display,$stu_status,$submission_status);
 4332:                 }
 4333:             } else {
 4334:                 if (grep(/^all$/,@groups)) {
 4335:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4336:                                    $section_display,$stu_status,$submission_status);
 4337:                 } elsif (grep(/^none$/,@groups)) {
 4338:                     $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.',
 4339:                                    $section_display,$stu_status,$submission_status);
 4340:                 } else {
 4341:                     $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.',
 4342:                                    $section_display,$group_display,$stu_status,$submission_status);
 4343:                 }
 4344:             }
 4345: 	}
 4346: 	$result .= '</span><br />';
 4347:     }
 4348:     return $result;
 4349: }
 4350: 
 4351: #--- call by previous routine to display each student who satisfies submission filter.
 4352: sub viewstudentgrade {
 4353:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4354:     my ($uname,$udom) = split(/:/,$student);
 4355:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4356:     my $submitonly = $env{'form.submitonly'};
 4357:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4358:         my %partstatus = ();
 4359:         if (ref($parts) eq 'ARRAY') {
 4360:             foreach my $apart (@{$parts}) {
 4361:                 my ($part,$type) = &split_part_type($apart);
 4362:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4363:                 $status = 'nothing' if ($status eq '');
 4364:                 $partstatus{$part}      = $status;
 4365:                 my $subkey = "resource.$part.submitted_by";
 4366:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4367:             }
 4368:             my $submitted = 0;
 4369:             my $graded = 0;
 4370:             my $incorrect = 0;
 4371:             foreach my $key (keys(%partstatus)) {
 4372:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4373:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4374:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4375: 
 4376:                 my $partid = (split(/\./,$key))[1];
 4377:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4378:                     $submitted = 0;
 4379:                 }
 4380:             }
 4381:             return if (!$submitted && ($submitonly eq 'yes' ||
 4382:                                        $submitonly eq 'incorrect' ||
 4383:                                        $submitonly eq 'graded'));
 4384:             return if (!$graded && ($submitonly eq 'graded'));
 4385:             return if (!$incorrect && $submitonly eq 'incorrect');
 4386:         }
 4387:     }
 4388:     if ($submitonly eq 'queued') {
 4389:         my ($cdom,$cnum) = split(/_/,$courseid);
 4390:         my %queue_status =
 4391:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4392:                                                     $udom,$uname);
 4393:         return if (!defined($queue_status{'gradingqueue'}));
 4394:     }
 4395:     $$ctr++;
 4396:     my %aggregates = ();
 4397:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4398: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4399: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4400: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4401: 	'\');" target="_self">'.$fullname.'</a> '.
 4402: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4403:     $student=~s/:/_/; # colon doen't work in javascript for names
 4404:     foreach my $apart (@$parts) {
 4405: 	my ($part,$type) = &split_part_type($apart);
 4406: 	my $score=$record{"resource.$part.$type"};
 4407:         $result.='<td align="center">';
 4408:         my ($aggtries,$totaltries);
 4409:         unless (exists($aggregates{$part})) {
 4410: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4411: 
 4412: 	    $aggtries = $totaltries;
 4413:             if ($$last_resets{$part}) {  
 4414:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4415: 					   $part);
 4416:             }
 4417:             $result.='<input type="hidden" name="'.
 4418:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4419:             $result.='<input type="hidden" name="'.
 4420:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4421:             $aggregates{$part} = 1;
 4422:         }
 4423: 	if ($type eq 'awarded') {
 4424: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4425: 	    $result.='<input type="hidden" name="'.
 4426: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4427: 	    $result.='<input type="text" name="'.
 4428: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4429:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4430: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4431: 	} elsif ($type eq 'solved') {
 4432: 	    my ($status,$foo)=split(/_/,$score,2);
 4433: 	    $status = 'nothing' if ($status eq '');
 4434: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4435: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4436: 	    $result.='&nbsp;<select name="'.
 4437: 		'GD_'.$student.'_'.$part.'_solved" '.
 4438:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4439: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4440: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4441: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4442: 	    $result.="</select>&nbsp;</td>\n";
 4443: 	} else {
 4444: 	    $result.='<input type="hidden" name="'.
 4445: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4446: 		    "\n";
 4447: 	    $result.='<input type="text" name="'.
 4448: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4449: 		'value="'.$score.'" size="4" /></td>'."\n";
 4450: 	}
 4451:     }
 4452:     $result.=&Apache::loncommon::end_data_table_row();
 4453:     return $result;
 4454: }
 4455: 
 4456: #--- change scores for all the students in a section/class
 4457: #    record does not get update if unchanged
 4458: sub editgrades {
 4459:     my ($request,$symb) = @_;
 4460: 
 4461:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4462:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4463:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4464: 
 4465:     my $result= &Apache::loncommon::start_data_table().
 4466: 	&Apache::loncommon::start_data_table_header_row().
 4467: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4468: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4469:     my %scoreptr = (
 4470: 		    'correct'  =>'correct_by_override',
 4471: 		    'incorrect'=>'incorrect_by_override',
 4472: 		    'excused'  =>'excused',
 4473: 		    'ungraded' =>'ungraded_attempted',
 4474:                     'credited' =>'credit_attempted',
 4475: 		    'nothing'  => '',
 4476: 		    );
 4477:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4478: 
 4479:     my (@partid);
 4480:     my %weight = ();
 4481:     my %columns = ();
 4482:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4483: 
 4484:     my $partserror;
 4485:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4486:     if ($partserror) {
 4487:         return &navmap_errormsg();
 4488:     }
 4489:     my $header;
 4490:     while ($ctr < $env{'form.totalparts'}) {
 4491: 	my $partid = $env{'form.partid_'.$ctr};
 4492: 	push(@partid,$partid);
 4493: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4494: 	$ctr++;
 4495:     }
 4496:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4497:     my $totcolspan = 0;
 4498:     foreach my $partid (@partid) {
 4499: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4500: 	    '<th align="center">'.&mt('New Score').'</th>';
 4501: 	$columns{$partid}=2;
 4502: 	foreach my $stores (@parts) {
 4503: 	    my ($part,$type) = &split_part_type($stores);
 4504: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4505: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4506: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4507: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4508:             my $narrowtext = &mt('Tries');
 4509: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4510: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4511: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4512: 	    $columns{$partid}+=2;
 4513: 	}
 4514:         $totcolspan += $columns{$partid};
 4515:     }
 4516:     foreach my $partid (@partid) {
 4517: 	my $display_part=&get_display_part($partid,$symb);
 4518: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4519: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4520: 	    '</th>';
 4521: 
 4522:     }
 4523:     $result .= &Apache::loncommon::end_data_table_header_row().
 4524: 	&Apache::loncommon::start_data_table_header_row().
 4525: 	$header.
 4526: 	&Apache::loncommon::end_data_table_header_row();
 4527:     my @noupdate;
 4528:     my ($updateCtr,$noupdateCtr) = (1,1);
 4529:     my ($got_types,%queueable);
 4530:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4531: 	my $user = $env{'form.ctr'.$i};
 4532: 	my ($uname,$udom)=split(/:/,$user);
 4533: 	my %newrecord;
 4534: 	my $updateflag = 0;
 4535:         my $usec=$classlist->{"$uname:$udom"}[5];
 4536:         my $canmodify = &canmodify($usec);
 4537:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4538:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4539:         if (!$canmodify) {
 4540:             push(@noupdate,
 4541:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4542:                  &mt('Not allowed to modify student')."</span></td>");
 4543:             next;
 4544:         }
 4545:         my %aggregate = ();
 4546:         my $aggregateflag = 0;
 4547: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4548: 	foreach (@partid) {
 4549: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4550: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4551: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4552: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4553: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4554: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4555: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4556: 	    my $score;
 4557: 	    if ($partial eq '') {
 4558: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4559: 	    } elsif ($partial > 0) {
 4560: 		$score = 'correct_by_override';
 4561: 	    } elsif ($partial == 0) {
 4562: 		$score = 'incorrect_by_override';
 4563: 	    }
 4564: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4565: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4566: 
 4567: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4568: 		"$env{'user.name'}:$env{'user.domain'}";
 4569: 	    if ($dropMenu eq 'reset status' &&
 4570: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4571: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4572: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4573: 		$newrecord{'resource.'.$_.'.award'} = '';
 4574: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4575: 		$updateflag = 1;
 4576:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4577:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4578:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4579:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4580:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4581:                     $aggregateflag = 1;
 4582:                 }
 4583: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4584: 		$updateflag = 1;
 4585: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4586: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4587: 		$rec_update++;
 4588: 	    }
 4589: 
 4590: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4591: 		'<td align="center">'.$awarded.
 4592: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4593: 
 4594: 
 4595: 	    my $partid=$_;
 4596: 	    foreach my $stores (@parts) {
 4597: 		my ($part,$type) = &split_part_type($stores);
 4598: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4599: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4600: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4601: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4602: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4603: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4604: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4605: 		    $updateflag=1;
 4606: 		}
 4607: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4608: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4609: 	    }
 4610: 	}
 4611: 	$line.="\n";
 4612: 
 4613: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4614: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4615: 
 4616: 	if ($updateflag) {
 4617: 	    $count++;
 4618: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4619: 				    $udom,$uname);
 4620: 
 4621: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4622: 					      $cnum,$udom,$uname)) {
 4623: 		# need to figure out if should be in queue.
 4624: 		my %record =  
 4625: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4626: 					     $udom,$uname);
 4627: 		my $all_graded = 1;
 4628: 		my $none_graded = 1;
 4629:                 unless ($got_types) {
 4630:                     my $error;
 4631:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4632:                     unless ($error) {
 4633:                         foreach my $part (@parts) {
 4634:                             if (ref($resptype->{$part}) eq 'HASH') {
 4635:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4636:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4637:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4638:                                         $queueable{$part} = 1;
 4639:                                         last;
 4640:                                     }
 4641:                                 }
 4642:                             }
 4643:                         }
 4644:                     }
 4645:                     $got_types = 1;
 4646:                 }
 4647: 		foreach my $part (@parts) {
 4648:                     if ($queueable{$part}) {
 4649: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4650: 			    $all_graded = 0;
 4651: 		        } else {
 4652: 			    $none_graded = 0;
 4653: 		        }
 4654:                     }
 4655: 		}
 4656: 
 4657: 		if ($all_graded || $none_graded) {
 4658: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4659: 							   $symb,$cdom,$cnum,
 4660: 							   $udom,$uname);
 4661: 		}
 4662: 	    }
 4663: 
 4664: 	    $result.=&Apache::loncommon::start_data_table_row().
 4665: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4666: 		&Apache::loncommon::end_data_table_row();
 4667: 	    $updateCtr++;
 4668: 	} else {
 4669: 	    push(@noupdate,
 4670: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4671: 	    $noupdateCtr++;
 4672: 	}
 4673:         if ($aggregateflag) {
 4674:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4675: 				  $cdom,$cnum);
 4676:         }
 4677:     }
 4678:     if (@noupdate) {
 4679:         my $numcols=$totcolspan+2;
 4680: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4681: 	    '<td align="center" colspan="'.$numcols.'">'.
 4682: 	    &mt('No Changes Occurred For the Students Below').
 4683: 	    '</td>'.
 4684: 	    &Apache::loncommon::end_data_table_row();
 4685: 	foreach my $line (@noupdate) {
 4686: 	    $result.=
 4687: 		&Apache::loncommon::start_data_table_row().
 4688: 		$line.
 4689: 		&Apache::loncommon::end_data_table_row();
 4690: 	}
 4691:     }
 4692:     $result .= &Apache::loncommon::end_data_table();
 4693:     my $msg = '<p><b>'.
 4694: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4695: 	    $rec_update,$count).'</b><br />'.
 4696: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4697: 	'</b></p>';
 4698:     return $title.$msg.$result;
 4699: }
 4700: 
 4701: sub split_part_type {
 4702:     my ($partstr) = @_;
 4703:     my ($temp,@allparts)=split(/_/,$partstr);
 4704:     my $type=pop(@allparts);
 4705:     my $part=join('_',@allparts);
 4706:     return ($part,$type);
 4707: }
 4708: 
 4709: #------------- end of section for handling grading by section/class ---------
 4710: #
 4711: #----------------------------------------------------------------------------
 4712: 
 4713: 
 4714: #----------------------------------------------------------------------------
 4715: #
 4716: #-------------------------- Next few routines handles grading by csv upload
 4717: #
 4718: #--- Javascript to handle csv upload
 4719: sub csvupload_javascript_reverse_associate {
 4720:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4721:     my $error2=&mt('You need to specify at least one grading field');
 4722:   &js_escape(\$error1);
 4723:   &js_escape(\$error2);
 4724:   return(<<ENDPICK);
 4725:   function verify(vf) {
 4726:     var foundsomething=0;
 4727:     var founduname=0;
 4728:     var foundID=0;
 4729:     for (i=0;i<=vf.nfields.value;i++) {
 4730:       tw=eval('vf.f'+i+'.selectedIndex');
 4731:       if (i==0 && tw!=0) { foundID=1; }
 4732:       if (i==1 && tw!=0) { founduname=1; }
 4733:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4734:     }
 4735:     if (founduname==0 && foundID==0) {
 4736: 	alert('$error1');
 4737: 	return;
 4738:     }
 4739:     if (foundsomething==0) {
 4740: 	alert('$error2');
 4741: 	return;
 4742:     }
 4743:     vf.submit();
 4744:   }
 4745:   function flip(vf,tf) {
 4746:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4747:     var i;
 4748:     for (i=0;i<=vf.nfields.value;i++) {
 4749:       //can not pick the same destination field for both name and domain
 4750:       if (((i ==0)||(i ==1)) && 
 4751:           ((tf==0)||(tf==1)) && 
 4752:           (i!=tf) &&
 4753:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4754:         eval('vf.f'+i+'.selectedIndex=0;')
 4755:       }
 4756:     }
 4757:   }
 4758: ENDPICK
 4759: }
 4760: 
 4761: sub csvupload_javascript_forward_associate {
 4762:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4763:     my $error2=&mt('You need to specify at least one grading field');
 4764:   &js_escape(\$error1);
 4765:   &js_escape(\$error2);
 4766:   return(<<ENDPICK);
 4767:   function verify(vf) {
 4768:     var foundsomething=0;
 4769:     var founduname=0;
 4770:     var foundID=0;
 4771:     for (i=0;i<=vf.nfields.value;i++) {
 4772:       tw=eval('vf.f'+i+'.selectedIndex');
 4773:       if (tw==1) { foundID=1; }
 4774:       if (tw==2) { founduname=1; }
 4775:       if (tw>3) { foundsomething=1; }
 4776:     }
 4777:     if (founduname==0 && foundID==0) {
 4778: 	alert('$error1');
 4779: 	return;
 4780:     }
 4781:     if (foundsomething==0) {
 4782: 	alert('$error2');
 4783: 	return;
 4784:     }
 4785:     vf.submit();
 4786:   }
 4787:   function flip(vf,tf) {
 4788:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4789:     var i;
 4790:     //can not pick the same destination field twice
 4791:     for (i=0;i<=vf.nfields.value;i++) {
 4792:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4793:         eval('vf.f'+i+'.selectedIndex=0;')
 4794:       }
 4795:     }
 4796:   }
 4797: ENDPICK
 4798: }
 4799: 
 4800: sub csvuploadmap_header {
 4801:     my ($request,$symb,$datatoken,$distotal)= @_;
 4802:     my $javascript;
 4803:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4804: 	$javascript=&csvupload_javascript_reverse_associate();
 4805:     } else {
 4806: 	$javascript=&csvupload_javascript_forward_associate();
 4807:     }
 4808: 
 4809:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4810:     my $ignore=&mt('Ignore First Line');
 4811:     $symb = &Apache::lonenc::check_encrypt($symb);
 4812:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4813:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4814:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4815:     my $reverse=&mt("Reverse Association");
 4816:     $request->print(<<ENDPICK);
 4817: <br />
 4818: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4819: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4820: <input type="hidden" name="associate"  value="" />
 4821: <input type="hidden" name="phase"      value="three" />
 4822: <input type="hidden" name="datatoken"  value="$datatoken" />
 4823: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4824: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4825: <input type="hidden" name="upfile_associate" 
 4826:                                        value="$env{'form.upfile_associate'}" />
 4827: <input type="hidden" name="symb"       value="$symb" />
 4828: <input type="hidden" name="command"    value="csvuploadoptions" />
 4829: <hr />
 4830: ENDPICK
 4831:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4832:     return '';
 4833: 
 4834: }
 4835: 
 4836: sub csvupload_fields {
 4837:     my ($symb,$errorref) = @_;
 4838:     my (@parts) = &getpartlist($symb,$errorref);
 4839:     if (ref($errorref)) {
 4840:         if ($$errorref) {
 4841:             return;
 4842:         }
 4843:     }
 4844: 
 4845:     my @fields=(['ID','Student/Employee ID'],
 4846: 		['username','Student Username'],
 4847: 		['domain','Student Domain']);
 4848:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4849:     foreach my $part (sort(@parts)) {
 4850: 	my @datum;
 4851: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4852: 	my $name=$part;
 4853: 	if  (!$display) { $display = $name; }
 4854: 	@datum=($name,$display);
 4855: 	if ($name=~/^stores_(.*)_awarded/) {
 4856: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4857: 	}
 4858: 	push(@fields,\@datum);
 4859:     }
 4860:     return (@fields);
 4861: }
 4862: 
 4863: sub csvuploadmap_footer {
 4864:     my ($request,$i,$keyfields) =@_;
 4865:     my $buttontext = &mt('Assign Grades');
 4866:     $request->print(<<ENDPICK);
 4867: </table>
 4868: <input type="hidden" name="nfields" value="$i" />
 4869: <input type="hidden" name="keyfields" value="$keyfields" />
 4870: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4871: </form>
 4872: ENDPICK
 4873: }
 4874: 
 4875: sub checkforfile_js {
 4876:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4877:     &js_escape(\$alertmsg);
 4878:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4879:     function checkUpload(formname) {
 4880: 	if (formname.upfile.value == "") {
 4881: 	    alert("$alertmsg");
 4882: 	    return false;
 4883: 	}
 4884: 	formname.submit();
 4885:     }
 4886: CSVFORMJS
 4887:     return $result;
 4888: }
 4889: 
 4890: sub upcsvScores_form {
 4891:     my ($request,$symb) = @_;
 4892:     if (!$symb) {return '';}
 4893:     my $result=&checkforfile_js();
 4894:     $result.=&Apache::loncommon::start_data_table().
 4895:              &Apache::loncommon::start_data_table_header_row().
 4896:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4897:              &Apache::loncommon::end_data_table_header_row().
 4898:              &Apache::loncommon::start_data_table_row().'<td>';
 4899:     my $upload=&mt("Upload Scores");
 4900:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4901:     my $ignore=&mt('Ignore First Line');
 4902:     $symb = &Apache::lonenc::check_encrypt($symb);
 4903:     $result.=<<ENDUPFORM;
 4904: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4905: <input type="hidden" name="symb" value="$symb" />
 4906: <input type="hidden" name="command" value="csvuploadmap" />
 4907: $upfile_select
 4908: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4909: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4910: </form>
 4911: ENDUPFORM
 4912:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4913:                            &mt("How do I create a CSV file from a spreadsheet")).
 4914:             '</td>'.
 4915:             &Apache::loncommon::end_data_table_row().
 4916:             &Apache::loncommon::end_data_table();
 4917:     return $result;
 4918: }
 4919: 
 4920: 
 4921: sub csvuploadmap {
 4922:     my ($request,$symb) = @_;
 4923:     if (!$symb) {return '';}
 4924: 
 4925:     my $datatoken;
 4926:     if (!$env{'form.datatoken'}) {
 4927: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4928:     } else {
 4929:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4930:         if ($datatoken ne '') { 
 4931: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4932:         }
 4933:     }
 4934:     my @records=&Apache::loncommon::upfile_record_sep();
 4935:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4936:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4937:     my ($i,$keyfields);
 4938:     if (@records) {
 4939:         my $fieldserror;
 4940: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4941:         if ($fieldserror) {
 4942:             $request->print(&navmap_errormsg());
 4943:             return;
 4944:         }
 4945: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4946: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4947: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4948: 							  \@fields);
 4949: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4950: 	    chop($keyfields);
 4951: 	} else {
 4952: 	    unshift(@fields,['none','']);
 4953: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4954: 							    \@fields);
 4955:             foreach my $rec (@records) {
 4956:                 my %temp = &Apache::loncommon::record_sep($rec);
 4957:                 if (%temp) {
 4958:                     $keyfields=join(',',sort(keys(%temp)));
 4959:                     last;
 4960:                 }
 4961:             }
 4962: 	}
 4963:     }
 4964:     &csvuploadmap_footer($request,$i,$keyfields);
 4965: 
 4966:     return '';
 4967: }
 4968: 
 4969: sub csvuploadoptions {
 4970:     my ($request,$symb)= @_;
 4971:     my $overwrite=&mt('Overwrite any existing score');
 4972:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4973:     my $ignore=&mt('Ignore First Line');
 4974:     $request->print(<<ENDPICK);
 4975: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4976: <input type="hidden" name="command"    value="csvuploadassign" />
 4977: <p>
 4978: <label>
 4979:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4980:    $overwrite
 4981: </label>
 4982: </p>
 4983: ENDPICK
 4984:     my %fields=&get_fields();
 4985:     if (!defined($fields{'domain'})) {
 4986: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4987:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4988:     }
 4989:     foreach my $key (sort(keys(%env))) {
 4990: 	if ($key !~ /^form\.(.*)$/) { next; }
 4991: 	my $cleankey=$1;
 4992: 	if ($cleankey eq 'command') { next; }
 4993: 	$request->print('<input type="hidden" name="'.$cleankey.
 4994: 			'"  value="'.$env{$key}.'" />'."\n");
 4995:     }
 4996:     # FIXME do a check for any duplicated user ids...
 4997:     # FIXME do a check for any invalid user ids?...
 4998:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4999: <hr /></form>'."\n");
 5000:     return '';
 5001: }
 5002: 
 5003: sub get_fields {
 5004:     my %fields;
 5005:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 5006:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 5007: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 5008: 	    if ($env{'form.f'.$i} ne 'none') {
 5009: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 5010: 	    }
 5011: 	} else {
 5012: 	    if ($env{'form.f'.$i} ne 'none') {
 5013: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 5014: 	    }
 5015: 	}
 5016:     }
 5017:     return %fields;
 5018: }
 5019: 
 5020: sub csvuploadassign {
 5021:     my ($request,$symb) = @_;
 5022:     if (!$symb) {return '';}
 5023:     my $error_msg = '';
 5024:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 5025:     if ($datatoken ne '') {
 5026:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 5027:     }
 5028:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 5029:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 5030:     my %fields=&get_fields();
 5031:     my $courseid=$env{'request.course.id'};
 5032:     my ($classlist) = &getclasslist('all',0);
 5033:     my @notallowed;
 5034:     my @skipped;
 5035:     my @warnings;
 5036:     my $countdone=0;
 5037:     foreach my $grade (@gradedata) {
 5038: 	my %entries=&Apache::loncommon::record_sep($grade);
 5039: 	my $domain;
 5040: 	if ($entries{$fields{'domain'}}) {
 5041: 	    $domain=$entries{$fields{'domain'}};
 5042: 	} else {
 5043: 	    $domain=$env{'form.default_domain'};
 5044: 	}
 5045: 	$domain=~s/\s//g;
 5046: 	my $username=$entries{$fields{'username'}};
 5047: 	$username=~s/\s//g;
 5048: 	if (!$username) {
 5049: 	    my $id=$entries{$fields{'ID'}};
 5050: 	    $id=~s/\s//g;
 5051: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 5052: 	    $username=$ids{$id};
 5053: 	}
 5054: 	if (!exists($$classlist{"$username:$domain"})) {
 5055: 	    my $id=$entries{$fields{'ID'}};
 5056: 	    $id=~s/\s//g;
 5057: 	    if ($id) {
 5058: 		push(@skipped,"$id:$domain");
 5059: 	    } else {
 5060: 		push(@skipped,"$username:$domain");
 5061: 	    }
 5062: 	    next;
 5063: 	}
 5064: 	my $usec=$classlist->{"$username:$domain"}[5];
 5065: 	if (!&canmodify($usec)) {
 5066: 	    push(@notallowed,"$username:$domain");
 5067: 	    next;
 5068: 	}
 5069: 	my %points;
 5070: 	my %grades;
 5071: 	foreach my $dest (keys(%fields)) {
 5072: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5073: 		$dest eq 'domain') { next; }
 5074: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5075: 	    if ($dest=~/stores_(.*)_points/) {
 5076: 		my $part=$1;
 5077: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5078: 					      $symb,$domain,$username);
 5079:                 if ($wgt) {
 5080:                     $entries{$fields{$dest}}=~s/\s//g;
 5081:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5082:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5083:                                           : 'correct_by_override';
 5084:                     if ($pcr>1) {
 5085:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5086:                     }
 5087:                     $grades{"resource.$part.awarded"}=$pcr;
 5088:                     $grades{"resource.$part.solved"}=$award;
 5089:                     $points{$part}=1;
 5090:                 } else {
 5091:                     $error_msg = "<br />" .
 5092:                         &mt("Some point values were assigned"
 5093:                             ." for problems with a weight "
 5094:                             ."of zero. These values were "
 5095:                             ."ignored.");
 5096:                 }
 5097: 	    } else {
 5098: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5099: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5100: 		my $store_key=$dest;
 5101: 		$store_key=~s/^stores/resource/;
 5102: 		$store_key=~s/_/\./g;
 5103: 		$grades{$store_key}=$entries{$fields{$dest}};
 5104: 	    }
 5105: 	}
 5106: 	if (! %grades) {
 5107:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5108:         } else {
 5109: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5110: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5111: 					   $env{'request.course.id'},
 5112: 					   $domain,$username);
 5113: 	   if ($result eq 'ok') {
 5114: # Successfully stored
 5115: 	      $request->print('.');
 5116: # Remove from grading queue
 5117:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5118:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5119:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5120:                                              $domain,$username);
 5121: 	   } else {
 5122: 	      $request->print("<p><span class=\"LC_error\">".
 5123:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5124:                                   "$username:$domain",$result)."</span></p>");
 5125: 	   }
 5126: 	   $request->rflush();
 5127: 	   $countdone++;
 5128:         }
 5129:     }
 5130:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5131:     if (@warnings) {
 5132:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5133:         $request->print(join(', ',@warnings));
 5134:     }
 5135:     if (@skipped) {
 5136: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5137:         $request->print(join(', ',@skipped));
 5138:     }
 5139:     if (@notallowed) {
 5140: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5141: 	$request->print(join(', ',@notallowed));
 5142:     }
 5143:     $request->print("<br />\n");
 5144:     return $error_msg;
 5145: }
 5146: #------------- end of section for handling csv file upload ---------
 5147: #
 5148: #-------------------------------------------------------------------
 5149: #
 5150: #-------------- Next few routines handle grading by page/sequence
 5151: #
 5152: #--- Select a page/sequence and a student to grade
 5153: sub pickStudentPage {
 5154:     my ($request,$symb) = @_;
 5155: 
 5156:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5157:     &js_escape(\$alertmsg);
 5158:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5159: 
 5160: function checkPickOne(formname) {
 5161:     if (radioSelection(formname.student) == null) {
 5162: 	alert("$alertmsg");
 5163: 	return;
 5164:     }
 5165:     ptr = pullDownSelection(formname.selectpage);
 5166:     formname.page.value = formname["page"+ptr].value;
 5167:     formname.title.value = formname["title"+ptr].value;
 5168:     formname.submit();
 5169: }
 5170: 
 5171: LISTJAVASCRIPT
 5172:     &commonJSfunctions($request);
 5173: 
 5174:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5175:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5176:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5177:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5178: 
 5179:     my $result='<h3><span class="LC_info">&nbsp;'.
 5180: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5181: 
 5182:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5183:     my $map_error;
 5184:     my ($titles,$symbx) = &getSymbMap($map_error);
 5185:     if ($map_error) {
 5186:         $request->print(&navmap_errormsg());
 5187:         return; 
 5188:     }
 5189:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5190: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5191: #    my $type=($curpage =~ /\.(page|sequence)/);
 5192: 
 5193:     # Collection of hidden fields
 5194:     my $ctr=0;
 5195:     foreach (@$titles) {
 5196: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5197: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5198: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5199: 	$ctr++;
 5200:     }
 5201:     $result.='<input type="hidden" name="page" />'."\n".
 5202: 	'<input type="hidden" name="title" />'."\n";
 5203: 
 5204:     $result.=&build_section_inputs();
 5205:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5206:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5207:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5208:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5209: 
 5210:     # Show grading options
 5211:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5212:     my $select = '<select name="selectpage">'."\n";
 5213:     $ctr=0;
 5214:     foreach (@$titles) {
 5215:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5216:         $select.='<option value="'.$ctr.'"'.
 5217:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5218:             '>'.$showtitle.'</option>'."\n";
 5219:         $ctr++;
 5220:     }
 5221:     $select.= '</select>';
 5222: 
 5223:     $result.=
 5224:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5225:        .$select
 5226:        .&Apache::lonhtmlcommon::row_closure();
 5227: 
 5228:     $result.=
 5229:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5230:        .'<label><input type="radio" name="vProb" value="no"'
 5231:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5232:        .'<label><input type="radio" name="vProb" value="yes" />'
 5233:            .&mt('yes').'</label>'."\n"
 5234:        .&Apache::lonhtmlcommon::row_closure();
 5235: 
 5236:     $result.=
 5237:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5238:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5239:            .&mt('none').' </label>'."\n"
 5240:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5241:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5242:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5243:            .&mt('all submissions with details').' </label>'
 5244:        .&Apache::lonhtmlcommon::row_closure();
 5245: 
 5246:     $result.=
 5247:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5248:        .'<input type="text" name="CODE" value="" />'
 5249:        .&Apache::lonhtmlcommon::row_closure(1)
 5250:        .&Apache::lonhtmlcommon::end_pick_box();
 5251: 
 5252:     # Show list of students to select for grading
 5253:     $result.='<br /><input type="button" '.
 5254:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5255: 
 5256:     $request->print($result);
 5257: 
 5258:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5259: 	&Apache::loncommon::start_data_table().
 5260: 	&Apache::loncommon::start_data_table_header_row().
 5261: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5262: 	'<th>'.&nameUserString('header').'</th>'.
 5263: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5264: 	'<th>'.&nameUserString('header').'</th>'.
 5265: 	&Apache::loncommon::end_data_table_header_row();
 5266:  
 5267:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5268:     my $ptr = 1;
 5269:     foreach my $student (sort 
 5270: 			 {
 5271: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5272: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5273: 			     }
 5274: 			     return $a cmp $b;
 5275: 			 } (keys(%$fullname))) {
 5276: 	my ($uname,$udom) = split(/:/,$student);
 5277: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5278:                                   : '</td>');
 5279: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5280: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5281: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5282: 	$studentTable.=
 5283: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5284:                          : '');
 5285: 	$ptr++;
 5286:     }
 5287:     if ($ptr%2 == 0) {
 5288: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5289: 	    &Apache::loncommon::end_data_table_row();
 5290:     }
 5291:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5292:     $studentTable.='<input type="button" '.
 5293:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5294: 
 5295:     $request->print($studentTable);
 5296: 
 5297:     return '';
 5298: }
 5299: 
 5300: sub getSymbMap {
 5301:     my ($map_error) = @_;
 5302:     my $navmap = Apache::lonnavmaps::navmap->new();
 5303:     unless (ref($navmap)) {
 5304:         if (ref($map_error)) {
 5305:             $$map_error = 'navmap';
 5306:         }
 5307:         return;
 5308:     }
 5309:     my %symbx = ();
 5310:     my @titles = ();
 5311:     my $minder = 0;
 5312: 
 5313:     # Gather every sequence that has problems.
 5314:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5315: 					       1,0,1);
 5316:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5317: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5318: 	    my $title = $minder.'.'.
 5319: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5320: 	    push(@titles, $title); # minder in case two titles are identical
 5321: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5322: 	    $minder++;
 5323: 	}
 5324:     }
 5325:     return \@titles,\%symbx;
 5326: }
 5327: 
 5328: #
 5329: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5330: sub displayPage {
 5331:     my ($request,$symb) = @_;
 5332:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5333:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5334:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5335:     my $pageTitle = $env{'form.page'};
 5336:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5337:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5338:     my $usec=$classlist->{$env{'form.student'}}[5];
 5339: 
 5340:     #need to make sure we have the correct data for later EXT calls, 
 5341:     #thus invalidate the cache
 5342:     &Apache::lonnet::devalidatecourseresdata(
 5343:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5344:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5345:     &Apache::lonnet::clear_EXT_cache_status();
 5346: 
 5347:     if (!&canview($usec)) {
 5348: 	$request->print(
 5349:             '<span class="LC_warning">'.
 5350:             &mt('Unable to view requested student. ([_1])',
 5351:                 $env{'form.student'}).
 5352:             '</span>');
 5353:         return;
 5354:     }
 5355:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5356:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5357: 	'</h3>'."\n";
 5358:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5359:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5360: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5361:     } else {
 5362: 	delete($env{'form.CODE'});
 5363:     }
 5364:     &sub_page_js($request);
 5365:     $request->print($result);
 5366: 
 5367:     my $navmap = Apache::lonnavmaps::navmap->new();
 5368:     unless (ref($navmap)) {
 5369:         $request->print(&navmap_errormsg());
 5370:         return;
 5371:     }
 5372:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5373:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5374:     if (!$map) {
 5375: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5376: 	return; 
 5377:     }
 5378:     my $iterator = $navmap->getIterator($map->map_start(),
 5379: 					$map->map_finish());
 5380: 
 5381:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5382: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5383: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5384: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5385: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5386: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5387: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5388: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5389: 
 5390:     if (defined($env{'form.CODE'})) {
 5391: 	$studentTable.=
 5392: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5393:     }
 5394:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5395: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5396: 
 5397:     $studentTable.='&nbsp;<span class="LC_info">'.
 5398:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5399:         '</span>'."\n".
 5400: 	&Apache::loncommon::start_data_table().
 5401: 	&Apache::loncommon::start_data_table_header_row().
 5402: 	'<th>'.&mt('Prob.').'</th>'.
 5403: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5404: 	&Apache::loncommon::end_data_table_header_row();
 5405: 
 5406:     &Apache::lonxml::clear_problem_counter();
 5407:     my ($depth,$question,$prob) = (1,1,1);
 5408:     $iterator->next(); # skip the first BEGIN_MAP
 5409:     my $curRes = $iterator->next(); # for "current resource"
 5410:     while ($depth > 0) {
 5411:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5412:         if($curRes == $iterator->END_MAP) { $depth--; }
 5413: 
 5414:         if (ref($curRes) && $curRes->is_problem()) {
 5415: 	    my $parts = $curRes->parts();
 5416:             my $title = $curRes->compTitle();
 5417: 	    my $symbx = $curRes->symb();
 5418: 	    $studentTable.=
 5419: 		&Apache::loncommon::start_data_table_row().
 5420: 		'<td align="center" valign="top" >'.$prob.
 5421: 		(scalar(@{$parts}) == 1 ? '' 
 5422: 		                        : '<br />('.&mt('[_1]parts',
 5423: 							scalar(@{$parts}).'&nbsp;').')'
 5424: 		 ).
 5425: 		 '</td>';
 5426: 	    $studentTable.='<td valign="top">';
 5427: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5428: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5429: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5430: 					     undef,'both',\%form);
 5431: 	    } else {
 5432: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5433: 		$companswer =~ s|<form(.*?)>||g;
 5434: 		$companswer =~ s|</form>||g;
 5435: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5436: #		    $companswer =~ s/$1/ /ms;
 5437: #		    $request->print('match='.$1."<br />\n");
 5438: #		}
 5439: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5440: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5441: 	    }
 5442: 
 5443: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5444: 
 5445: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5446: 		if ($record{'version'} eq '') {
 5447: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5448: 		} else {
 5449: 		    my %responseType = ();
 5450: 		    foreach my $partid (@{$parts}) {
 5451: 			my @responseIds =$curRes->responseIds($partid);
 5452: 			my @responseType =$curRes->responseType($partid);
 5453: 			my %responseIds;
 5454: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5455: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5456: 			}
 5457: 			$responseType{$partid} = \%responseIds;
 5458: 		    }
 5459: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5460: 
 5461: 		}
 5462: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5463: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5464:                 my $identifier = (&canmodify($usec)? $prob : '');
 5465: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5466: 									$env{'request.course.id'},
 5467: 									'','.submission',undef,
 5468:                                                                         $usec,$identifier);
 5469:  
 5470: 	    }
 5471: 	    if (&canmodify($usec)) {
 5472:             $studentTable.=&gradeBox_start();
 5473: 		foreach my $partid (@{$parts}) {
 5474: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5475: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5476: 		    $question++;
 5477: 		}
 5478:             $studentTable.=&gradeBox_end();
 5479: 		$prob++;
 5480: 	    }
 5481: 	    $studentTable.='</td></tr>';
 5482: 
 5483: 	}
 5484:         $curRes = $iterator->next();
 5485:     }
 5486:     my $disabled;
 5487:     unless (&canmodify($usec)) {
 5488:         $disabled = ' disabled="disabled"';
 5489:     }
 5490: 
 5491:     $studentTable.=
 5492:         '</table>'."\n".
 5493:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5494:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5495:         '</form>'."\n";
 5496:     $request->print($studentTable);
 5497: 
 5498:     return '';
 5499: }
 5500: 
 5501: sub displaySubByDates {
 5502:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5503:     my $isCODE=0;
 5504:     my $isTask = ($symb =~/\.task$/);
 5505:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5506:     my $studentTable=&Apache::loncommon::start_data_table().
 5507: 	&Apache::loncommon::start_data_table_header_row().
 5508: 	'<th>'.&mt('Date/Time').'</th>'.
 5509: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5510:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5511: 	'<th>'.&mt('Submission').'</th>'.
 5512: 	'<th>'.&mt('Status').'</th>'.
 5513: 	&Apache::loncommon::end_data_table_header_row();
 5514:     my ($version);
 5515:     my %mark;
 5516:     my %orders;
 5517:     $mark{'correct_by_student'} = $checkIcon;
 5518:     if (!exists($$record{'1:timestamp'})) {
 5519: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5520:     }
 5521: 
 5522:     my $interaction;
 5523:     my $no_increment = 1;
 5524:     my (%lastrndseed,%lasttype);
 5525:     for ($version=1;$version<=$$record{'version'};$version++) {
 5526: 	my $timestamp = 
 5527: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5528: 	if (exists($$record{$version.':resource.0.version'})) {
 5529: 	    $interaction = $$record{$version.':resource.0.version'};
 5530: 	}
 5531:         if ($isTask && $env{'form.previousversion'}) {
 5532:             next unless ($interaction == $env{'form.previousversion'});
 5533:         }
 5534: 	my $where = ($isTask ? "$version:resource.$interaction"
 5535: 		             : "$version:resource");
 5536: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5537: 	    '<td>'.$timestamp.'</td>';
 5538: 	if ($isCODE) {
 5539: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5540: 	}
 5541:         if ($isTask) {
 5542:             $studentTable.='<td>'.$interaction.'</td>';
 5543:         }
 5544: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5545: 	my @displaySub = ();
 5546: 	foreach my $partid (@{$parts}) {
 5547:             my ($hidden,$type);
 5548:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5549:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5550:                 $hidden = 1;
 5551:             }
 5552: 	    my @matchKey;
 5553:             if ($isTask) {
 5554:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5555:             } else {
 5556: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5557:             }
 5558: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5559: 	    my $display_part=&get_display_part($partid,$symb);
 5560: 	    foreach my $matchKey (@matchKey) {
 5561: 		if (exists($$record{$version.':'.$matchKey}) &&
 5562: 		    $$record{$version.':'.$matchKey} ne '') {
 5563:                     
 5564: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5565: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5566:                     $displaySub[0].='<span class="LC_nobreak">';
 5567:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5568:                                    .' <span class="LC_internal_info">'
 5569:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5570:                                    .'</span>'
 5571:                                    .' <b>';
 5572:                     if ($hidden) {
 5573:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5574:                     } else {
 5575:                         my ($trial,$rndseed,$newvariation);
 5576:                         if ($type eq 'randomizetry') {
 5577:                             $trial = $$record{"$where.$partid.tries"};
 5578:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5579:                         }
 5580: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5581: 			    $displaySub[0].=&mt('Trial not counted');
 5582: 		        } else {
 5583: 			    $displaySub[0].=&mt('Trial: [_1]',
 5584: 					    $$record{"$where.$partid.tries"});
 5585:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5586:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5587:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5588:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5589:                                 }
 5590:                             }
 5591:                             $lastrndseed{$partid} = $rndseed;
 5592:                             $lasttype{$partid} = $type;
 5593: 		        }
 5594: 		        my $responseType=($isTask ? 'Task'
 5595:                                               : $responseType->{$partid}->{$responseId});
 5596: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5597: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5598: 			    $orders{$partid}->{$responseId}=
 5599: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5600:                                            $no_increment,$type,$trial,$rndseed);
 5601: 		        }
 5602: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5603: 		        $displaySub[0].='&nbsp; '.
 5604: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5605:                     }
 5606: 		}
 5607: 	    }
 5608: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5609: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5610: 				    $$record{"$where.$partid.checkedin"},
 5611: 				    $$record{"$where.$partid.checkedin.slot"}).
 5612: 					'<br />';
 5613: 	    }
 5614: 	    if (exists $$record{"$where.$partid.award"}) {
 5615: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5616: 		    lc($$record{"$where.$partid.award"}).' '.
 5617: 		    $mark{$$record{"$where.$partid.solved"}}.
 5618: 		    '<br />';
 5619: 	    }
 5620: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5621: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5622: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5623: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5624: 		$displaySub[2].=
 5625: 		    $$record{"$version:resource.$partid.regrader"}.
 5626: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5627: 	    }
 5628: 	}
 5629: 	# needed because old essay regrader has not parts info
 5630: 	if (exists $$record{"$version:resource.regrader"}) {
 5631: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5632: 	}
 5633: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5634: 	if ($displaySub[2]) {
 5635: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5636: 	}
 5637: 	$studentTable.='&nbsp;</td>'.
 5638: 	    &Apache::loncommon::end_data_table_row();
 5639:     }
 5640:     $studentTable.=&Apache::loncommon::end_data_table();
 5641:     return $studentTable;
 5642: }
 5643: 
 5644: sub updateGradeByPage {
 5645:     my ($request,$symb) = @_;
 5646: 
 5647:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5648:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5649:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5650:     my $pageTitle = $env{'form.page'};
 5651:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5652:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5653:     my $usec=$classlist->{$env{'form.student'}}[5];
 5654:     if (!&canmodify($usec)) {
 5655: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5656: 	return;
 5657:     }
 5658:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5659:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5660: 	'</h3>'."\n";
 5661: 
 5662:     $request->print($result);
 5663: 
 5664: 
 5665:     my $navmap = Apache::lonnavmaps::navmap->new();
 5666:     unless (ref($navmap)) {
 5667:         $request->print(&navmap_errormsg());
 5668:         return;
 5669:     }
 5670:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5671:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5672:     if (!$map) {
 5673: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5674: 	return; 
 5675:     }
 5676:     my $iterator = $navmap->getIterator($map->map_start(),
 5677: 					$map->map_finish());
 5678: 
 5679:     my $studentTable=
 5680: 	&Apache::loncommon::start_data_table().
 5681: 	&Apache::loncommon::start_data_table_header_row().
 5682: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5683: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5684: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5685: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5686: 	&Apache::loncommon::end_data_table_header_row();
 5687: 
 5688:     $iterator->next(); # skip the first BEGIN_MAP
 5689:     my $curRes = $iterator->next(); # for "current resource"
 5690:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5691:     while ($depth > 0) {
 5692:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5693:         if($curRes == $iterator->END_MAP) { $depth--; }
 5694: 
 5695:         if (ref($curRes) && $curRes->is_problem()) {
 5696: 	    my $parts = $curRes->parts();
 5697:             my $title = $curRes->compTitle();
 5698: 	    my $symbx = $curRes->symb();
 5699: 	    $studentTable.=
 5700: 		&Apache::loncommon::start_data_table_row().
 5701: 		'<td align="center" valign="top" >'.$prob.
 5702: 		(scalar(@{$parts}) == 1 ? '' 
 5703:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5704: 		.')').'</td>';
 5705: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5706: 
 5707: 	    my %newrecord=();
 5708: 	    my @displayPts=();
 5709:             my %aggregate = ();
 5710:             my $aggregateflag = 0;
 5711:             my %queueable;
 5712:             if ($env{'form.HIDE'.$prob}) {
 5713:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5714:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5715:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5716:                 $hideflag += $numchgs;
 5717:             }
 5718: 	    foreach my $partid (@{$parts}) {
 5719: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5720: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5721:                 my @types = $curRes->responseType($partid);
 5722:                 if (grep(/^essay$/,@types)) {
 5723:                     $queueable{$partid} = 1;
 5724:                 } else {
 5725:                     my @ids = $curRes->responseIds($partid);
 5726:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5727:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
 5728:                                                           '.handgrade',$symb);
 5729:                         if (lc($hndgrd) eq 'yes') {
 5730:                             $queueable{$partid} = 1;
 5731:                             last;
 5732:                         }
 5733:                     }
 5734:                 }
 5735: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5736: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5737: 		my $partial = $newpts/$wgt;
 5738: 		my $score;
 5739: 		if ($partial > 0) {
 5740: 		    $score = 'correct_by_override';
 5741: 		} elsif ($newpts ne '') { #empty is taken as 0
 5742: 		    $score = 'incorrect_by_override';
 5743: 		}
 5744: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5745: 		if ($dropMenu eq 'excused') {
 5746: 		    $partial = '';
 5747: 		    $score = 'excused';
 5748: 		} elsif ($dropMenu eq 'reset status'
 5749: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5750: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5751: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5752: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5753: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5754: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5755: 		    $changeflag++;
 5756: 		    $newpts = '';
 5757:                     
 5758:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5759:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5760:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5761:                     if ($aggtries > 0) {
 5762:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5763:                         $aggregateflag = 1;
 5764:                     }
 5765: 		}
 5766: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5767: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5768: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5769: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5770: 		    '&nbsp;<br />';
 5771: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5772: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5773: 		    '&nbsp;<br />';
 5774: 		$question++;
 5775: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5776: 
 5777: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5778: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5779: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5780: 		    if (scalar(keys(%newrecord)) > 0);
 5781: 
 5782: 		$changeflag++;
 5783: 	    }
 5784: 	    if (scalar(keys(%newrecord)) > 0) {
 5785: 		my %record = 
 5786: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5787: 					     $udom,$uname);
 5788: 
 5789: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5790: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5791: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5792: 		    $newrecord{'resource.CODE'} = '';
 5793: 		}
 5794: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5795: 					$udom,$uname);
 5796: 		%record = &Apache::lonnet::restore($symbx,
 5797: 						   $env{'request.course.id'},
 5798: 						   $udom,$uname);
 5799: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5800: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5801: 	    }
 5802: 	    
 5803:             if ($aggregateflag) {
 5804:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5805:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5806:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5807:             }
 5808: 
 5809: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5810: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5811: 		&Apache::loncommon::end_data_table_row();
 5812: 
 5813: 	    $prob++;
 5814: 	}
 5815:         $curRes = $iterator->next();
 5816:     }
 5817: 
 5818:     $studentTable.=&Apache::loncommon::end_data_table();
 5819:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5820: 		  &mt('The scores were changed for [quant,_1,problem].',
 5821: 		  $changeflag).'<br />');
 5822:     my $hidemsg=($hideflag == 0 ? '' :
 5823:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5824:                      $hideflag).'<br />');
 5825:     $request->print($hidemsg.$grademsg.$studentTable);
 5826: 
 5827:     return '';
 5828: }
 5829: 
 5830: #-------- end of section for handling grading by page/sequence ---------
 5831: #
 5832: #-------------------------------------------------------------------
 5833: 
 5834: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5835: #
 5836: #------ start of section for handling grading by page/sequence ---------
 5837: 
 5838: =pod
 5839: 
 5840: =head1 Bubble sheet grading routines
 5841: 
 5842:   For this documentation:
 5843: 
 5844:    'scanline' refers to the full line of characters
 5845:    from the file that we are parsing that represents one entire sheet
 5846: 
 5847:    'bubble line' refers to the data
 5848:    representing the line of bubbles that are on the physical bubblesheet
 5849: 
 5850: 
 5851: The overall process is that a scanned in bubblesheet data is uploaded
 5852: into a course. When a user wants to grade, they select a
 5853: sequence/folder of resources, a file of bubblesheet info, and pick
 5854: one of the predefined configurations for what each scanline looks
 5855: like.
 5856: 
 5857: Next each scanline is checked for any errors of either 'missing
 5858: bubbles' (it's an error because it may have been mis-scanned
 5859: because too light bubbling), 'double bubble' (each bubble line should
 5860: have no more than one letter picked), invalid or duplicated CODE,
 5861: invalid student/employee ID
 5862: 
 5863: If the CODE option is used that determines the randomization of the
 5864: homework problems, either way the student/employee ID is looked up into a
 5865: username:domain.
 5866: 
 5867: During the validation phase the instructor can choose to skip scanlines. 
 5868: 
 5869: After the validation phase, there are now 3 bubblesheet files
 5870: 
 5871:   scantron_original_filename (unmodified original file)
 5872:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5873:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5874: 
 5875: Also there is a separate hash nohist_scantrondata that contains extra
 5876: correction information that isn't representable in the bubblesheet
 5877: file (see &scantron_getfile() for more information)
 5878: 
 5879: After all scanlines are either valid, marked as valid or skipped, then
 5880: foreach line foreach problem in the picked sequence, an ssi request is
 5881: made that simulates a user submitting their selected letter(s) against
 5882: the homework problem.
 5883: 
 5884: =over 4
 5885: 
 5886: 
 5887: 
 5888: =item defaultFormData
 5889: 
 5890:   Returns html hidden inputs used to hold context/default values.
 5891: 
 5892:  Arguments:
 5893:   $symb - $symb of the current resource 
 5894: 
 5895: =cut
 5896: 
 5897: sub defaultFormData {
 5898:     my ($symb)=@_;
 5899:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5900: }
 5901: 
 5902: 
 5903: =pod 
 5904: 
 5905: =item getSequenceDropDown
 5906: 
 5907:    Return html dropdown of possible sequences to grade
 5908:  
 5909:  Arguments:
 5910:    $symb - $symb of the current resource
 5911:    $map_error - ref to scalar which will container error if
 5912:                 $navmap object is unavailable in &getSymbMap().
 5913: 
 5914: =cut
 5915: 
 5916: sub getSequenceDropDown {
 5917:     my ($symb,$map_error)=@_;
 5918:     my $result='<select name="selectpage">'."\n";
 5919:     my ($titles,$symbx) = &getSymbMap($map_error);
 5920:     if (ref($map_error)) {
 5921:         return if ($$map_error);
 5922:     }
 5923:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5924:     my $ctr=0;
 5925:     foreach (@$titles) {
 5926: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5927: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5928: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5929: 	    '>'.$showtitle.'</option>'."\n";
 5930: 	$ctr++;
 5931:     }
 5932:     $result.= '</select>';
 5933:     return $result;
 5934: }
 5935: 
 5936: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5937:                                    # key is zero-based index - 0, 1, 2 ...
 5938: 
 5939: my %first_bubble_line;             # First bubble line no. for each bubble.
 5940: 
 5941: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5942:                                    # matchresponse or rankresponse, where 
 5943:                                    # an individual response can have multiple 
 5944:                                    # lines
 5945: 
 5946: my %responsetype_per_response;     # responsetype for each response
 5947: 
 5948: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5949:                                    # numbered response. Needed when randomorder
 5950:                                    # or randompick are in use. Key is ID, value 
 5951:                                    # is response number.
 5952: 
 5953: # Save and restore the bubble lines array to the form env.
 5954: 
 5955: 
 5956: sub save_bubble_lines {
 5957:     foreach my $line (keys(%bubble_lines_per_response)) {
 5958: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5959: 	$env{"form.scantron.first_bubble_line.$line"} =
 5960: 	    $first_bubble_line{$line};
 5961:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5962:             $subdivided_bubble_lines{$line};
 5963:         $env{"form.scantron.responsetype.$line"} =
 5964:             $responsetype_per_response{$line};
 5965:     }
 5966:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5967:         my $line = $masterseq_id_responsenum{$resid};
 5968:         $env{"form.scantron.residpart.$line"} = $resid;
 5969:     }
 5970: }
 5971: 
 5972: 
 5973: sub restore_bubble_lines {
 5974:     my $line = 0;
 5975:     %bubble_lines_per_response = ();
 5976:     %masterseq_id_responsenum = ();
 5977:     while ($env{"form.scantron.bubblelines.$line"}) {
 5978: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5979: 	$bubble_lines_per_response{$line} = $value;
 5980: 	$first_bubble_line{$line}  =
 5981: 	    $env{"form.scantron.first_bubble_line.$line"};
 5982:         $subdivided_bubble_lines{$line} =
 5983:             $env{"form.scantron.sub_bubblelines.$line"};
 5984:         $responsetype_per_response{$line} =
 5985:             $env{"form.scantron.responsetype.$line"};
 5986:         my $id = $env{"form.scantron.residpart.$line"};
 5987:         $masterseq_id_responsenum{$id} = $line;
 5988: 	$line++;
 5989:     }
 5990: }
 5991: 
 5992: =pod 
 5993: 
 5994: =item scantron_filenames
 5995: 
 5996:    Returns a list of the scantron files in the current course 
 5997: 
 5998: =cut
 5999: 
 6000: sub scantron_filenames {
 6001:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6002:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6003:     my $getpropath = 1;
 6004:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6005:                                                         $cname,$getpropath);
 6006:     my @possiblenames;
 6007:     if (ref($dirlist) eq 'ARRAY') {
 6008:         foreach my $filename (sort(@{$dirlist})) {
 6009: 	    ($filename)=split(/&/,$filename);
 6010: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6011: 	    $filename=~s/^scantron_orig_//;
 6012: 	    push(@possiblenames,$filename);
 6013:         }
 6014:     }
 6015:     return @possiblenames;
 6016: }
 6017: 
 6018: =pod 
 6019: 
 6020: =item scantron_uploads
 6021: 
 6022:    Returns  html drop-down list of scantron files in current course.
 6023: 
 6024:  Arguments:
 6025:    $file2grade - filename to set as selected in the dropdown
 6026: 
 6027: =cut
 6028: 
 6029: sub scantron_uploads {
 6030:     my ($file2grade) = @_;
 6031:     my $result=	'<select name="scantron_selectfile">';
 6032:     $result.="<option></option>";
 6033:     foreach my $filename (sort(&scantron_filenames())) {
 6034: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6035:     }
 6036:     $result.="</select>";
 6037:     return $result;
 6038: }
 6039: 
 6040: =pod 
 6041: 
 6042: =item scantron_scantab
 6043: 
 6044:   Returns html drop down of the scantron formats in the scantronformat.tab
 6045:   file.
 6046: 
 6047: =cut
 6048: 
 6049: sub scantron_scantab {
 6050:     my $result='<select name="scantron_format">'."\n";
 6051:     $result.='<option></option>'."\n";
 6052:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6053:     if (@lines > 0) {
 6054:         foreach my $line (@lines) {
 6055:             next if (($line =~ /^\#/) || ($line eq ''));
 6056: 	    my ($name,$descrip)=split(/:/,$line);
 6057: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6058:         }
 6059:     }
 6060:     $result.='</select>'."\n";
 6061:     return $result;
 6062: }
 6063: 
 6064: =pod 
 6065: 
 6066: =item scantron_CODElist
 6067: 
 6068:   Returns html drop down of the saved CODE lists from current course,
 6069:   generated from earlier printings.
 6070: 
 6071: =cut
 6072: 
 6073: sub scantron_CODElist {
 6074:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6075:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6076:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6077:     my $namechoice='<option></option>';
 6078:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6079: 	if ($name =~ /^error: 2 /) { next; }
 6080: 	if ($name =~ /^type\0/) { next; }
 6081: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6082:     }
 6083:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6084:     return $namechoice;
 6085: }
 6086: 
 6087: =pod 
 6088: 
 6089: =item scantron_CODEunique
 6090: 
 6091:   Returns the html for "Each CODE to be used once" radio.
 6092: 
 6093: =cut
 6094: 
 6095: sub scantron_CODEunique {
 6096:     my $result='<span class="LC_nobreak">
 6097:                  <label><input type="radio" name="scantron_CODEunique"
 6098:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6099:                 </span>
 6100:                 <span class="LC_nobreak">
 6101:                  <label><input type="radio" name="scantron_CODEunique"
 6102:                         value="no" />'.&mt('No').' </label>
 6103:                 </span>';
 6104:     return $result;
 6105: }
 6106: 
 6107: =pod 
 6108: 
 6109: =item scantron_selectphase
 6110: 
 6111:   Generates the initial screen to start the bubblesheet process.
 6112:   Allows for - starting a grading run.
 6113:              - downloading existing scan data (original, corrected
 6114:                                                 or skipped info)
 6115: 
 6116:              - uploading new scan data
 6117: 
 6118:  Arguments:
 6119:   $r          - The Apache request object
 6120:   $file2grade - name of the file that contain the scanned data to score
 6121: 
 6122: =cut
 6123: 
 6124: sub scantron_selectphase {
 6125:     my ($r,$file2grade,$symb) = @_;
 6126:     if (!$symb) {return '';}
 6127:     my $map_error;
 6128:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6129:     if ($map_error) {
 6130:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6131:         return;
 6132:     }
 6133:     my $default_form_data=&defaultFormData($symb);
 6134:     my $file_selector=&scantron_uploads($file2grade);
 6135:     my $format_selector=&scantron_scantab();
 6136:     my $CODE_selector=&scantron_CODElist();
 6137:     my $CODE_unique=&scantron_CODEunique();
 6138:     my $result;
 6139: 
 6140:     $ssi_error = 0;
 6141: 
 6142:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6143:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6144: 
 6145:         # Chunk of form to prompt for a scantron file upload.
 6146: 
 6147:         $r->print('
 6148:     <br />');
 6149:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6150:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6151:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6152:         &js_escape(\$alertmsg);
 6153:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6154:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6155:     function checkUpload(formname) {
 6156:         if (formname.upfile.value == "") {
 6157:             alert("'.$alertmsg.'");
 6158:             return false;
 6159:         }
 6160:         formname.submit();
 6161:     }'."\n".$formatjs));
 6162:         $r->print('
 6163:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6164:                 '.$default_form_data.'
 6165:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6166:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6167:                 <input name="command" value="scantronupload_save" type="hidden" />
 6168:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6169:               '.&Apache::loncommon::start_data_table_header_row().'
 6170:                 <th>
 6171:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6172:                 </th>
 6173:               '.&Apache::loncommon::end_data_table_header_row().'
 6174:               '.&Apache::loncommon::start_data_table_row().'
 6175:             <td>
 6176:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6177:         if ($formatoptions) {
 6178:             $r->print('</td>
 6179:                  '.&Apache::loncommon::end_data_table_row().'
 6180:                  '.&Apache::loncommon::start_data_table_row().'
 6181:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6182:                  </td>
 6183:                  '.&Apache::loncommon::end_data_table_row().'
 6184:                  '.&Apache::loncommon::start_data_table_row().'
 6185:                  <td>'
 6186:             );
 6187:         } else {
 6188:             $r->print(' <br />');
 6189:         }
 6190:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6191:               </td>
 6192:              '.&Apache::loncommon::end_data_table_row().'
 6193:              '.&Apache::loncommon::end_data_table().'
 6194:              </form>'
 6195:         );
 6196: 
 6197:     }
 6198: 
 6199:     # Chunk of form to prompt for a file to grade and how:
 6200: 
 6201:     $result.= '
 6202:     <br />
 6203:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6204:     <input type="hidden" name="command" value="scantron_warning" />
 6205:     '.$default_form_data.'
 6206:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6207:        '.&Apache::loncommon::start_data_table_header_row().'
 6208:             <th colspan="2">
 6209:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6210:             </th>
 6211:        '.&Apache::loncommon::end_data_table_header_row().'
 6212:        '.&Apache::loncommon::start_data_table_row().'
 6213:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6214:        '.&Apache::loncommon::end_data_table_row().'
 6215:        '.&Apache::loncommon::start_data_table_row().'
 6216:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6217:        '.&Apache::loncommon::end_data_table_row().'
 6218:        '.&Apache::loncommon::start_data_table_row().'
 6219:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6220:        '.&Apache::loncommon::end_data_table_row().'
 6221:        '.&Apache::loncommon::start_data_table_row().'
 6222:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6223:        '.&Apache::loncommon::end_data_table_row().'
 6224:        '.&Apache::loncommon::start_data_table_row().'
 6225:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6226:        '.&Apache::loncommon::end_data_table_row().'
 6227:        '.&Apache::loncommon::start_data_table_row().'
 6228: 	    <td> '.&mt('Options:').' </td>
 6229:             <td>
 6230: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6231:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6232:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6233: 	    </td>
 6234:        '.&Apache::loncommon::end_data_table_row().'
 6235:        '.&Apache::loncommon::start_data_table_row().'
 6236:             <td colspan="2">
 6237:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6238:             </td>
 6239:        '.&Apache::loncommon::end_data_table_row().'
 6240:     '.&Apache::loncommon::end_data_table().'
 6241:     </form>
 6242: ';
 6243:    
 6244:     $r->print($result);
 6245: 
 6246:     # Chunk of the form that prompts to view a scoring office file,
 6247:     # corrected file, skipped records in a file.
 6248: 
 6249:     $r->print('
 6250:    <br />
 6251:    <form action="/adm/grades" name="scantron_download">
 6252:      '.$default_form_data.'
 6253:      <input type="hidden" name="command" value="scantron_download" />
 6254:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6255:        '.&Apache::loncommon::start_data_table_header_row().'
 6256:               <th>
 6257:                 &nbsp;'.&mt('Download a scoring office file').'
 6258:               </th>
 6259:        '.&Apache::loncommon::end_data_table_header_row().'
 6260:        '.&Apache::loncommon::start_data_table_row().'
 6261:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6262:                 <br />
 6263:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6264:        '.&Apache::loncommon::end_data_table_row().'
 6265:      '.&Apache::loncommon::end_data_table().'
 6266:    </form>
 6267:    <br />
 6268: ');
 6269: 
 6270:     &Apache::lonpickcode::code_list($r,2);
 6271: 
 6272:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6273:              $default_form_data."\n".
 6274:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6275:              &Apache::loncommon::start_data_table_header_row()."\n".
 6276:              '<th colspan="2">
 6277:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6278:              '</th>'."\n".
 6279:               &Apache::loncommon::end_data_table_header_row()."\n".
 6280:               &Apache::loncommon::start_data_table_row()."\n".
 6281:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6282:               '<td> '.$sequence_selector.' </td>'.
 6283:               &Apache::loncommon::end_data_table_row()."\n".
 6284:               &Apache::loncommon::start_data_table_row()."\n".
 6285:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6286:               '<td> '.$file_selector.' </td>'."\n".
 6287:               &Apache::loncommon::end_data_table_row()."\n".
 6288:               &Apache::loncommon::start_data_table_row()."\n".
 6289:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6290:               '<td> '.$format_selector.' </td>'."\n".
 6291:               &Apache::loncommon::end_data_table_row()."\n".
 6292:               &Apache::loncommon::start_data_table_row()."\n".
 6293:               '<td> '.&mt('Options').' </td>'."\n".
 6294:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6295:               &Apache::loncommon::end_data_table_row()."\n".
 6296:               &Apache::loncommon::start_data_table_row()."\n".
 6297:               '<td colspan="2">'."\n".
 6298:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6299:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6300:               '</td>'."\n".
 6301:               &Apache::loncommon::end_data_table_row()."\n".
 6302:               &Apache::loncommon::end_data_table()."\n".
 6303:               '</form><br />');
 6304:     return;
 6305: }
 6306: 
 6307: =pod 
 6308: 
 6309: =item username_to_idmap
 6310: 
 6311:     creates a hash keyed by student/employee ID with values of the corresponding
 6312:     student username:domain.
 6313: 
 6314:   Arguments:
 6315: 
 6316:     $classlist - reference to the class list hash. This is a hash
 6317:                  keyed by student name:domain  whose elements are references
 6318:                  to arrays containing various chunks of information
 6319:                  about the student. (See loncoursedata for more info).
 6320: 
 6321:   Returns
 6322:     %idmap - the constructed hash
 6323: 
 6324: =cut
 6325: 
 6326: sub username_to_idmap {
 6327:     my ($classlist)= @_;
 6328:     my %idmap;
 6329:     foreach my $student (keys(%$classlist)) {
 6330:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6331:         unless ($id eq '') {
 6332:             if (!exists($idmap{$id})) {
 6333:                 $idmap{$id} = $student;
 6334:             } else {
 6335:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6336:                 if ($status eq 'Active') {
 6337:                     $idmap{$id} = $student;
 6338:                 }
 6339:             }
 6340:         }
 6341:     }
 6342:     return %idmap;
 6343: }
 6344: 
 6345: =pod
 6346: 
 6347: =item scantron_fixup_scanline
 6348: 
 6349:    Process a requested correction to a scanline.
 6350: 
 6351:   Arguments:
 6352:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6353:     $scan_data         - hash of correction information 
 6354:                           (see &scantron_getfile())
 6355:     $line              - existing scanline
 6356:     $whichline         - line number of the passed in scanline
 6357:     $field             - type of change to process 
 6358:                          (either 
 6359:                           'ID'     -> correct the student/employee ID
 6360:                           'CODE'   -> correct the CODE
 6361:                           'answer' -> fixup the submitted answers)
 6362:     
 6363:    $args               - hash of additional info,
 6364:                           - 'ID' 
 6365:                                'newid' -> studentID to use in replacement
 6366:                                           of existing one
 6367:                           - 'CODE' 
 6368:                                'CODE_ignore_dup' - set to true if duplicates
 6369:                                                    should be ignored.
 6370: 	                       'CODE' - is new code or 'use_unfound'
 6371:                                         if the existing unfound code should
 6372:                                         be used as is
 6373:                           - 'answer'
 6374:                                'response' - new answer or 'none' if blank
 6375:                                'question' - the bubble line to change
 6376:                                'questionnum' - the question identifier,
 6377:                                                may include subquestion. 
 6378: 
 6379:   Returns:
 6380:     $line - the modified scanline
 6381: 
 6382:   Side effects: 
 6383:     $scan_data - may be updated
 6384: 
 6385: =cut
 6386: 
 6387: 
 6388: sub scantron_fixup_scanline {
 6389:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6390:     if ($field eq 'ID') {
 6391: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6392: 	    return ($line,1,'New value too large');
 6393: 	}
 6394: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6395: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6396: 				     $args->{'newid'});
 6397: 	}
 6398: 	substr($line,$$scantron_config{'IDstart'}-1,
 6399: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6400: 	if ($args->{'newid'}=~/^\s*$/) {
 6401: 	    &scan_data($scan_data,"$whichline.user",
 6402: 		       $args->{'username'}.':'.$args->{'domain'});
 6403: 	}
 6404:     } elsif ($field eq 'CODE') {
 6405: 	if ($args->{'CODE_ignore_dup'}) {
 6406: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6407: 	}
 6408: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6409: 	if ($args->{'CODE'} ne 'use_unfound') {
 6410: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6411: 		return ($line,1,'New CODE value too large');
 6412: 	    }
 6413: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6414: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6415: 	    }
 6416: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6417: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6418: 	}
 6419:     } elsif ($field eq 'answer') {
 6420: 	my $length=$scantron_config->{'Qlength'};
 6421: 	my $off=$scantron_config->{'Qoff'};
 6422: 	my $on=$scantron_config->{'Qon'};
 6423: 	my $answer=${off}x$length;
 6424: 	if ($args->{'response'} eq 'none') {
 6425: 	    &scan_data($scan_data,
 6426: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6427: 	} else {
 6428: 	    if ($on eq 'letter') {
 6429: 		my @alphabet=('A'..'Z');
 6430: 		$answer=$alphabet[$args->{'response'}];
 6431: 	    } elsif ($on eq 'number') {
 6432: 		$answer=$args->{'response'}+1;
 6433: 		if ($answer == 10) { $answer = '0'; }
 6434: 	    } else {
 6435: 		substr($answer,$args->{'response'},1)=$on;
 6436: 	    }
 6437: 	    &scan_data($scan_data,
 6438: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6439: 	}
 6440: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6441: 	substr($line,$where-1,$length)=$answer;
 6442:     }
 6443:     return $line;
 6444: }
 6445: 
 6446: =pod
 6447: 
 6448: =item scan_data
 6449: 
 6450:     Edit or look up  an item in the scan_data hash.
 6451: 
 6452:   Arguments:
 6453:     $scan_data  - The hash (see scantron_getfile)
 6454:     $key        - shorthand of the key to edit (actual key is
 6455:                   scantronfilename_key).
 6456:     $data        - New value of the hash entry.
 6457:     $delete      - If true, the entry is removed from the hash.
 6458: 
 6459:   Returns:
 6460:     The new value of the hash table field (undefined if deleted).
 6461: 
 6462: =cut
 6463: 
 6464: 
 6465: sub scan_data {
 6466:     my ($scan_data,$key,$value,$delete)=@_;
 6467:     my $filename=$env{'form.scantron_selectfile'};
 6468:     if (defined($value)) {
 6469: 	$scan_data->{$filename.'_'.$key} = $value;
 6470:     }
 6471:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6472:     return $scan_data->{$filename.'_'.$key};
 6473: }
 6474: 
 6475: # ----- These first few routines are general use routines.----
 6476: 
 6477: # Return the number of occurences of a pattern in a string.
 6478: 
 6479: sub occurence_count {
 6480:     my ($string, $pattern) = @_;
 6481: 
 6482:     my @matches = ($string =~ /$pattern/g);
 6483: 
 6484:     return scalar(@matches);
 6485: }
 6486: 
 6487: 
 6488: # Take a string known to have digits and convert all the
 6489: # digits into letters in the range J,A..I.
 6490: 
 6491: sub digits_to_letters {
 6492:     my ($input) = @_;
 6493: 
 6494:     my @alphabet = ('J', 'A'..'I');
 6495: 
 6496:     my @input    = split(//, $input);
 6497:     my $output ='';
 6498:     for (my $i = 0; $i < scalar(@input); $i++) {
 6499: 	if ($input[$i] =~ /\d/) {
 6500: 	    $output .= $alphabet[$input[$i]];
 6501: 	} else {
 6502: 	    $output .= $input[$i];
 6503: 	}
 6504:     }
 6505:     return $output;
 6506: }
 6507: 
 6508: =pod 
 6509: 
 6510: =item scantron_parse_scanline
 6511: 
 6512:   Decodes a scanline from the selected scantron file
 6513: 
 6514:  Arguments:
 6515:     line             - The text of the scantron file line to process
 6516:     whichline        - Line number
 6517:     scantron_config  - Hash describing the format of the scantron lines.
 6518:     scan_data        - Hash of extra information about the scanline
 6519:                        (see scantron_getfile for more information)
 6520:     just_header      - True if should not process question answers but only
 6521:                        the stuff to the left of the answers.
 6522:     randomorder      - True if randomorder in use
 6523:     randompick       - True if randompick in use
 6524:     sequence         - Exam folder URL
 6525:     master_seq       - Ref to array containing symbs in exam folder
 6526:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6527:                        (corresponding values are resource objects)
 6528:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6529:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6530:                        are refs to an array of resource objects, ordered
 6531:                        according to order used for CODE, when randomorder
 6532:                        and or randompick are in use.
 6533:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6534:                        for current line to question number used for same question
 6535:                         in "Master Sequence" (as seen by Course Coordinator).
 6536:     startline        - Ref to hash where key is question number (0 is first)
 6537:                        and value is number of first bubble line for current 
 6538:                        student or code-based randompick and/or randomorder.
 6539:     totalref         - Ref of scalar used to score total number of bubble
 6540:                        lines needed for responses in a scan line (used when
 6541:                        randompick in use. 
 6542: 
 6543:  Returns:
 6544:    Hash containing the result of parsing the scanline
 6545: 
 6546:    Keys are all proceeded by the string 'scantron.'
 6547: 
 6548:        CODE    - the CODE in use for this scanline
 6549:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6550:                  by the operator
 6551:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6552:                             CODEs were selected, but the usage has been
 6553:                             forced by the operator
 6554:        ID  - student/employee ID
 6555:        PaperID - if used, the ID number printed on the sheet when the 
 6556:                  paper was scanned
 6557:        FirstName - first name from the sheet
 6558:        LastName  - last name from the sheet
 6559: 
 6560:      if just_header was not true these key may also exist
 6561: 
 6562:        missingerror - a list of bubble ranges that are considered to be answers
 6563:                       to a single question that don't have any bubbles filled in.
 6564:                       Of the form questionnumber:firstbubblenumber:count.
 6565:        doubleerror  - a list of bubble ranges that are considered to be answers
 6566:                       to a single question that have more than one bubble filled in.
 6567:                       Of the form questionnumber::firstbubblenumber:count
 6568:    
 6569:                 In the above, count is the number of bubble responses in the
 6570:                 input line needed to represent the possible answers to the question.
 6571:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6572:                 per line would have count = 2.
 6573: 
 6574:        maxquest     - the number of the last bubble line that was parsed
 6575: 
 6576:        (<number> starts at 1)
 6577:        <number>.answer - zero or more letters representing the selected
 6578:                          letters from the scanline for the bubble line 
 6579:                          <number>.
 6580:                          if blank there was either no bubble or there where
 6581:                          multiple bubbles, (consult the keys missingerror and
 6582:                          doubleerror if this is an error condition)
 6583: 
 6584: =cut
 6585: 
 6586: sub scantron_parse_scanline {
 6587:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6588:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6589:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6590: 
 6591:     my %record;
 6592:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6593:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6594: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6595: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6596: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6597: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6598: 	    $record{'scantron.CODE'}=substr($data,
 6599: 					    $$scantron_config{'CODEstart'}-1,
 6600: 					    $$scantron_config{'CODElength'});
 6601: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6602: 		$record{'scantron.useCODE'}=1;
 6603: 	    }
 6604: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6605: 		$record{'scantron.CODE_ignore_dup'}=1;
 6606: 	    }
 6607: 	} else {
 6608: 	    #FIXME interpret first N questions
 6609: 	}
 6610:     }
 6611:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6612: 				  $$scantron_config{'IDlength'});
 6613:     $record{'scantron.PaperID'}=
 6614: 	substr($data,$$scantron_config{'PaperID'}-1,
 6615: 	       $$scantron_config{'PaperIDlength'});
 6616:     $record{'scantron.FirstName'}=
 6617: 	substr($data,$$scantron_config{'FirstName'}-1,
 6618: 	       $$scantron_config{'FirstNamelength'});
 6619:     $record{'scantron.LastName'}=
 6620: 	substr($data,$$scantron_config{'LastName'}-1,
 6621: 	       $$scantron_config{'LastNamelength'});
 6622:     if ($just_header) { return \%record; }
 6623: 
 6624:     my @alphabet=('A'..'Z');
 6625:     my $questnum=0;
 6626:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6627: 
 6628:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6629:     if ($randompick || $randomorder) {
 6630:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6631:                                          $master_seq,$symb_to_resource,
 6632:                                          $partids_by_symb,$orderedforcode,
 6633:                                          $respnumlookup,$startline);
 6634:         if ($total) {
 6635:             $lastpos = $total*$$scantron_config{'Qlength'};
 6636:         }
 6637:         if (ref($totalref)) {
 6638:             $$totalref = $total;
 6639:         }
 6640:     }
 6641:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6642:     chomp($questions);		# Get rid of any trailing \n.
 6643:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6644:     while (length($questions)) {
 6645:         my $answers_needed;
 6646:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6647:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6648:         } else {
 6649:             $answers_needed = $bubble_lines_per_response{$questnum};
 6650:         }
 6651:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6652:                              || 1;
 6653:         $questnum++;
 6654:         my $quest_id = $questnum;
 6655:         my $currentquest = substr($questions,0,$answer_length);
 6656:         $questions       = substr($questions,$answer_length);
 6657:         if (length($currentquest) < $answer_length) { next; }
 6658: 
 6659:         my $subdivided;
 6660:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6661:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6662:         } else {
 6663:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6664:         }
 6665:         if ($subdivided =~ /,/) {
 6666:             my $subquestnum = 1;
 6667:             my $subquestions = $currentquest;
 6668:             my @subanswers_needed = split(/,/,$subdivided);
 6669:             foreach my $subans (@subanswers_needed) {
 6670:                 my $subans_length =
 6671:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6672:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6673:                 $subquestions   = substr($subquestions,$subans_length);
 6674:                 $quest_id = "$questnum.$subquestnum";
 6675:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6676:                     ($$scantron_config{'Qon'} eq 'number')) {
 6677:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6678:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6679:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6680:                         $randomorder,$randompick,$respnumlookup);
 6681:                 } else {
 6682:                     $ansnum = &scantron_validator_positional($ansnum,
 6683:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6684:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6685:                         $randomorder,$randompick,$respnumlookup);
 6686:                 }
 6687:                 $subquestnum ++;
 6688:             }
 6689:         } else {
 6690:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6691:                 ($$scantron_config{'Qon'} eq 'number')) {
 6692:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6693:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6694:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6695:                     $randomorder,$randompick,$respnumlookup);
 6696:             } else {
 6697:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6698:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6699:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6700:                     $randomorder,$randompick,$respnumlookup);
 6701:             }
 6702:         }
 6703:     }
 6704:     $record{'scantron.maxquest'}=$questnum;
 6705:     return \%record;
 6706: }
 6707: 
 6708: sub get_master_seq {
 6709:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
 6710:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6711:                    (ref($symb_to_resource) eq 'HASH'));
 6712:     if ($need_symb_in_map) {
 6713:         return unless (ref($symb_for_examcode) eq 'HASH');
 6714:     }
 6715:     my $resource_error;
 6716:     foreach my $resource (@{$resources}) {
 6717:         my $ressymb;
 6718:         if (ref($resource)) {
 6719:             $ressymb = $resource->symb();
 6720:             push(@{$master_seq},$ressymb);
 6721:             $symb_to_resource->{$ressymb} = $resource;
 6722:             if ($need_symb_in_map) {
 6723:                 unless ($resource->is_map()) {
 6724:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
 6725:                     unless (exists($symb_for_examcode->{$map})) {
 6726:                         $symb_for_examcode->{$map} = $ressymb;
 6727:                     }
 6728:                 }
 6729:             }
 6730:         } else {
 6731:             $resource_error = 1;
 6732:             last;
 6733:         }
 6734:     }
 6735:     return $resource_error;
 6736: }
 6737: 
 6738: sub get_respnum_lookups {
 6739:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6740:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6741:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6742:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6743:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6744:                    (ref($startline) eq 'HASH'));
 6745:     my ($user,$scancode);
 6746:     if ((exists($record->{'scantron.CODE'})) &&
 6747:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6748:         $scancode = $record->{'scantron.CODE'};
 6749:     } else {
 6750:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6751:     }
 6752:     my @mapresources =
 6753:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6754:                      $orderedforcode);
 6755:     my $total = 0;
 6756:     my $count = 0;
 6757:     foreach my $resource (@mapresources) {
 6758:         my $id = $resource->id();
 6759:         my $symb = $resource->symb();
 6760:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6761:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6762:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6763:                 if ($respnum ne '') {
 6764:                     $respnumlookup->{$count} = $respnum;
 6765:                     $startline->{$count} = $total;
 6766:                     $total += $bubble_lines_per_response{$respnum};
 6767:                     $count ++;
 6768:                 }
 6769:             }
 6770:         }
 6771:     }
 6772:     return $total;
 6773: }
 6774: 
 6775: sub scantron_validator_lettnum {
 6776:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6777:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6778:         $randompick,$respnumlookup) = @_;
 6779: 
 6780:     # Qon 'letter' implies for each slot in currquest we have:
 6781:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6782:     #    about anything else (esp. a value of Qoff) for missing
 6783:     #    bubbles.
 6784:     #
 6785:     # Qon 'number' implies each slot gives a digit that indexes the
 6786:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6787:     #    and * or ? for double bubbles on a single line.
 6788:     #
 6789: 
 6790:     my $matchon;
 6791:     if ($$scantron_config{'Qon'} eq 'letter') {
 6792:         $matchon = '[A-Z]';
 6793:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6794:         $matchon = '\d';
 6795:     }
 6796:     my $occurrences = 0;
 6797:     my $responsenum = $questnum-1;
 6798:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6799:        $responsenum = $respnumlookup->{$questnum-1}
 6800:     }
 6801:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6802:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6803:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6804:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6805:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6806:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6807:         my @singlelines = split('',$currquest);
 6808:         foreach my $entry (@singlelines) {
 6809:             $occurrences = &occurence_count($entry,$matchon);
 6810:             if ($occurrences > 1) {
 6811:                 last;
 6812:             }
 6813:         }
 6814:     } else {
 6815:         $occurrences = &occurence_count($currquest,$matchon); 
 6816:     }
 6817:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6818:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6819:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6820:             my $bubble = substr($currquest,$ans,1);
 6821:             if ($bubble =~ /$matchon/ ) {
 6822:                 if ($$scantron_config{'Qon'} eq 'number') {
 6823:                     if ($bubble == 0) {
 6824:                         $bubble = 10; 
 6825:                     }
 6826:                     $record->{"scantron.$ansnum.answer"} = 
 6827:                         $alphabet->[$bubble-1];
 6828:                 } else {
 6829:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6830:                 }
 6831:             } else {
 6832:                 $record->{"scantron.$ansnum.answer"}='';
 6833:             }
 6834:             $ansnum++;
 6835:         }
 6836:     } elsif (!defined($currquest)
 6837:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6838:             || (&occurence_count($currquest,$matchon) == 0)) {
 6839:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6840:             $record->{"scantron.$ansnum.answer"}='';
 6841:             $ansnum++;
 6842:         }
 6843:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6844:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6845:         }
 6846:     } else {
 6847:         if ($$scantron_config{'Qon'} eq 'number') {
 6848:             $currquest = &digits_to_letters($currquest);            
 6849:         }
 6850:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6851:             my $bubble = substr($currquest,$ans,1);
 6852:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6853:             $ansnum++;
 6854:         }
 6855:     }
 6856:     return $ansnum;
 6857: }
 6858: 
 6859: sub scantron_validator_positional {
 6860:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6861:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6862:         $randomorder,$randompick,$respnumlookup) = @_;
 6863: 
 6864:     # Otherwise there's a positional notation;
 6865:     # each bubble line requires Qlength items, and there are filled in
 6866:     # bubbles for each case where there 'Qon' characters.
 6867:     #
 6868: 
 6869:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6870: 
 6871:     # If the split only gives us one element.. the full length of the
 6872:     # answer string, no bubbles are filled in:
 6873: 
 6874:     if ($answers_needed eq '') {
 6875:         return;
 6876:     }
 6877: 
 6878:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6879:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6880:             $record->{"scantron.$ansnum.answer"}='';
 6881:             $ansnum++;
 6882:         }
 6883:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6884:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6885:         }
 6886:     } elsif (scalar(@array) == 2) {
 6887:         my $location = length($array[0]);
 6888:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6889:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6890:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6891:             if ($ans eq $line_num) {
 6892:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6893:             } else {
 6894:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6895:             }
 6896:             $ansnum++;
 6897:          }
 6898:     } else {
 6899:         #  If there's more than one instance of a bubble character
 6900:         #  That's a double bubble; with positional notation we can
 6901:         #  record all the bubbles filled in as well as the
 6902:         #  fact this response consists of multiple bubbles.
 6903:         #
 6904:         my $responsenum = $questnum-1;
 6905:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6906:             $responsenum = $respnumlookup->{$questnum-1}
 6907:         }
 6908:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6909:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6910:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6911:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6912:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6913:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6914:             my $doubleerror = 0;
 6915:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6916:                    (!$doubleerror)) {
 6917:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6918:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6919:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6920:                if (length(@currarray) > 2) {
 6921:                    $doubleerror = 1;
 6922:                } 
 6923:             }
 6924:             if ($doubleerror) {
 6925:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6926:             }
 6927:         } else {
 6928:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6929:         }
 6930:         my $item = $ansnum;
 6931:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6932:             $record->{"scantron.$item.answer"} = '';
 6933:             $item ++;
 6934:         }
 6935: 
 6936:         my @ans=@array;
 6937:         my $i=0;
 6938:         my $increment = 0;
 6939:         while ($#ans) {
 6940:             $i+=length($ans[0]) + $increment;
 6941:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6942:             my $bubble = $i%$$scantron_config{'Qlength'};
 6943:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6944:             shift(@ans);
 6945:             $increment = 1;
 6946:         }
 6947:         $ansnum += $answers_needed;
 6948:     }
 6949:     return $ansnum;
 6950: }
 6951: 
 6952: =pod
 6953: 
 6954: =item scantron_add_delay
 6955: 
 6956:    Adds an error message that occurred during the grading phase to a
 6957:    queue of messages to be shown after grading pass is complete
 6958: 
 6959:  Arguments:
 6960:    $delayqueue  - arrary ref of hash ref of error messages
 6961:    $scanline    - the scanline that caused the error
 6962:    $errormesage - the error message
 6963:    $errorcode   - a numeric code for the error
 6964: 
 6965:  Side Effects:
 6966:    updates the $delayqueue to have a new hash ref of the error
 6967: 
 6968: =cut
 6969: 
 6970: sub scantron_add_delay {
 6971:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6972:     push(@$delayqueue,
 6973: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6974: 	  'ecode' => $errorcode }
 6975: 	 );
 6976: }
 6977: 
 6978: =pod
 6979: 
 6980: =item scantron_find_student
 6981: 
 6982:    Finds the username for the current scanline
 6983: 
 6984:   Arguments:
 6985:    $scantron_record - hash result from scantron_parse_scanline
 6986:    $scan_data       - hash of correction information 
 6987:                       (see &scantron_getfile() form more information)
 6988:    $idmap           - hash from &username_to_idmap()
 6989:    $line            - number of current scanline
 6990:  
 6991:   Returns:
 6992:    Either 'username:domain' or undef if unknown
 6993: 
 6994: =cut
 6995: 
 6996: sub scantron_find_student {
 6997:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6998:     my $scanID=$$scantron_record{'scantron.ID'};
 6999:     if ($scanID =~ /^\s*$/) {
 7000:  	return &scan_data($scan_data,"$line.user");
 7001:     }
 7002:     foreach my $id (keys(%$idmap)) {
 7003:  	if (lc($id) eq lc($scanID)) {
 7004:  	    return $$idmap{$id};
 7005:  	}
 7006:     }
 7007:     return undef;
 7008: }
 7009: 
 7010: =pod
 7011: 
 7012: =item scantron_filter
 7013: 
 7014:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7015:    hidden resources was selected
 7016: 
 7017: =cut
 7018: 
 7019: sub scantron_filter {
 7020:     my ($curres)=@_;
 7021: 
 7022:     if (ref($curres) && $curres->is_problem()) {
 7023: 	# if the user has asked to not have either hidden
 7024: 	# or 'randomout' controlled resources to be graded
 7025: 	# don't include them
 7026: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7027: 	    && $curres->randomout) {
 7028: 	    return 0;
 7029: 	}
 7030: 	return 1;
 7031:     }
 7032:     return 0;
 7033: }
 7034: 
 7035: =pod
 7036: 
 7037: =item scantron_process_corrections
 7038: 
 7039:    Gets correction information out of submitted form data and corrects
 7040:    the scanline
 7041: 
 7042: =cut
 7043: 
 7044: sub scantron_process_corrections {
 7045:     my ($r) = @_;
 7046:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7047:     my ($scanlines,$scan_data)=&scantron_getfile();
 7048:     my $classlist=&Apache::loncoursedata::get_classlist();
 7049:     my $which=$env{'form.scantron_line'};
 7050:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7051:     my ($skip,$err,$errmsg);
 7052:     if ($env{'form.scantron_skip_record'}) {
 7053: 	$skip=1;
 7054:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7055: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7056: 	    $env{'form.scantron_domain'};
 7057: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7058: 	($line,$err,$errmsg)=
 7059: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7060: 				     'ID',{'newid'=>$newid,
 7061: 				    'username'=>$env{'form.scantron_username'},
 7062: 				    'domain'=>$env{'form.scantron_domain'}});
 7063:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7064: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7065: 	my $newCODE;
 7066: 	my %args;
 7067: 	if      ($resolution eq 'use_unfound') {
 7068: 	    $newCODE='use_unfound';
 7069: 	} elsif ($resolution eq 'use_found') {
 7070: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7071: 	} elsif ($resolution eq 'use_typed') {
 7072: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7073: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7074: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7075: 	}
 7076: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7077: 	    $args{'CODE_ignore_dup'}=1;
 7078: 	}
 7079: 	$args{'CODE'}=$newCODE;
 7080: 	($line,$err,$errmsg)=
 7081: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7082: 				     'CODE',\%args);
 7083:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7084: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7085: 	    ($line,$err,$errmsg)=
 7086: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7087: 					 $which,'answer',
 7088: 					 { 'question'=>$question,
 7089: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7090:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7091: 	    if ($err) { last; }
 7092: 	}
 7093:     }
 7094:     if ($err) {
 7095: 	$r->print(
 7096:             '<p class="LC_error">'
 7097:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7098:                 $errmsg)
 7099:            .'</p>');
 7100:     } else {
 7101: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7102: 	&scantron_putfile($scanlines,$scan_data);
 7103:     }
 7104: }
 7105: 
 7106: =pod
 7107: 
 7108: =item reset_skipping_status
 7109: 
 7110:    Forgets the current set of remember skipped scanlines (and thus
 7111:    reverts back to considering all lines in the
 7112:    scantron_skipped_<filename> file)
 7113: 
 7114: =cut
 7115: 
 7116: sub reset_skipping_status {
 7117:     my ($scanlines,$scan_data)=&scantron_getfile();
 7118:     &scan_data($scan_data,'remember_skipping',undef,1);
 7119:     &scantron_putfile(undef,$scan_data);
 7120: }
 7121: 
 7122: =pod
 7123: 
 7124: =item start_skipping
 7125: 
 7126:    Marks a scanline to be skipped. 
 7127: 
 7128: =cut
 7129: 
 7130: sub start_skipping {
 7131:     my ($scan_data,$i)=@_;
 7132:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7133:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7134: 	$remembered{$i}=2;
 7135:     } else {
 7136: 	$remembered{$i}=1;
 7137:     }
 7138:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7139: }
 7140: 
 7141: =pod
 7142: 
 7143: =item should_be_skipped
 7144: 
 7145:    Checks whether a scanline should be skipped.
 7146: 
 7147: =cut
 7148: 
 7149: sub should_be_skipped {
 7150:     my ($scanlines,$scan_data,$i)=@_;
 7151:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7152: 	# not redoing old skips
 7153: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7154: 	return 0;
 7155:     }
 7156:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7157: 
 7158:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7159: 	return 0;
 7160:     }
 7161:     return 1;
 7162: }
 7163: 
 7164: =pod
 7165: 
 7166: =item remember_current_skipped
 7167: 
 7168:    Discovers what scanlines are in the scantron_skipped_<filename>
 7169:    file and remembers them into scan_data for later use.
 7170: 
 7171: =cut
 7172: 
 7173: sub remember_current_skipped {
 7174:     my ($scanlines,$scan_data)=&scantron_getfile();
 7175:     my %to_remember;
 7176:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7177: 	if ($scanlines->{'skipped'}[$i]) {
 7178: 	    $to_remember{$i}=1;
 7179: 	}
 7180:     }
 7181: 
 7182:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7183:     &scantron_putfile(undef,$scan_data);
 7184: }
 7185: 
 7186: =pod
 7187: 
 7188: =item check_for_error
 7189: 
 7190:     Checks if there was an error when attempting to remove a specific
 7191:     scantron_.. bubblesheet data file. Prints out an error if
 7192:     something went wrong.
 7193: 
 7194: =cut
 7195: 
 7196: sub check_for_error {
 7197:     my ($r,$result)=@_;
 7198:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7199: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7200:     }
 7201: }
 7202: 
 7203: =pod
 7204: 
 7205: =item scantron_warning_screen
 7206: 
 7207:    Interstitial screen to make sure the operator has selected the
 7208:    correct options before we start the validation phase.
 7209: 
 7210: =cut
 7211: 
 7212: sub scantron_warning_screen {
 7213:     my ($button_text,$symb)=@_;
 7214:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7215:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7216:     my $CODElist;
 7217:     if ($scantron_config{'CODElocation'} &&
 7218: 	$scantron_config{'CODEstart'} &&
 7219: 	$scantron_config{'CODElength'}) {
 7220: 	$CODElist=$env{'form.scantron_CODElist'};
 7221: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7222: 	$CODElist=
 7223: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7224: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7225:     }
 7226:     my $lastbubblepoints;
 7227:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7228:         $lastbubblepoints =
 7229:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7230:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7231:     }
 7232:     return ('
 7233: <p>
 7234: <span class="LC_warning">
 7235: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7236: </p>
 7237: <table>
 7238: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7239: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7240: '.$CODElist.$lastbubblepoints.'
 7241: </table>
 7242: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7243: '.&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>
 7244: 
 7245: <br />
 7246: ');
 7247: }
 7248: 
 7249: =pod
 7250: 
 7251: =item scantron_do_warning
 7252: 
 7253:    Check if the operator has picked something for all required
 7254:    fields. Error out if something is missing.
 7255: 
 7256: =cut
 7257: 
 7258: sub scantron_do_warning {
 7259:     my ($r,$symb)=@_;
 7260:     if (!$symb) {return '';}
 7261:     my $default_form_data=&defaultFormData($symb);
 7262:     $r->print(&scantron_form_start().$default_form_data);
 7263:     if ( $env{'form.selectpage'} eq '' ||
 7264: 	 $env{'form.scantron_selectfile'} eq '' ||
 7265: 	 $env{'form.scantron_format'} eq '' ) {
 7266: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7267: 	if ( $env{'form.selectpage'} eq '') {
 7268: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7269: 	} 
 7270: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7271: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7272: 	} 
 7273: 	if ( $env{'form.scantron_format'} eq '') {
 7274: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7275: 	} 
 7276:     } else {
 7277: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7278:         my $bubbledbyhand=&hand_bubble_option();
 7279: 	$r->print('
 7280: '.$warning.$bubbledbyhand.'
 7281: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7282: <input type="hidden" name="command" value="scantron_validate" />
 7283: ');
 7284:     }
 7285:     $r->print("</form><br />");
 7286:     return '';
 7287: }
 7288: 
 7289: =pod
 7290: 
 7291: =item scantron_form_start
 7292: 
 7293:     html hidden input for remembering all selected grading options
 7294: 
 7295: =cut
 7296: 
 7297: sub scantron_form_start {
 7298:     my ($max_bubble)=@_;
 7299:     my $result= <<SCANTRONFORM;
 7300: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7301:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7302:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7303:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7304:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7305:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7306:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7307:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7308:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7309:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7310: SCANTRONFORM
 7311: 
 7312:   my $line = 0;
 7313:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7314:        my $chunk =
 7315: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7316:        $chunk .=
 7317: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7318:        $chunk .= 
 7319:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7320:        $chunk .=
 7321:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7322:        $chunk .=
 7323:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7324:        $result .= $chunk;
 7325:        $line++;
 7326:     }
 7327:     return $result;
 7328: }
 7329: 
 7330: =pod
 7331: 
 7332: =item scantron_validate_file
 7333: 
 7334:     Dispatch routine for doing validation of a bubblesheet data file.
 7335: 
 7336:     Also processes any necessary information resets that need to
 7337:     occur before validation begins (ignore previous corrections,
 7338:     restarting the skipped records processing)
 7339: 
 7340: =cut
 7341: 
 7342: sub scantron_validate_file {
 7343:     my ($r,$symb) = @_;
 7344:     if (!$symb) {return '';}
 7345:     my $default_form_data=&defaultFormData($symb);
 7346:     
 7347:     # do the detection of only doing skipped records first before we delete
 7348:     # them when doing the corrections reset
 7349:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7350: 	&reset_skipping_status();
 7351:     }
 7352:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7353: 	&remember_current_skipped();
 7354: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7355:     }
 7356: 
 7357:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7358: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7359: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7360: 	&check_for_error($r,&scantron_remove_scan_data());
 7361: 	$env{'form.scantron_options_ignore'}='done';
 7362:     }
 7363: 
 7364:     if ($env{'form.scantron_corrections'}) {
 7365: 	&scantron_process_corrections($r);
 7366:     }
 7367:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7368:     #get the student pick code ready
 7369:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7370:     my $nav_error;
 7371:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7372:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7373:     if ($nav_error) {
 7374:         $r->print(&navmap_errormsg());
 7375:         return '';
 7376:     }
 7377:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7378:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7379:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7380:     }
 7381:     $r->print($result);
 7382:     
 7383:     my @validate_phases=( 'sequence',
 7384: 			  'ID',
 7385: 			  'CODE',
 7386: 			  'doublebubble',
 7387: 			  'missingbubbles');
 7388:     if (!$env{'form.validatepass'}) {
 7389: 	$env{'form.validatepass'} = 0;
 7390:     }
 7391:     my $currentphase=$env{'form.validatepass'};
 7392: 
 7393: 
 7394:     my $stop=0;
 7395:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7396: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7397: 	$r->rflush();
 7398: 
 7399: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7400: 	{
 7401: 	    no strict 'refs';
 7402: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7403: 	}
 7404:     }
 7405:     if (!$stop) {
 7406: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7407: 	$r->print(&mt('Validation process complete.').'<br />'.
 7408:                   $warning.
 7409:                   &mt('Perform verification for each student after storage of submissions?').
 7410:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7411:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7412:                   ('&nbsp;'x3).'<label>'.
 7413:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7414:                   '</label></span><br />'.
 7415:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7416:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7417:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7418:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7419:     } else {
 7420: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7421: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7422:     }
 7423:     if ($stop) {
 7424: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7425: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7426: 	    $r->print(' '.&mt('this error').' <br />');
 7427: 
 7428:             $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>');
 7429: 	} else {
 7430:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7431: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7432:             } else {
 7433:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7434:             }
 7435: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7436: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7437: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7438: 	}
 7439:     }
 7440:     $r->print(" </form><br />");
 7441:     return '';
 7442: }
 7443: 
 7444: 
 7445: =pod
 7446: 
 7447: =item scantron_remove_file
 7448: 
 7449:    Removes the requested bubblesheet data file, makes sure that
 7450:    scantron_original_<filename> is never removed
 7451: 
 7452: 
 7453: =cut
 7454: 
 7455: sub scantron_remove_file {
 7456:     my ($which)=@_;
 7457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7459:     my $file='scantron_';
 7460:     if ($which eq 'corrected' || $which eq 'skipped') {
 7461: 	$file.=$which.'_';
 7462:     } else {
 7463: 	return 'refused';
 7464:     }
 7465:     $file.=$env{'form.scantron_selectfile'};
 7466:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7467: }
 7468: 
 7469: 
 7470: =pod
 7471: 
 7472: =item scantron_remove_scan_data
 7473: 
 7474:    Removes all scan_data correction for the requested bubblesheet
 7475:    data file.  (In the case that both the are doing skipped records we need
 7476:    to remember the old skipped lines for the time being so that element
 7477:    persists for a while.)
 7478: 
 7479: =cut
 7480: 
 7481: sub scantron_remove_scan_data {
 7482:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7483:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7484:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7485:     my @todelete;
 7486:     my $filename=$env{'form.scantron_selectfile'};
 7487:     foreach my $key (@keys) {
 7488: 	if ($key=~/^\Q$filename\E_/) {
 7489: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7490: 		$key=~/remember_skipping/) {
 7491: 		next;
 7492: 	    }
 7493: 	    push(@todelete,$key);
 7494: 	}
 7495:     }
 7496:     my $result;
 7497:     if (@todelete) {
 7498: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7499: 				       \@todelete,$cdom,$cname);
 7500:     } else {
 7501: 	$result = 'ok';
 7502:     }
 7503:     return $result;
 7504: }
 7505: 
 7506: 
 7507: =pod
 7508: 
 7509: =item scantron_getfile
 7510: 
 7511:     Fetches the requested bubblesheet data file (all 3 versions), and
 7512:     the scan_data hash
 7513:   
 7514:   Arguments:
 7515:     None
 7516: 
 7517:   Returns:
 7518:     2 hash references
 7519: 
 7520:      - first one has 
 7521:          orig      -
 7522:          corrected -
 7523:          skipped   -  each of which points to an array ref of the specified
 7524:                       file broken up into individual lines
 7525:          count     - number of scanlines
 7526:  
 7527:      - second is the scan_data hash possible keys are
 7528:        ($number refers to scanline numbered $number and thus the key affects
 7529:         only that scanline
 7530:         $bubline refers to the specific bubble line element and the aspects
 7531:         refers to that specific bubble line element)
 7532: 
 7533:        $number.user - username:domain to use
 7534:        $number.CODE_ignore_dup 
 7535:                     - ignore the duplicate CODE error 
 7536:        $number.useCODE
 7537:                     - use the CODE in the scanline as is
 7538:        $number.no_bubble.$bubline
 7539:                     - it is valid that there is no bubbled in bubble
 7540:                       at $number $bubline
 7541:        remember_skipping
 7542:                     - a frozen hash containing keys of $number and values
 7543:                       of either 
 7544:                         1 - we are on a 'do skipped records pass' and plan
 7545:                             on processing this line
 7546:                         2 - we are on a 'do skipped records pass' and this
 7547:                             scanline has been marked to skip yet again
 7548: 
 7549: =cut
 7550: 
 7551: sub scantron_getfile {
 7552:     #FIXME really would prefer a scantron directory
 7553:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7554:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7555:     my $lines;
 7556:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7557: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7558:     my %scanlines;
 7559:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7560:     my $temp=$scanlines{'orig'};
 7561:     $scanlines{'count'}=$#$temp;
 7562: 
 7563:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7564: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7565:     if ($lines eq '-1') {
 7566: 	$scanlines{'corrected'}=[];
 7567:     } else {
 7568: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7569:     }
 7570:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7571: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7572:     if ($lines eq '-1') {
 7573: 	$scanlines{'skipped'}=[];
 7574:     } else {
 7575: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7576:     }
 7577:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7578:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7579:     my %scan_data = @tmp;
 7580:     return (\%scanlines,\%scan_data);
 7581: }
 7582: 
 7583: =pod
 7584: 
 7585: =item lonnet_putfile
 7586: 
 7587:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7588: 
 7589:  Arguments:
 7590:    $contents - data to store
 7591:    $filename - filename to store $contents into
 7592: 
 7593:  Returns:
 7594:    result value from &Apache::lonnet::finishuserfileupload
 7595: 
 7596: =cut
 7597: 
 7598: sub lonnet_putfile {
 7599:     my ($contents,$filename)=@_;
 7600:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7601:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7602:     $env{'form.sillywaytopassafilearound'}=$contents;
 7603:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7604: 
 7605: }
 7606: 
 7607: =pod
 7608: 
 7609: =item scantron_putfile
 7610: 
 7611:     Stores the current version of the bubblesheet data files, and the
 7612:     scan_data hash. (Does not modify the original version only the
 7613:     corrected and skipped versions.
 7614: 
 7615:  Arguments:
 7616:     $scanlines - hash ref that looks like the first return value from
 7617:                  &scantron_getfile()
 7618:     $scan_data - hash ref that looks like the second return value from
 7619:                  &scantron_getfile()
 7620: 
 7621: =cut
 7622: 
 7623: sub scantron_putfile {
 7624:     my ($scanlines,$scan_data) = @_;
 7625:     #FIXME really would prefer a scantron directory
 7626:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7627:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7628:     if ($scanlines) {
 7629: 	my $prefix='scantron_';
 7630: # no need to update orig, shouldn't change
 7631: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7632: #		    $env{'form.scantron_selectfile'});
 7633: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7634: 			$prefix.'corrected_'.
 7635: 			$env{'form.scantron_selectfile'});
 7636: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7637: 			$prefix.'skipped_'.
 7638: 			$env{'form.scantron_selectfile'});
 7639:     }
 7640:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7641: }
 7642: 
 7643: =pod
 7644: 
 7645: =item scantron_get_line
 7646: 
 7647:    Returns the correct version of the scanline
 7648: 
 7649:  Arguments:
 7650:     $scanlines - hash ref that looks like the first return value from
 7651:                  &scantron_getfile()
 7652:     $scan_data - hash ref that looks like the second return value from
 7653:                  &scantron_getfile()
 7654:     $i         - number of the requested line (starts at 0)
 7655: 
 7656:  Returns:
 7657:    A scanline, (either the original or the corrected one if it
 7658:    exists), or undef if the requested scanline should be
 7659:    skipped. (Either because it's an skipped scanline, or it's an
 7660:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7661:    pass.
 7662: 
 7663: =cut
 7664: 
 7665: sub scantron_get_line {
 7666:     my ($scanlines,$scan_data,$i)=@_;
 7667:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7668:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7669:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7670:     return $scanlines->{'orig'}[$i]; 
 7671: }
 7672: 
 7673: =pod
 7674: 
 7675: =item scantron_todo_count
 7676: 
 7677:     Counts the number of scanlines that need processing.
 7678: 
 7679:  Arguments:
 7680:     $scanlines - hash ref that looks like the first return value from
 7681:                  &scantron_getfile()
 7682:     $scan_data - hash ref that looks like the second return value from
 7683:                  &scantron_getfile()
 7684: 
 7685:  Returns:
 7686:     $count - number of scanlines to process
 7687: 
 7688: =cut
 7689: 
 7690: sub get_todo_count {
 7691:     my ($scanlines,$scan_data)=@_;
 7692:     my $count=0;
 7693:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7694: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7695: 	if ($line=~/^[\s\cz]*$/) { next; }
 7696: 	$count++;
 7697:     }
 7698:     return $count;
 7699: }
 7700: 
 7701: =pod
 7702: 
 7703: =item scantron_put_line
 7704: 
 7705:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7706:     data file.
 7707: 
 7708:  Arguments:
 7709:     $scanlines - hash ref that looks like the first return value from
 7710:                  &scantron_getfile()
 7711:     $scan_data - hash ref that looks like the second return value from
 7712:                  &scantron_getfile()
 7713:     $i         - line number to update
 7714:     $newline   - contents of the updated scanline
 7715:     $skip      - if true make the line for skipping and update the
 7716:                  'skipped' file
 7717: 
 7718: =cut
 7719: 
 7720: sub scantron_put_line {
 7721:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7722:     if ($skip) {
 7723: 	$scanlines->{'skipped'}[$i]=$newline;
 7724: 	&start_skipping($scan_data,$i);
 7725: 	return;
 7726:     }
 7727:     $scanlines->{'corrected'}[$i]=$newline;
 7728: }
 7729: 
 7730: =pod
 7731: 
 7732: =item scantron_clear_skip
 7733: 
 7734:    Remove a line from the 'skipped' file
 7735: 
 7736:  Arguments:
 7737:     $scanlines - hash ref that looks like the first return value from
 7738:                  &scantron_getfile()
 7739:     $scan_data - hash ref that looks like the second return value from
 7740:                  &scantron_getfile()
 7741:     $i         - line number to update
 7742: 
 7743: =cut
 7744: 
 7745: sub scantron_clear_skip {
 7746:     my ($scanlines,$scan_data,$i)=@_;
 7747:     if (exists($scanlines->{'skipped'}[$i])) {
 7748: 	undef($scanlines->{'skipped'}[$i]);
 7749: 	return 1;
 7750:     }
 7751:     return 0;
 7752: }
 7753: 
 7754: =pod
 7755: 
 7756: =item scantron_filter_not_exam
 7757: 
 7758:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7759:    filter out resources that are not marked as 'exam' mode
 7760: 
 7761: =cut
 7762: 
 7763: sub scantron_filter_not_exam {
 7764:     my ($curres)=@_;
 7765:     
 7766:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7767: 	# if the user has asked to not have either hidden
 7768: 	# or 'randomout' controlled resources to be graded
 7769: 	# don't include them
 7770: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7771: 	    && $curres->randomout) {
 7772: 	    return 0;
 7773: 	}
 7774: 	return 1;
 7775:     }
 7776:     return 0;
 7777: }
 7778: 
 7779: =pod
 7780: 
 7781: =item scantron_validate_sequence
 7782: 
 7783:     Validates the selected sequence, checking for resource that are
 7784:     not set to exam mode.
 7785: 
 7786: =cut
 7787: 
 7788: sub scantron_validate_sequence {
 7789:     my ($r,$currentphase) = @_;
 7790: 
 7791:     my $navmap=Apache::lonnavmaps::navmap->new();
 7792:     unless (ref($navmap)) {
 7793:         $r->print(&navmap_errormsg());
 7794:         return (1,$currentphase);
 7795:     }
 7796:     my (undef,undef,$sequence)=
 7797: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7798: 
 7799:     my $map=$navmap->getResourceByUrl($sequence);
 7800: 
 7801:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7802:                                     value="ignore" />');
 7803:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7804: 	my @resources=
 7805: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7806: 	if (@resources) {
 7807: 	    $r->print('<p class="LC_warning">'
 7808:                .&mt('Some resources in the sequence currently are not set to'
 7809:                    .' exam mode. Grading these resources currently may not'
 7810:                    .' work correctly.')
 7811:                .'</p>'
 7812:             );
 7813: 	    return (1,$currentphase);
 7814: 	}
 7815:     }
 7816: 
 7817:     return (0,$currentphase+1);
 7818: }
 7819: 
 7820: 
 7821: 
 7822: sub scantron_validate_ID {
 7823:     my ($r,$currentphase) = @_;
 7824:     
 7825:     #get student info
 7826:     my $classlist=&Apache::loncoursedata::get_classlist();
 7827:     my %idmap=&username_to_idmap($classlist);
 7828: 
 7829:     #get scantron line setup
 7830:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7831:     my ($scanlines,$scan_data)=&scantron_getfile();
 7832: 
 7833:     my $nav_error;
 7834:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7835:     if ($nav_error) {
 7836:         $r->print(&navmap_errormsg());
 7837:         return(1,$currentphase);
 7838:     }
 7839: 
 7840:     my %found=('ids'=>{},'usernames'=>{});
 7841:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7842: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7843: 	if ($line=~/^[\s\cz]*$/) { next; }
 7844: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7845: 						 $scan_data);
 7846: 	my $id=$$scan_record{'scantron.ID'};
 7847: 	my $found;
 7848: 	foreach my $checkid (keys(%idmap)) {
 7849: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7850: 	}
 7851: 	if ($found) {
 7852: 	    my $username=$idmap{$found};
 7853: 	    if ($found{'ids'}{$found}) {
 7854: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7855: 					 $line,'duplicateID',$found);
 7856: 		return(1,$currentphase);
 7857: 	    } elsif ($found{'usernames'}{$username}) {
 7858: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7859: 					 $line,'duplicateID',$username);
 7860: 		return(1,$currentphase);
 7861: 	    }
 7862: 	    #FIXME store away line we previously saw the ID on to use above
 7863: 	    $found{'ids'}{$found}++;
 7864: 	    $found{'usernames'}{$username}++;
 7865: 	} else {
 7866: 	    if ($id =~ /^\s*$/) {
 7867: 		my $username=&scan_data($scan_data,"$i.user");
 7868: 		if (defined($username) && $found{'usernames'}{$username}) {
 7869: 		    &scantron_get_correction($r,$i,$scan_record,
 7870: 					     \%scantron_config,
 7871: 					     $line,'duplicateID',$username);
 7872: 		    return(1,$currentphase);
 7873: 		} elsif (!defined($username)) {
 7874: 		    &scantron_get_correction($r,$i,$scan_record,
 7875: 					     \%scantron_config,
 7876: 					     $line,'incorrectID');
 7877: 		    return(1,$currentphase);
 7878: 		}
 7879: 		$found{'usernames'}{$username}++;
 7880: 	    } else {
 7881: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7882: 					 $line,'incorrectID');
 7883: 		return(1,$currentphase);
 7884: 	    }
 7885: 	}
 7886:     }
 7887: 
 7888:     return (0,$currentphase+1);
 7889: }
 7890: 
 7891: 
 7892: sub scantron_get_correction {
 7893:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7894:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7895: #FIXME in the case of a duplicated ID the previous line, probably need
 7896: #to show both the current line and the previous one and allow skipping
 7897: #the previous one or the current one
 7898: 
 7899:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7900:         $r->print(
 7901:             '<p class="LC_warning">'
 7902:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7903:                 "<b>$error</b>",
 7904:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7905:            ."</p> \n");
 7906:     } else {
 7907:         $r->print(
 7908:             '<p class="LC_warning">'
 7909:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7910:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7911:            ."</p> \n");
 7912:     }
 7913:     my $message =
 7914:         '<p>'
 7915:        .&mt('The ID on the form is [_1]',
 7916:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7917:        .'<br />'
 7918:        .&mt('The name on the paper is [_1], [_2]',
 7919:             $$scan_record{'scantron.LastName'},
 7920:             $$scan_record{'scantron.FirstName'})
 7921:        .'</p>';
 7922: 
 7923:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7924:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7925:                            # Array populated for doublebubble or
 7926:     my @lines_to_correct;  # missingbubble errors to build javascript
 7927:                            # to validate radio button checking   
 7928: 
 7929:     if ($error =~ /ID$/) {
 7930: 	if ($error eq 'incorrectID') {
 7931: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7932: 		      "</p>\n");
 7933: 	} elsif ($error eq 'duplicateID') {
 7934: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7935: 	}
 7936: 	$r->print($message);
 7937: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7938: 	$r->print("\n<ul><li> ");
 7939: 	#FIXME it would be nice if this sent back the user ID and
 7940: 	#could do partial userID matches
 7941: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7942: 				       'scantron_username','scantron_domain'));
 7943: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7944: 	$r->print("\n:\n".
 7945: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7946: 
 7947: 	$r->print('</li>');
 7948:     } elsif ($error =~ /CODE$/) {
 7949: 	if ($error eq 'incorrectCODE') {
 7950: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7951: 	} elsif ($error eq 'duplicateCODE') {
 7952: 	    $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");
 7953: 	}
 7954:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7955:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7956:                  ."</p>\n");
 7957: 	$r->print($message);
 7958: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7959: 	$r->print("\n<br /> ");
 7960: 	my $i=0;
 7961: 	if ($error eq 'incorrectCODE' 
 7962: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7963: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7964: 	    if ($closest > 0) {
 7965: 		foreach my $testcode (@{$closest}) {
 7966: 		    my $checked='';
 7967: 		    if (!$i) { $checked=' checked="checked"'; }
 7968: 		    $r->print("
 7969:    <label>
 7970:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7971:        ".&mt("Use the similar CODE [_1] instead.",
 7972: 	    "<b><tt>".$testcode."</tt></b>")."
 7973:     </label>
 7974:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7975: 		    $r->print("\n<br />");
 7976: 		    $i++;
 7977: 		}
 7978: 	    }
 7979: 	}
 7980: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7981: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7982: 	    $r->print("
 7983:     <label>
 7984:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7985:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7986: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7987:     </label>");
 7988: 	    $r->print("\n<br />");
 7989: 	}
 7990: 
 7991: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7992: function change_radio(field) {
 7993:     var slct=document.scantronupload.scantron_CODE_resolution;
 7994:     var i;
 7995:     for (i=0;i<slct.length;i++) {
 7996:         if (slct[i].value==field) { slct[i].checked=true; }
 7997:     }
 7998: }
 7999: ENDSCRIPT
 8000: 	my $href="/adm/pickcode?".
 8001: 	   "form=".&escape("scantronupload").
 8002: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8003: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8004: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8005: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8006: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8007: 	    $r->print("
 8008:     <label>
 8009:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8010:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8011: 	     "<a target='_blank' href='$href'>","</a>")."
 8012:     </label> 
 8013:     ".&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\')" />'));
 8014: 	    $r->print("\n<br />");
 8015: 	}
 8016: 	$r->print("
 8017:     <label>
 8018:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8019:        ".&mt("Use [_1] as the CODE.",
 8020: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8021: 	$r->print("\n<br /><br />");
 8022:     } elsif ($error eq 'doublebubble') {
 8023: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8024: 
 8025: 	# The form field scantron_questions is acutally a list of line numbers.
 8026: 	# represented by this form so:
 8027: 
 8028: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8029:                                                 $respnumlookup,$startline);
 8030: 
 8031: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8032: 		  $line_list.'" />');
 8033: 	$r->print($message);
 8034: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8035: 	foreach my $question (@{$arg}) {
 8036: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8037:                                                    $scan_record, $error,
 8038:                                                    $randomorder,$randompick,
 8039:                                                    $respnumlookup,$startline);
 8040:             push(@lines_to_correct,@linenums);
 8041: 	}
 8042:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8043:     } elsif ($error eq 'missingbubble') {
 8044: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8045: 	$r->print($message);
 8046: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8047: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8048: 
 8049: 	# The form field scantron_questions is actually a list of line numbers not
 8050: 	# a list of question numbers. Therefore:
 8051: 	#
 8052: 	
 8053: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8054:                                                 $respnumlookup,$startline);
 8055: 
 8056: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8057: 		  $line_list.'" />');
 8058: 	foreach my $question (@{$arg}) {
 8059: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8060:                                                    $scan_record, $error,
 8061:                                                    $randomorder,$randompick,
 8062:                                                    $respnumlookup,$startline);
 8063:             push(@lines_to_correct,@linenums);
 8064: 	}
 8065:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8066:     } else {
 8067: 	$r->print("\n<ul>");
 8068:     }
 8069:     $r->print("\n</li></ul>");
 8070: }
 8071: 
 8072: sub verify_bubbles_checked {
 8073:     my (@ansnums) = @_;
 8074:     my $ansnumstr = join('","',@ansnums);
 8075:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8076:     &js_escape(\$warning);
 8077:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8078: function verify_bubble_radio(form) {
 8079:     var ansnumArray = new Array ("$ansnumstr");
 8080:     var need_bubble_count = 0;
 8081:     for (var i=0; i<ansnumArray.length; i++) {
 8082:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8083:             var bubble_picked = 0; 
 8084:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8085:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8086:                     bubble_picked = 1;
 8087:                 }
 8088:             }
 8089:             if (bubble_picked == 0) {
 8090:                 need_bubble_count ++;
 8091:             }
 8092:         }
 8093:     }
 8094:     if (need_bubble_count) {
 8095:         alert("$warning");
 8096:         return;
 8097:     }
 8098:     form.submit(); 
 8099: }
 8100: ENDSCRIPT
 8101:     return $output;
 8102: }
 8103: 
 8104: =pod
 8105: 
 8106: =item  questions_to_line_list
 8107: 
 8108: Converts a list of questions into a string of comma separated
 8109: line numbers in the answer sheet used by the questions.  This is
 8110: used to fill in the scantron_questions form field.
 8111: 
 8112:   Arguments:
 8113:      questions    - Reference to an array of questions.
 8114:      randomorder  - True if randomorder in use.
 8115:      randompick   - True if randompick in use.
 8116:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8117:                      for current line to question number used for same question
 8118:                      in "Master Seqence" (as seen by Course Coordinator).
 8119:      startline    - Reference to hash where key is question number (0 is first)
 8120:                     and key is number of first bubble line for current student
 8121:                     or code-based randompick and/or randomorder.
 8122: 
 8123: =cut
 8124: 
 8125: 
 8126: sub questions_to_line_list {
 8127:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8128:     my @lines;
 8129: 
 8130:     foreach my $item (@{$questions}) {
 8131:         my $question = $item;
 8132:         my ($first,$count,$last);
 8133:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8134:             $question = $1;
 8135:             my $subquestion = $2;
 8136:             my $responsenum = $question-1;
 8137:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8138:                 $responsenum = $respnumlookup->{$question-1};
 8139:                 if (ref($startline) eq 'HASH') {
 8140:                     $first = $startline->{$question-1} + 1;
 8141:                 }
 8142:             } else {
 8143:                 $first = $first_bubble_line{$responsenum} + 1;
 8144:             }
 8145:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8146:             my $subcount = 1;
 8147:             while ($subcount<$subquestion) {
 8148:                 $first += $subans[$subcount-1];
 8149:                 $subcount ++;
 8150:             }
 8151:             $count = $subans[$subquestion-1];
 8152:         } else {
 8153:             my $responsenum = $question-1;
 8154:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8155:                 $responsenum = $respnumlookup->{$question-1};
 8156:                 if (ref($startline) eq 'HASH') {
 8157:                     $first = $startline->{$question-1} + 1;
 8158:                 }
 8159:             } else {
 8160:                 $first = $first_bubble_line{$responsenum} + 1;
 8161:             }
 8162:             $count   = $bubble_lines_per_response{$responsenum};
 8163:         }
 8164:         $last = $first+$count-1;
 8165:         push(@lines, ($first..$last));
 8166:     }
 8167:     return join(',', @lines);
 8168: }
 8169: 
 8170: =pod 
 8171: 
 8172: =item prompt_for_corrections
 8173: 
 8174: Prompts for a potentially multiline correction to the
 8175: user's bubbling (factors out common code from scantron_get_correction
 8176: for multi and missing bubble cases).
 8177: 
 8178:  Arguments:
 8179:    $r           - Apache request object.
 8180:    $question    - The question number to prompt for.
 8181:    $scan_config - The scantron file configuration hash.
 8182:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8183:    $error       - Type of error
 8184:    $randomorder - True if randomorder in use.
 8185:    $randompick  - True if randompick in use.
 8186:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8187:                     for current line to question number used for same question
 8188:                     in "Master Seqence" (as seen by Course Coordinator).
 8189:    $startline   - Reference to hash where key is question number (0 is first)
 8190:                   and value is number of first bubble line for current student
 8191:                   or code-based randompick and/or randomorder.
 8192: 
 8193:  Implicit inputs:
 8194:    %bubble_lines_per_response   - Starting line numbers for each question.
 8195:                                   Numbered from 0 (but question numbers are from
 8196:                                   1.
 8197:    %first_bubble_line           - Starting bubble line for each question.
 8198:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8199:                                   type problems render as separate sub-questions, 
 8200:                                   in exam mode. This hash contains a 
 8201:                                   comma-separated list of the lines per 
 8202:                                   sub-question.
 8203:    %responsetype_per_response   - essayresponse, formularesponse,
 8204:                                   stringresponse, imageresponse, reactionresponse,
 8205:                                   and organicresponse type problem parts can have
 8206:                                   multiple lines per response if the weight
 8207:                                   assigned exceeds 10.  In this case, only
 8208:                                   one bubble per line is permitted, but more 
 8209:                                   than one line might contain bubbles, e.g.
 8210:                                   bubbling of: line 1 - J, line 2 - J, 
 8211:                                   line 3 - B would assign 22 points.  
 8212: 
 8213: =cut
 8214: 
 8215: sub prompt_for_corrections {
 8216:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8217:         $randompick, $respnumlookup, $startline) = @_;
 8218:     my ($current_line,$lines);
 8219:     my @linenums;
 8220:     my $questionnum = $question;
 8221:     my ($first,$responsenum);
 8222:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8223:         $question = $1;
 8224:         my $subquestion = $2;
 8225:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8226:             $responsenum = $respnumlookup->{$question-1};
 8227:             if (ref($startline) eq 'HASH') {
 8228:                 $first = $startline->{$question-1};
 8229:             }
 8230:         } else {
 8231:             $responsenum = $question-1;
 8232:             $first = $first_bubble_line{$responsenum};
 8233:         }
 8234:         $current_line = $first + 1 ;
 8235:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8236:         my $subcount = 1;
 8237:         while ($subcount<$subquestion) {
 8238:             $current_line += $subans[$subcount-1];
 8239:             $subcount ++;
 8240:         }
 8241:         $lines = $subans[$subquestion-1];
 8242:     } else {
 8243:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8244:             $responsenum = $respnumlookup->{$question-1};
 8245:             if (ref($startline) eq 'HASH') {
 8246:                 $first = $startline->{$question-1};
 8247:             }
 8248:         } else {
 8249:             $responsenum = $question-1;
 8250:             $first = $first_bubble_line{$responsenum};
 8251:         }
 8252:         $current_line = $first + 1;
 8253:         $lines        = $bubble_lines_per_response{$responsenum};
 8254:     }
 8255:     if ($lines > 1) {
 8256:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8257:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8258:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8259:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8260:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8261:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8262:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8263:             $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 />');
 8264:         } else {
 8265:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8266:         }
 8267:     }
 8268:     for (my $i =0; $i < $lines; $i++) {
 8269:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8270: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8271: 	        		  $questionnum,$error,split('', $selected));
 8272:         push(@linenums,$current_line);
 8273: 	$current_line++;
 8274:     }
 8275:     if ($lines > 1) {
 8276: 	$r->print("<hr /><br />");
 8277:     }
 8278:     return @linenums;
 8279: }
 8280: 
 8281: =pod
 8282: 
 8283: =item scantron_bubble_selector
 8284:   
 8285:    Generates the html radiobuttons to correct a single bubble line
 8286:    possibly showing the existing the selected bubbles if known
 8287: 
 8288:  Arguments:
 8289:     $r           - Apache request object
 8290:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8291:     $line        - Number of the line being displayed.
 8292:     $questionnum - Question number (may include subquestion)
 8293:     $error       - Type of error.
 8294:     @selected    - Array of bubbles picked on this line.
 8295: 
 8296: =cut
 8297: 
 8298: sub scantron_bubble_selector {
 8299:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8300:     my $max=$$scan_config{'Qlength'};
 8301: 
 8302:     my $scmode=$$scan_config{'Qon'};
 8303:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8304:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8305:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8306:             $max=$$scan_config{'BubblesPerRow'};
 8307:             if (($scmode eq 'number') && ($max > 10)) {
 8308:                 $max = 10;
 8309:             } elsif (($scmode eq 'letter') && $max > 26) {
 8310:                 $max = 26;
 8311:             }
 8312:         } else {
 8313:             $max = 10;
 8314:         }
 8315:     }
 8316: 
 8317:     my @alphabet=('A'..'Z');
 8318:     $r->print(&Apache::loncommon::start_data_table().
 8319:               &Apache::loncommon::start_data_table_row());
 8320:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8321:     for (my $i=0;$i<$max+1;$i++) {
 8322: 	$r->print("\n".'<td align="center">');
 8323: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8324: 	else { $r->print('&nbsp;'); }
 8325: 	$r->print('</td>');
 8326:     }
 8327:     $r->print(&Apache::loncommon::end_data_table_row().
 8328:               &Apache::loncommon::start_data_table_row());
 8329:     for (my $i=0;$i<$max;$i++) {
 8330: 	$r->print("\n".
 8331: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8332: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8333:     }
 8334:     my $nobub_checked = ' ';
 8335:     if ($error eq 'missingbubble') {
 8336:         $nobub_checked = ' checked = "checked" ';
 8337:     }
 8338:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8339: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8340:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8341:               $line.'" value="'.$questionnum.'" /></td>');
 8342:     $r->print(&Apache::loncommon::end_data_table_row().
 8343:               &Apache::loncommon::end_data_table());
 8344: }
 8345: 
 8346: =pod
 8347: 
 8348: =item num_matches
 8349: 
 8350:    Counts the number of characters that are the same between the two arguments.
 8351: 
 8352:  Arguments:
 8353:    $orig - CODE from the scanline
 8354:    $code - CODE to match against
 8355: 
 8356:  Returns:
 8357:    $count - integer count of the number of same characters between the
 8358:             two arguments
 8359: 
 8360: =cut
 8361: 
 8362: sub num_matches {
 8363:     my ($orig,$code) = @_;
 8364:     my @code=split(//,$code);
 8365:     my @orig=split(//,$orig);
 8366:     my $same=0;
 8367:     for (my $i=0;$i<scalar(@code);$i++) {
 8368: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8369:     }
 8370:     return $same;
 8371: }
 8372: 
 8373: =pod
 8374: 
 8375: =item scantron_get_closely_matching_CODEs
 8376: 
 8377:    Cycles through all CODEs and finds the set that has the greatest
 8378:    number of same characters as the provided CODE
 8379: 
 8380:  Arguments:
 8381:    $allcodes - hash ref returned by &get_codes()
 8382:    $CODE     - CODE from the current scanline
 8383: 
 8384:  Returns:
 8385:    2 element list
 8386:     - first elements is number of how closely matching the best fit is 
 8387:       (5 means best set has 5 matching characters)
 8388:     - second element is an arrary ref containing the set of valid CODEs
 8389:       that best fit the passed in CODE
 8390: 
 8391: =cut
 8392: 
 8393: sub scantron_get_closely_matching_CODEs {
 8394:     my ($allcodes,$CODE)=@_;
 8395:     my @CODEs;
 8396:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8397: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8398:     }
 8399: 
 8400:     return ($#CODEs,$CODEs[-1]);
 8401: }
 8402: 
 8403: =pod
 8404: 
 8405: =item get_codes
 8406: 
 8407:    Builds a hash which has keys of all of the valid CODEs from the selected
 8408:    set of remembered CODEs.
 8409: 
 8410:  Arguments:
 8411:   $old_name - name of the set of remembered CODEs
 8412:   $cdom     - domain of the course
 8413:   $cnum     - internal course name
 8414: 
 8415:  Returns:
 8416:   %allcodes - keys are the valid CODEs, values are all 1
 8417: 
 8418: =cut
 8419: 
 8420: sub get_codes {
 8421:     my ($old_name, $cdom, $cnum) = @_;
 8422:     if (!$old_name) {
 8423: 	$old_name=$env{'form.scantron_CODElist'};
 8424:     }
 8425:     if (!$cdom) {
 8426: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8427:     }
 8428:     if (!$cnum) {
 8429: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8430:     }
 8431:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8432: 				    $cdom,$cnum);
 8433:     my %allcodes;
 8434:     if ($result{"type\0$old_name"} eq 'number') {
 8435: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8436:     } else {
 8437: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8438:     }
 8439:     return %allcodes;
 8440: }
 8441: 
 8442: =pod
 8443: 
 8444: =item scantron_validate_CODE
 8445: 
 8446:    Validates all scanlines in the selected file to not have any
 8447:    invalid or underspecified CODEs and that none of the codes are
 8448:    duplicated if this was requested.
 8449: 
 8450: =cut
 8451: 
 8452: sub scantron_validate_CODE {
 8453:     my ($r,$currentphase) = @_;
 8454:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8455:     if ($scantron_config{'CODElocation'} &&
 8456: 	$scantron_config{'CODEstart'} &&
 8457: 	$scantron_config{'CODElength'}) {
 8458: 	if (!defined($env{'form.scantron_CODElist'})) {
 8459: 	    &FIXME_blow_up()
 8460: 	}
 8461:     } else {
 8462: 	return (0,$currentphase+1);
 8463:     }
 8464:     
 8465:     my %usedCODEs;
 8466: 
 8467:     my %allcodes=&get_codes();
 8468: 
 8469:     my $nav_error;
 8470:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8471:     if ($nav_error) {
 8472:         $r->print(&navmap_errormsg());
 8473:         return(1,$currentphase);
 8474:     }
 8475: 
 8476:     my ($scanlines,$scan_data)=&scantron_getfile();
 8477:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8478: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8479: 	if ($line=~/^[\s\cz]*$/) { next; }
 8480: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8481: 						 $scan_data);
 8482: 	my $CODE=$$scan_record{'scantron.CODE'};
 8483: 	my $error=0;
 8484: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8485: 	    &scantron_get_correction($r,$i,$scan_record,
 8486: 				     \%scantron_config,
 8487: 				     $line,'incorrectCODE',\%allcodes);
 8488: 	    return(1,$currentphase);
 8489: 	}
 8490: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8491: 	    && !$$scan_record{'scantron.useCODE'}) {
 8492: 	    &scantron_get_correction($r,$i,$scan_record,
 8493: 				     \%scantron_config,
 8494: 				     $line,'incorrectCODE',\%allcodes);
 8495: 	    return(1,$currentphase);
 8496: 	}
 8497: 	if (exists($usedCODEs{$CODE}) 
 8498: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8499: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8500: 	    &scantron_get_correction($r,$i,$scan_record,
 8501: 				     \%scantron_config,
 8502: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8503: 	    return(1,$currentphase);
 8504: 	}
 8505: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8506:     }
 8507:     return (0,$currentphase+1);
 8508: }
 8509: 
 8510: =pod
 8511: 
 8512: =item scantron_validate_doublebubble
 8513: 
 8514:    Validates all scanlines in the selected file to not have any
 8515:    bubble lines with multiple bubbles marked.
 8516: 
 8517: =cut
 8518: 
 8519: sub scantron_validate_doublebubble {
 8520:     my ($r,$currentphase) = @_;
 8521:     #get student info
 8522:     my $classlist=&Apache::loncoursedata::get_classlist();
 8523:     my %idmap=&username_to_idmap($classlist);
 8524:     my (undef,undef,$sequence)=
 8525:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8526: 
 8527:     #get scantron line setup
 8528:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8529:     my ($scanlines,$scan_data)=&scantron_getfile();
 8530: 
 8531:     my $navmap = Apache::lonnavmaps::navmap->new();
 8532:     unless (ref($navmap)) {
 8533:         $r->print(&navmap_errormsg());
 8534:         return(1,$currentphase);
 8535:     }
 8536:     my $map=$navmap->getResourceByUrl($sequence);
 8537:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8538:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8539:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8540:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8541: 
 8542:     my $nav_error;
 8543:     if (ref($map)) {
 8544:         $randomorder = $map->randomorder();
 8545:         $randompick = $map->randompick();
 8546:         unless ($randomorder || $randompick) {
 8547:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8548:                 if ($res->randomorder()) {
 8549:                     $randomorder = 1;
 8550:                 }
 8551:                 if ($res->randompick()) {
 8552:                     $randompick = 1;
 8553:                 }
 8554:                 last if ($randomorder || $randompick);
 8555:             }
 8556:         }
 8557:         if ($randomorder || $randompick) {
 8558:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8559:             if ($nav_error) {
 8560:                 $r->print(&navmap_errormsg());
 8561:                 return(1,$currentphase);
 8562:             }
 8563:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8564:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8565:         }
 8566:     } else {
 8567:         $r->print(&navmap_errormsg());
 8568:         return(1,$currentphase);
 8569:     }
 8570: 
 8571:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8572:     if ($nav_error) {
 8573:         $r->print(&navmap_errormsg());
 8574:         return(1,$currentphase);
 8575:     }
 8576: 
 8577:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8578: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8579: 	if ($line=~/^[\s\cz]*$/) { next; }
 8580: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8581: 						 $scan_data,undef,\%idmap,$randomorder,
 8582:                                                  $randompick,$sequence,\@master_seq,
 8583:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8584:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8585: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8586: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8587: 				 'doublebubble',
 8588: 				 $$scan_record{'scantron.doubleerror'},
 8589:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8590:     	return (1,$currentphase);
 8591:     }
 8592:     return (0,$currentphase+1);
 8593: }
 8594: 
 8595: 
 8596: sub scantron_get_maxbubble {
 8597:     my ($nav_error,$scantron_config) = @_;
 8598:     if (defined($env{'form.scantron_maxbubble'}) &&
 8599: 	$env{'form.scantron_maxbubble'}) {
 8600: 	&restore_bubble_lines();
 8601: 	return $env{'form.scantron_maxbubble'};
 8602:     }
 8603: 
 8604:     my (undef, undef, $sequence) =
 8605: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8606: 
 8607:     my $navmap=Apache::lonnavmaps::navmap->new();
 8608:     unless (ref($navmap)) {
 8609:         if (ref($nav_error)) {
 8610:             $$nav_error = 1;
 8611:         }
 8612:         return;
 8613:     }
 8614:     my $map=$navmap->getResourceByUrl($sequence);
 8615:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8616:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8617: 
 8618:     &Apache::lonxml::clear_problem_counter();
 8619: 
 8620:     my $uname       = $env{'user.name'};
 8621:     my $udom        = $env{'user.domain'};
 8622:     my $cid         = $env{'request.course.id'};
 8623:     my $total_lines = 0;
 8624:     %bubble_lines_per_response = ();
 8625:     %first_bubble_line         = ();
 8626:     %subdivided_bubble_lines   = ();
 8627:     %responsetype_per_response = ();
 8628:     %masterseq_id_responsenum  = ();
 8629: 
 8630:     my $response_number = 0;
 8631:     my $bubble_line     = 0;
 8632:     foreach my $resource (@resources) {
 8633:         my $resid = $resource->id();
 8634:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8635:                                                           $udom,undef,$bubbles_per_row);
 8636:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8637: 	    foreach my $part_id (@{$parts}) {
 8638:                 my $lines;
 8639: 
 8640: 	        # TODO - make this a persistent hash not an array.
 8641: 
 8642:                 # optionresponse, matchresponse and rankresponse type items 
 8643:                 # render as separate sub-questions in exam mode.
 8644:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8645:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8646:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8647:                     my ($numbub,$numshown);
 8648:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8649:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8650:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8651:                         }
 8652:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8653:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8654:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8655:                         }
 8656:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8657:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8658:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8659:                         }
 8660:                     }
 8661:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8662:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8663:                     }
 8664:                     my $bubbles_per_row =
 8665:                         &bubblesheet_bubbles_per_row($scantron_config);
 8666:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8667:                     if (($numbub % $bubbles_per_row) != 0) {
 8668:                         $inner_bubble_lines++;
 8669:                     }
 8670:                     for (my $i=0; $i<$numshown; $i++) {
 8671:                         $subdivided_bubble_lines{$response_number} .= 
 8672:                             $inner_bubble_lines.',';
 8673:                     }
 8674:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8675:                     $lines = $numshown * $inner_bubble_lines;
 8676:                 } else {
 8677:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8678:                 }
 8679: 
 8680:                 $first_bubble_line{$response_number} = $bubble_line;
 8681: 	        $bubble_lines_per_response{$response_number} = $lines;
 8682:                 $responsetype_per_response{$response_number} = 
 8683:                     $analysis->{$part_id.'.type'};
 8684:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8685: 	        $response_number++;
 8686: 
 8687: 	        $bubble_line +=  $lines;
 8688: 	        $total_lines +=  $lines;
 8689: 	    }
 8690:         }
 8691:     }
 8692:     &Apache::lonnet::delenv('scantron.');
 8693: 
 8694:     &save_bubble_lines();
 8695:     $env{'form.scantron_maxbubble'} =
 8696: 	$total_lines;
 8697:     return $env{'form.scantron_maxbubble'};
 8698: }
 8699: 
 8700: sub bubblesheet_bubbles_per_row {
 8701:     my ($scantron_config) = @_;
 8702:     my $bubbles_per_row;
 8703:     if (ref($scantron_config) eq 'HASH') {
 8704:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8705:     }
 8706:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8707:         $bubbles_per_row = 10;
 8708:     }
 8709:     return $bubbles_per_row;
 8710: }
 8711: 
 8712: sub scantron_validate_missingbubbles {
 8713:     my ($r,$currentphase) = @_;
 8714:     #get student info
 8715:     my $classlist=&Apache::loncoursedata::get_classlist();
 8716:     my %idmap=&username_to_idmap($classlist);
 8717:     my (undef,undef,$sequence)=
 8718:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8719: 
 8720:     #get scantron line setup
 8721:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8722:     my ($scanlines,$scan_data)=&scantron_getfile();
 8723: 
 8724:     my $navmap = Apache::lonnavmaps::navmap->new();
 8725:     unless (ref($navmap)) {
 8726:         $r->print(&navmap_errormsg());
 8727:         return(1,$currentphase);
 8728:     }
 8729: 
 8730:     my $map=$navmap->getResourceByUrl($sequence);
 8731:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8732:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8733:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8734:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8735: 
 8736:     my $nav_error;
 8737:     if (ref($map)) {
 8738:         $randomorder = $map->randomorder();
 8739:         $randompick = $map->randompick();
 8740:         unless ($randomorder || $randompick) {
 8741:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8742:                 if ($res->randomorder()) {
 8743:                     $randomorder = 1;
 8744:                 }
 8745:                 if ($res->randompick()) {
 8746:                     $randompick = 1;
 8747:                 }
 8748:                 last if ($randomorder || $randompick);
 8749:             }
 8750:         }
 8751:         if ($randomorder || $randompick) {
 8752:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8753:             if ($nav_error) {
 8754:                 $r->print(&navmap_errormsg());
 8755:                 return(1,$currentphase);
 8756:             }
 8757:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8758:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8759:         }
 8760:     } else {
 8761:         $r->print(&navmap_errormsg());
 8762:         return(1,$currentphase);
 8763:     }
 8764: 
 8765: 
 8766:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8767:     if ($nav_error) {
 8768:         $r->print(&navmap_errormsg());
 8769:         return(1,$currentphase);
 8770:     }
 8771: 
 8772:     if (!$max_bubble) { $max_bubble=2**31; }
 8773:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8774: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8775: 	if ($line=~/^[\s\cz]*$/) { next; }
 8776:         my $scan_record =
 8777:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8778:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8779:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8780:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8781: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8782: 	my @to_correct;
 8783: 	
 8784: 	# Probably here's where the error is...
 8785: 
 8786: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8787:             my $lastbubble;
 8788:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8789:                 my $question = $1;
 8790:                 my $subquestion = $2;
 8791:                 my ($first,$responsenum);
 8792:                 if ($randomorder || $randompick) {
 8793:                     $responsenum = $respnumlookup{$question-1};
 8794:                     $first = $startline{$question-1};
 8795:                 } else {
 8796:                     $responsenum = $question-1;
 8797:                     $first = $first_bubble_line{$responsenum};
 8798:                 }
 8799:                 if (!defined($first)) { next; }
 8800:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8801:                 my $subcount = 1;
 8802:                 while ($subcount<$subquestion) {
 8803:                     $first += $subans[$subcount-1];
 8804:                     $subcount ++;
 8805:                 }
 8806:                 my $count = $subans[$subquestion-1];
 8807:                 $lastbubble = $first + $count;
 8808:             } else {
 8809:                 my ($first,$responsenum);
 8810:                 if ($randomorder || $randompick) {
 8811:                     $responsenum = $respnumlookup{$missing-1};
 8812:                     $first = $startline{$missing-1};
 8813:                 } else {
 8814:                     $responsenum = $missing-1;
 8815:                     $first = $first_bubble_line{$responsenum};
 8816:                 }
 8817:                 if (!defined($first)) { next; }
 8818:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8819:             }
 8820:             if ($lastbubble > $max_bubble) { next; }
 8821: 	    push(@to_correct,$missing);
 8822: 	}
 8823: 	if (@to_correct) {
 8824: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8825: 				     $line,'missingbubble',\@to_correct,
 8826:                                      $randomorder,$randompick,\%respnumlookup,
 8827:                                      \%startline);
 8828: 	    return (1,$currentphase);
 8829: 	}
 8830: 
 8831:     }
 8832:     return (0,$currentphase+1);
 8833: }
 8834: 
 8835: sub hand_bubble_option {
 8836:     my (undef, undef, $sequence) =
 8837:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8838:     return if ($sequence eq '');
 8839:     my $navmap = Apache::lonnavmaps::navmap->new();
 8840:     unless (ref($navmap)) {
 8841:         return;
 8842:     }
 8843:     my $needs_hand_bubbles;
 8844:     my $map=$navmap->getResourceByUrl($sequence);
 8845:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8846:     foreach my $res (@resources) {
 8847:         if (ref($res)) {
 8848:             if ($res->is_problem()) {
 8849:                 my $partlist = $res->parts();
 8850:                 foreach my $part (@{ $partlist }) {
 8851:                     my @types = $res->responseType($part);
 8852:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8853:                         $needs_hand_bubbles = 1;
 8854:                         last;
 8855:                     }
 8856:                 }
 8857:             }
 8858:         }
 8859:     }
 8860:     if ($needs_hand_bubbles) {
 8861:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8862:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8863:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8864:                &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 />').
 8865:                '<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;'.
 8866:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8867:     }
 8868:     return;
 8869: }
 8870: 
 8871: sub scantron_process_students {
 8872:     my ($r,$symb) = @_;
 8873: 
 8874:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8875:     if (!$symb) {
 8876: 	return '';
 8877:     }
 8878:     my $default_form_data=&defaultFormData($symb);
 8879: 
 8880:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8881:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8882:     my ($scanlines,$scan_data)=&scantron_getfile();
 8883:     my $classlist=&Apache::loncoursedata::get_classlist();
 8884:     my %idmap=&username_to_idmap($classlist);
 8885:     my $navmap=Apache::lonnavmaps::navmap->new();
 8886:     unless (ref($navmap)) {
 8887:         $r->print(&navmap_errormsg());
 8888:         return '';
 8889:     }
 8890:     my $map=$navmap->getResourceByUrl($sequence);
 8891:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8892:         %grader_randomlists_by_symb,%symb_for_examcode);
 8893:     if (ref($map)) {
 8894:         $randomorder = $map->randomorder();
 8895:         $randompick = $map->randompick();
 8896:         unless ($randomorder || $randompick) {
 8897:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8898:                 if ($res->randomorder()) {
 8899:                     $randomorder = 1;
 8900:                 }
 8901:                 if ($res->randompick()) {
 8902:                     $randompick = 1;
 8903:                 }
 8904:                 last if ($randomorder || $randompick);
 8905:             }
 8906:         }
 8907:     } else {
 8908:         $r->print(&navmap_errormsg());
 8909:         return '';
 8910:     }
 8911:     my $nav_error;
 8912:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8913:     if ($randomorder || $randompick) {
 8914:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
 8915:         if ($nav_error) {
 8916:             $r->print(&navmap_errormsg());
 8917:             return '';
 8918:         }
 8919:     }
 8920:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8921:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8922: 
 8923:     my ($uname,$udom);
 8924:     my $result= <<SCANTRONFORM;
 8925: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8926:   <input type="hidden" name="command" value="scantron_configphase" />
 8927:   $default_form_data
 8928: SCANTRONFORM
 8929:     $r->print($result);
 8930: 
 8931:     my @delayqueue;
 8932:     my (%completedstudents,%scandata);
 8933:     
 8934:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8935:     my $count=&get_todo_count($scanlines,$scan_data);
 8936:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8937:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8938:     $r->print('<br />');
 8939:     my $start=&Time::HiRes::time();
 8940:     my $i=-1;
 8941:     my $started;
 8942: 
 8943:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8944:     if ($nav_error) {
 8945:         $r->print(&navmap_errormsg());
 8946:         return '';
 8947:     }
 8948: 
 8949:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8950:     # the user and return.
 8951: 
 8952:     if ($ssi_error) {
 8953: 	$r->print("</form>");
 8954: 	&ssi_print_error($r);
 8955:         &Apache::lonnet::remove_lock($lock);
 8956: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8957:     }
 8958: 
 8959:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8960:     my $numletts = scalar(keys(%lettdig));
 8961:     my %orderedforcode;
 8962: 
 8963:     while ($i<$scanlines->{'count'}) {
 8964:  	($uname,$udom)=('','');
 8965:  	$i++;
 8966:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8967:  	if ($line=~/^[\s\cz]*$/) { next; }
 8968: 	if ($started) {
 8969: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8970: 	}
 8971: 	$started=1;
 8972:         my %respnumlookup = ();
 8973:         my %startline = ();
 8974:         my $total;
 8975:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8976:  						 $scan_data,undef,\%idmap,$randomorder,
 8977:                                                  $randompick,$sequence,\@master_seq,
 8978:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8979:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8980:                                                  \$total);
 8981:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8982:  					      \%idmap,$i)) {
 8983:   	    &scantron_add_delay(\@delayqueue,$line,
 8984:  				'Unable to find a student that matches',1);
 8985:  	    next;
 8986:   	}
 8987:  	if (exists $completedstudents{$uname}) {
 8988:  	    &scantron_add_delay(\@delayqueue,$line,
 8989:  				'Student '.$uname.' has multiple sheets',2);
 8990:  	    next;
 8991:  	}
 8992:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8993:         my $user = $uname.':'.$usec;
 8994:   	($uname,$udom)=split(/:/,$uname);
 8995: 
 8996:         my $scancode;
 8997:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8998:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8999:             $scancode = $scan_record->{'scantron.CODE'};
 9000:         } else {
 9001:             $scancode = '';
 9002:         }
 9003: 
 9004:         my @mapresources = @resources;
 9005:         if ($randomorder || $randompick) {
 9006:             @mapresources =
 9007:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9008:                              \%orderedforcode);
 9009:         }
 9010:         my (%partids_by_symb,$res_error);
 9011:         foreach my $resource (@mapresources) {
 9012:             my $ressymb;
 9013:             if (ref($resource)) {
 9014:                 $ressymb = $resource->symb();
 9015:             } else {
 9016:                 $res_error = 1;
 9017:                 last;
 9018:             }
 9019:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9020:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9021:                 my $currcode;
 9022:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9023:                     $currcode = $scancode;
 9024:                 }
 9025:                 my ($analysis,$parts) =
 9026:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9027:                                               $uname,$udom,undef,$bubbles_per_row,
 9028:                                               $currcode);
 9029:                 $partids_by_symb{$ressymb} = $parts;
 9030:             } else {
 9031:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9032:             }
 9033:         }
 9034: 
 9035:         if ($res_error) {
 9036:             &scantron_add_delay(\@delayqueue,$line,
 9037:                                 'An error occurred while grading student '.$uname,2);
 9038:             next;
 9039:         }
 9040: 
 9041: 	&Apache::lonxml::clear_problem_counter();
 9042:   	&Apache::lonnet::appenv($scan_record);
 9043: 
 9044: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9045: 	    &scantron_putfile($scanlines,$scan_data);
 9046: 	}
 9047: 	
 9048:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9049:                                    \@mapresources,\%partids_by_symb,
 9050:                                    $bubbles_per_row,$randomorder,$randompick,
 9051:                                    \%respnumlookup,\%startline) 
 9052:             eq 'ssi_error') {
 9053:             $ssi_error = 0; # So end of handler error message does not trigger.
 9054:             $r->print("</form>");
 9055:             &ssi_print_error($r);
 9056:             &Apache::lonnet::remove_lock($lock);
 9057:             return '';      # Why return ''?  Beats me.
 9058:         }
 9059: 
 9060:         if (($scancode) && ($randomorder || $randompick)) {
 9061:             foreach my $key (keys(%symb_for_examcode)) {
 9062:                 my $symb_in_map = $symb_for_examcode{$key};
 9063:                 if ($symb_in_map ne '') {
 9064:                     my $parmresult =
 9065:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
 9066:                                                                '0_examcode',2,$scancode,
 9067:                                                                'string_examcode',$uname,
 9068:                                                                $udom);
 9069:                 }
 9070:             }
 9071:         }
 9072: 	$completedstudents{$uname}={'line'=>$line};
 9073:         if ($env{'form.verifyrecord'}) {
 9074:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9075:             if ($randompick) {
 9076:                 if ($total) {
 9077:                     $lastpos = $total*$scantron_config{'Qlength'};
 9078:                 }
 9079:             }
 9080: 
 9081:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9082:             chomp($studentdata);
 9083:             $studentdata =~ s/\r$//;
 9084:             my $studentrecord = '';
 9085:             my $counter = -1;
 9086:             foreach my $resource (@mapresources) {
 9087:                 my $ressymb = $resource->symb();
 9088:                 ($counter,my $recording) =
 9089:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9090:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9091:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9092:                                              $randompick,\%respnumlookup,\%startline);
 9093:                 $studentrecord .= $recording;
 9094:             }
 9095:             if ($studentrecord ne $studentdata) {
 9096:                 &Apache::lonxml::clear_problem_counter();
 9097:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9098:                                            \@mapresources,\%partids_by_symb,
 9099:                                            $bubbles_per_row,$randomorder,$randompick,
 9100:                                            \%respnumlookup,\%startline)
 9101:                     eq 'ssi_error') {
 9102:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9103:                     $r->print("</form>");
 9104:                     &ssi_print_error($r);
 9105:                     &Apache::lonnet::remove_lock($lock);
 9106:                     delete($completedstudents{$uname});
 9107:                     return '';
 9108:                 }
 9109:                 $counter = -1;
 9110:                 $studentrecord = '';
 9111:                 foreach my $resource (@mapresources) {
 9112:                     my $ressymb = $resource->symb();
 9113:                     ($counter,my $recording) =
 9114:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9115:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9116:                                                  \%scantron_config,\%lettdig,$numletts,
 9117:                                                  $randomorder,$randompick,\%respnumlookup,
 9118:                                                  \%startline);
 9119:                     $studentrecord .= $recording;
 9120:                 }
 9121:                 if ($studentrecord ne $studentdata) {
 9122:                     $r->print('<p><span class="LC_warning">');
 9123:                     if ($scancode eq '') {
 9124:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9125:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9126:                     } else {
 9127:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9128:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9129:                     }
 9130:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9131:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9132:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9133:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9134:                               &Apache::loncommon::start_data_table_row().
 9135:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9136:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9137:                               &Apache::loncommon::end_data_table_row().
 9138:                               &Apache::loncommon::start_data_table_row().
 9139:                               '<td>'.&mt('Stored submissions').'</td>'.
 9140:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9141:                               &Apache::loncommon::end_data_table_row().
 9142:                               &Apache::loncommon::end_data_table().'</p>');
 9143:                 } else {
 9144:                     $r->print('<br /><span class="LC_warning">'.
 9145:                              &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 />'.
 9146:                              &mt("As a consequence, this user's submission history records two tries.").
 9147:                                  '</span><br />');
 9148:                 }
 9149:             }
 9150:         }
 9151:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9152:     } continue {
 9153: 	&Apache::lonxml::clear_problem_counter();
 9154: 	&Apache::lonnet::delenv('scantron.');
 9155:     }
 9156:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9157:     &Apache::lonnet::remove_lock($lock);
 9158: #    my $lasttime = &Time::HiRes::time()-$start;
 9159: #    $r->print("<p>took $lasttime</p>");
 9160: 
 9161:     $r->print("</form>");
 9162:     return '';
 9163: }
 9164: 
 9165: sub graders_resources_pass {
 9166:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9167:         $bubbles_per_row) = @_;
 9168:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9169:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9170:         foreach my $resource (@{$resources}) {
 9171:             my $ressymb = $resource->symb();
 9172:             my ($analysis,$parts) =
 9173:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9174:                                           $env{'user.name'},$env{'user.domain'},
 9175:                                           1,$bubbles_per_row);
 9176:             $grader_partids_by_symb->{$ressymb} = $parts;
 9177:             if (ref($analysis) eq 'HASH') {
 9178:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9179:                     $grader_randomlists_by_symb->{$ressymb} =
 9180:                         $analysis->{'parts_withrandomlist'};
 9181:                 }
 9182:             }
 9183:         }
 9184:     }
 9185:     return;
 9186: }
 9187: 
 9188: =pod
 9189: 
 9190: =item users_order
 9191: 
 9192:   Returns array of resources in current map, ordered based on either CODE,
 9193:   if this is a CODEd exam, or based on student's identity if this is a
 9194:   "NAMEd" exam.
 9195: 
 9196:   Should be used when randomorder and/or randompick applied when the 
 9197:   corresponding exam was printed, prior to students completing bubblesheets 
 9198:   for the version of the exam the student received.
 9199: 
 9200: =cut
 9201: 
 9202: sub users_order  {
 9203:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9204:     my @mapresources;
 9205:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9206:         return @mapresources;
 9207:     }
 9208:     if ($scancode) {
 9209:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9210:             @mapresources = @{$orderedforcode->{$scancode}};
 9211:         } else {
 9212:             $env{'form.CODE'} = $scancode;
 9213:             my $actual_seq =
 9214:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9215:                                                                $master_seq,
 9216:                                                                $user,$scancode,1);
 9217:             if (ref($actual_seq) eq 'ARRAY') {
 9218:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9219:                 if (ref($orderedforcode) eq 'HASH') {
 9220:                     if (@mapresources > 0) {
 9221:                         $orderedforcode->{$scancode} = \@mapresources;
 9222:                     }
 9223:                 }
 9224:             }
 9225:             delete($env{'form.CODE'});
 9226:         }
 9227:     } else {
 9228:         my $actual_seq =
 9229:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9230:                                                            $master_seq,
 9231:                                                            $user,undef,1);
 9232:         if (ref($actual_seq) eq 'ARRAY') {
 9233:             @mapresources =
 9234:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9235:         }
 9236:     }
 9237:     return @mapresources;
 9238: }
 9239: 
 9240: sub grade_student_bubbles {
 9241:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9242:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9243:     my $uselookup = 0;
 9244:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9245:         (ref($startline) eq 'HASH')) {
 9246:         $uselookup = 1;
 9247:     }
 9248: 
 9249:     if (ref($resources) eq 'ARRAY') {
 9250:         my $count = 0;
 9251:         foreach my $resource (@{$resources}) {
 9252:             my $ressymb = $resource->symb();
 9253:             my %form = ('submitted'      => 'scantron',
 9254:                         'grade_target'   => 'grade',
 9255:                         'grade_username' => $uname,
 9256:                         'grade_domain'   => $udom,
 9257:                         'grade_courseid' => $env{'request.course.id'},
 9258:                         'grade_symb'     => $ressymb,
 9259:                         'CODE'           => $scancode
 9260:                        );
 9261:             if ($bubbles_per_row ne '') {
 9262:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9263:             }
 9264:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9265:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9266:             }
 9267:             if (ref($parts) eq 'HASH') {
 9268:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9269:                     foreach my $part (@{$parts->{$ressymb}}) {
 9270:                         if ($uselookup) {
 9271:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9272:                         } else {
 9273:                             $form{'scantron_questnum_start.'.$part} =
 9274:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9275:                         }
 9276:                         $count++;
 9277:                     }
 9278:                 }
 9279:             }
 9280:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9281:             return 'ssi_error' if ($ssi_error);
 9282:             last if (&Apache::loncommon::connection_aborted($r));
 9283:         }
 9284:     }
 9285:     return;
 9286: }
 9287: 
 9288: sub scantron_upload_scantron_data {
 9289:     my ($r,$symb) = @_;
 9290:     my $dom = $env{'request.role.domain'};
 9291:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9292:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9293:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9294:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9295: 							  'domainid',
 9296: 							  'coursename',$dom);
 9297:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9298:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9299:     my $default_form_data=&defaultFormData($symb);
 9300:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9301:     &js_escape(\$nofile_alert);
 9302:     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.");
 9303:     &js_escape(\$nocourseid_alert);
 9304:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9305:     function checkUpload(formname) {
 9306: 	if (formname.upfile.value == "") {
 9307: 	    alert("'.$nofile_alert.'");
 9308: 	    return false;
 9309: 	}
 9310:         if (formname.courseid.value == "") {
 9311:             alert("'.$nocourseid_alert.'");
 9312:             return false;
 9313:         }
 9314: 	formname.submit();
 9315:     }
 9316: 
 9317:     function ToSyllabus() {
 9318:         var cdom = '."'$dom'".';
 9319:         var cnum = document.rules.courseid.value;
 9320:         if (cdom == "" || cdom == null) {
 9321:             return;
 9322:         }
 9323:         if (cnum == "" || cnum == null) {
 9324:            return;
 9325:         }
 9326:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9327:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9328:         return;
 9329:     }
 9330: 
 9331:     '.$formatjs.'
 9332: '));
 9333:     $r->print('
 9334: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9335: 
 9336: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9337: '.$default_form_data.
 9338:   &Apache::lonhtmlcommon::start_pick_box().
 9339:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9340:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9341:   &Apache::lonhtmlcommon::row_closure().
 9342:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9343:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9344:   &Apache::lonhtmlcommon::row_closure().
 9345:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9346:   '<input name="domainid" type="hidden" />'.$domdesc.
 9347:   &Apache::lonhtmlcommon::row_closure());
 9348:     if ($formatoptions) {
 9349:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9350:                   &Apache::lonhtmlcommon::row_closure());
 9351:     }
 9352:     $r->print(
 9353:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9354:   '<input type="file" name="upfile" size="50" />'.
 9355:   &Apache::lonhtmlcommon::row_closure(1).
 9356:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9357: 
 9358: <input name="command" value="scantronupload_save" type="hidden" />
 9359: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9360: </form>
 9361: ');
 9362:     return '';
 9363: }
 9364: 
 9365: sub scantron_upload_dataformat {
 9366:     my ($dom) = @_;
 9367:     my ($formatoptions,$formattitle,$formatjs);
 9368:     $formatjs = <<'END';
 9369: function toggleScantab(form) {
 9370:    return;
 9371: }
 9372: END
 9373:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9374:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9375:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9376:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9377:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9378:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9379:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9380:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9381:                             my ($onclick,$formatextra,$singleline);
 9382:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9383:                             my $count = 0;
 9384:                             foreach my $line (@lines) {
 9385:                                 next if (($line =~ /^\#/) || ($line eq ''));
 9386:                                 $singleline = $line;
 9387:                                 $count ++;
 9388:                             }
 9389:                             if ($count > 1) {
 9390:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9391:                                                '<span class="LC_nobreak">'.
 9392:                                                &mt('Bubblesheet type').':&nbsp;'.
 9393:                                                &scantron_scantab().'</span></div>';
 9394:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9395:                                 $formatjs = <<"END";
 9396: function toggleScantab(form) {
 9397:     var divid = 'bubbletype';
 9398:     if (document.getElementById(divid)) {
 9399:         var radioname = 'fileformat';
 9400:         var num = form.elements[radioname].length;
 9401:         if (num) {
 9402:             for (var i=0; i<num; i++) {
 9403:                 if (form.elements[radioname][i].checked) {
 9404:                     var chosen = form.elements[radioname][i].value;
 9405:                     if (chosen == 'dat') {
 9406:                         document.getElementById(divid).style.display = 'none';
 9407:                     } else if (chosen == 'csv') {
 9408:                         document.getElementById(divid).style.display = 'block';
 9409:                     }
 9410:                 }
 9411:             }
 9412:         }
 9413:     }
 9414:     return;
 9415: }
 9416: 
 9417: END
 9418:                             } elsif ($count == 1) {
 9419:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9420:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9421:                             }
 9422:                             $formattitle = &mt('File format');
 9423:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9424:                                              &mt('Plain Text (no delimiters)').
 9425:                                              '</label>'.('&nbsp;'x2).
 9426:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9427:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9428:                         }
 9429:                     }
 9430:                 }
 9431:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9432:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9433:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9434:                         $formattitle = &mt('Bubblesheet type');
 9435:                         $formatoptions = &scantron_scantab();
 9436:                     }
 9437:                 }
 9438:             }
 9439:         }
 9440:     }
 9441:     return ($formatoptions,$formattitle,$formatjs);
 9442: }
 9443: 
 9444: sub scantron_upload_scantron_data_save {
 9445:     my ($r,$symb) = @_;
 9446:     my $doanotherupload=
 9447: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9448: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9449: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9450: 	'</form>'."\n";
 9451:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9452: 	!&Apache::lonnet::allowed('usc',
 9453: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9454: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9455:         unless ($symb) {
 9456: 	    $r->print($doanotherupload);
 9457: 	}
 9458: 	return '';
 9459:     }
 9460:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9461:     my $uploadedfile;
 9462:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9463:     if (length($env{'form.upfile'}) < 2) {
 9464:         $r->print(
 9465:             &Apache::lonhtmlcommon::confirm_success(
 9466:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9467:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9468:     } else {
 9469:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9470:         my $parser;
 9471:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9472:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9473:                 my $is_csv;
 9474:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9475:                 if (@possibles > 1) {
 9476:                     if ($env{'form.fileformat'} eq 'csv') {
 9477:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9478:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9479:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9480:                                     $is_csv = 1;
 9481:                                 }
 9482:                             }
 9483:                         }
 9484:                     }
 9485:                 } elsif (@possibles == 1) {
 9486:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9487:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9488:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9489:                                 $is_csv = 1;
 9490:                             }
 9491:                         }
 9492:                     }
 9493:                 }
 9494:                 if ($is_csv) {
 9495:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9496:                 }
 9497:             }
 9498:         }
 9499:         my $result =
 9500:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9501:                                             $env{'form.courseid'},$env{'form.domainid'});
 9502: 	if ($result =~ m{^/uploaded/}) {
 9503:             $r->print(
 9504:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9505:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9506:                         (length($env{'form.upfile'})-1),
 9507:                         '<span class="LC_filename">'.$result.'</span>'));
 9508:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9509:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9510:                                                        $env{'form.courseid'},$uploadedfile));
 9511: 	} else {
 9512:             $r->print(
 9513:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9514:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9515:                           $result,
 9516: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9517: 	}
 9518:     }
 9519:     if ($symb) {
 9520: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9521:     } else {
 9522: 	$r->print($doanotherupload);
 9523:     }
 9524:     return '';
 9525: }
 9526: 
 9527: sub validate_uploaded_scantron_file {
 9528:     my ($cdom,$cname,$fname) = @_;
 9529:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9530:     my @lines;
 9531:     if ($scanlines ne '-1') {
 9532:         @lines=split("\n",$scanlines,-1);
 9533:     }
 9534:     my $output;
 9535:     if (@lines) {
 9536:         my (%counts,$max_match_format);
 9537:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9538:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9539:         my %idmap = &username_to_idmap($classlist);
 9540:         foreach my $key (keys(%idmap)) {
 9541:             my $lckey = lc($key);
 9542:             $idmap{$lckey} = $idmap{$key};
 9543:         }
 9544:         my %unique_formats;
 9545:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9546:         foreach my $line (@formatlines) {
 9547:             next if (($line =~ /^\#/) || ($line eq ''));
 9548:             my @config = split(/:/,$line);
 9549:             my $idstart = $config[5];
 9550:             my $idlength = $config[6];
 9551:             if (($idstart ne '') && ($idlength > 0)) {
 9552:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9553:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9554:                 } else {
 9555:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9556:                 }
 9557:             }
 9558:         }
 9559:         foreach my $key (keys(%unique_formats)) {
 9560:             my ($idstart,$idlength) = split(':',$key);
 9561:             %{$counts{$key}} = (
 9562:                                'found'   => 0,
 9563:                                'total'   => 0,
 9564:                               );
 9565:             foreach my $line (@lines) {
 9566:                 next if ($line =~ /^#/);
 9567:                 next if ($line =~ /^[\s\cz]*$/);
 9568:                 my $id = substr($line,$idstart-1,$idlength);
 9569:                 $id = lc($id);
 9570:                 if (exists($idmap{$id})) {
 9571:                     $counts{$key}{'found'} ++;
 9572:                 }
 9573:                 $counts{$key}{'total'} ++;
 9574:             }
 9575:             if ($counts{$key}{'total'}) {
 9576:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9577:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9578:                     $max_match_pct = $percent_match;
 9579:                     $max_match_format = $key;
 9580:                     $found_match_count = $counts{$key}{'found'};
 9581:                     $max_match_count = $counts{$key}{'total'};
 9582:                 }
 9583:             }
 9584:         }
 9585:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9586:             my $format_descs;
 9587:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9588:             for (my $i=0; $i<$numwithformat; $i++) {
 9589:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9590:                 if ($i<$numwithformat-2) {
 9591:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9592:                 } elsif ($i==$numwithformat-2) {
 9593:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9594:                 } elsif ($i==$numwithformat-1) {
 9595:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9596:                 }
 9597:             }
 9598:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9599:             $output .= '<br />';
 9600:             if ($found_match_count == $max_match_count) {
 9601:                 # 100% matching entries
 9602:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9603:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9604:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9605:                 &mt('Comparison of student IDs in the uploaded file with'.
 9606:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9607:                     ' in the file (for the format defined for [_3]).',
 9608:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9609:             } else {
 9610:                 # Not all entries matching? -> Show warning and additional info
 9611:                 $output .=
 9612:                     &Apache::lonhtmlcommon::confirm_success(
 9613:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9614:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9615:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9616:                     &mt('Comparison of student IDs in the uploaded file with'.
 9617:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9618:                         ' in the file (for the format defined for [_3]).',
 9619:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9620:                     '<p class="LC_info">'.
 9621:                     &mt('A low percentage of matches results from one of the following:').
 9622:                     '</p><ul>'.
 9623:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9624:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9625:                                '<i>'.$cdom.'</i>').'</li>'.
 9626:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9627:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9628:                     '</ul>';
 9629:             }
 9630:         }
 9631:     } else {
 9632:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9633:     }
 9634:     return $output;
 9635: }
 9636: 
 9637: sub valid_file {
 9638:     my ($requested_file)=@_;
 9639:     foreach my $filename (sort(&scantron_filenames())) {
 9640: 	if ($requested_file eq $filename) { return 1; }
 9641:     }
 9642:     return 0;
 9643: }
 9644: 
 9645: sub scantron_download_scantron_data {
 9646:     my ($r,$symb) = @_;
 9647:     my $default_form_data=&defaultFormData($symb);
 9648:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9649:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9650:     my $file=$env{'form.scantron_selectfile'};
 9651:     if (! &valid_file($file)) {
 9652: 	$r->print('
 9653: 	<p>
 9654: 	    '.&mt('The requested filename was invalid.').'
 9655:         </p>
 9656: ');
 9657: 	return;
 9658:     }
 9659:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9660:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9661:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9662:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9663:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9664:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9665:     $r->print('
 9666:     <p>
 9667: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9668: 	      '<a href="'.$orig.'">','</a>').'
 9669:     </p>
 9670:     <p>
 9671: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9672: 	      '<a href="'.$corrected.'">','</a>').'
 9673:     </p>
 9674:     <p>
 9675: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9676: 	      '<a href="'.$skipped.'">','</a>').'
 9677:     </p>
 9678: ');
 9679:     return '';
 9680: }
 9681: 
 9682: sub checkscantron_results {
 9683:     my ($r,$symb) = @_;
 9684:     if (!$symb) {return '';}
 9685:     my $cid = $env{'request.course.id'};
 9686:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9687:     my $numletts = scalar(keys(%lettdig));
 9688:     my $cnum = $env{'course.'.$cid.'.num'};
 9689:     my $cdom = $env{'course.'.$cid.'.domain'};
 9690:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9691:     my %record;
 9692:     my %scantron_config =
 9693:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9694:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9695:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9696:     my $classlist=&Apache::loncoursedata::get_classlist();
 9697:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9698:     my $navmap=Apache::lonnavmaps::navmap->new();
 9699:     unless (ref($navmap)) {
 9700:         $r->print(&navmap_errormsg());
 9701:         return '';
 9702:     }
 9703:     my $map=$navmap->getResourceByUrl($sequence);
 9704:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9705:         %grader_randomlists_by_symb,%orderedforcode);
 9706:     if (ref($map)) {
 9707:         $randomorder=$map->randomorder();
 9708:         $randompick=$map->randompick();
 9709:         unless ($randomorder || $randompick) {
 9710:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9711:                 if ($res->randomorder()) {
 9712:                     $randomorder = 1;
 9713:                 }
 9714:                 if ($res->randompick()) {
 9715:                     $randompick = 1;
 9716:                 }
 9717:                 last if ($randomorder || $randompick);
 9718:             }
 9719:         }
 9720:     }
 9721:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9722:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9723:     if ($nav_error) {
 9724:         $r->print(&navmap_errormsg());
 9725:         return '';
 9726:     }
 9727:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9728:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9729:     my ($uname,$udom);
 9730:     my (%scandata,%lastname,%bylast);
 9731:     $r->print('
 9732: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9733: 
 9734:     my @delayqueue;
 9735:     my %completedstudents;
 9736: 
 9737:     my $count=&get_todo_count($scanlines,$scan_data);
 9738:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9739:     my ($username,$domain,$started);
 9740:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9741:     if ($nav_error) {
 9742:         $r->print(&navmap_errormsg());
 9743:         return '';
 9744:     }
 9745: 
 9746:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9747:                                           'Processing first student');
 9748:     my $start=&Time::HiRes::time();
 9749:     my $i=-1;
 9750: 
 9751:     while ($i<$scanlines->{'count'}) {
 9752:         ($username,$domain,$uname)=('','','');
 9753:         $i++;
 9754:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9755:         if ($line=~/^[\s\cz]*$/) { next; }
 9756:         if ($started) {
 9757:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9758:                                                      'last student');
 9759:         }
 9760:         $started=1;
 9761:         my $scan_record=
 9762:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9763:                                                      $scan_data);
 9764:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9765:                                               \%idmap,$i)) {
 9766:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9767:                                 'Unable to find a student that matches',1);
 9768:             next;
 9769:         }
 9770:         if (exists $completedstudents{$uname}) {
 9771:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9772:                                 'Student '.$uname.' has multiple sheets',2);
 9773:             next;
 9774:         }
 9775:         my $pid = $scan_record->{'scantron.ID'};
 9776:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9777:         push(@{$bylast{$lastname{$pid}}},$pid);
 9778:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9779:         my $user = $uname.':'.$usec;
 9780:         ($username,$domain)=split(/:/,$uname);
 9781: 
 9782:         my $scancode;
 9783:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9784:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9785:             $scancode = $scan_record->{'scantron.CODE'};
 9786:         } else {
 9787:             $scancode = '';
 9788:         }
 9789: 
 9790:         my @mapresources = @resources;
 9791:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9792:         my %respnumlookup=();
 9793:         my %startline=();
 9794:         if ($randomorder || $randompick) {
 9795:             @mapresources =
 9796:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9797:                              \%orderedforcode);
 9798:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9799:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9800:                                              \%grader_partids_by_symb,\%orderedforcode,
 9801:                                              \%respnumlookup,\%startline);
 9802:             if ($randompick && $total) {
 9803:                 $lastpos = $total*$scantron_config{'Qlength'};
 9804:             }
 9805:         }
 9806:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9807:         chomp($scandata{$pid});
 9808:         $scandata{$pid} =~ s/\r$//;
 9809: 
 9810:         my $counter = -1;
 9811:         foreach my $resource (@mapresources) {
 9812:             my $parts;
 9813:             my $ressymb = $resource->symb();
 9814:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9815:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9816:                 my $currcode;
 9817:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9818:                     $currcode = $scancode;
 9819:                 }
 9820:                 (my $analysis,$parts) =
 9821:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9822:                                               $username,$domain,undef,
 9823:                                               $bubbles_per_row,$currcode);
 9824:             } else {
 9825:                 $parts = $grader_partids_by_symb{$ressymb};
 9826:             }
 9827:             ($counter,my $recording) =
 9828:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9829:                                          $scandata{$pid},$parts,
 9830:                                          \%scantron_config,\%lettdig,$numletts,
 9831:                                          $randomorder,$randompick,
 9832:                                          \%respnumlookup,\%startline);
 9833:             $record{$pid} .= $recording;
 9834:         }
 9835:     }
 9836:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9837:     $r->print('<br />');
 9838:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9839:     $passed = 0;
 9840:     $failed = 0;
 9841:     $numstudents = 0;
 9842:     foreach my $last (sort(keys(%bylast))) {
 9843:         if (ref($bylast{$last}) eq 'ARRAY') {
 9844:             foreach my $pid (sort(@{$bylast{$last}})) {
 9845:                 my $showscandata = $scandata{$pid};
 9846:                 my $showrecord = $record{$pid};
 9847:                 $showscandata =~ s/\s/&nbsp;/g;
 9848:                 $showrecord =~ s/\s/&nbsp;/g;
 9849:                 if ($scandata{$pid} eq $record{$pid}) {
 9850:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9851:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9852: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9853: '</tr>'."\n".
 9854: '<tr class="'.$css_class.'">'."\n".
 9855: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9856:                     $passed ++;
 9857:                 } else {
 9858:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9859:                     $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".
 9860: '</tr>'."\n".
 9861: '<tr class="'.$css_class.'">'."\n".
 9862: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9863: '</tr>'."\n";
 9864:                     $failed ++;
 9865:                 }
 9866:                 $numstudents ++;
 9867:             }
 9868:         }
 9869:     }
 9870:     $r->print('<p>'.
 9871:               &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).',
 9872:                   '<b>',
 9873:                   $numstudents,
 9874:                   '</b>',
 9875:                   $env{'form.scantron_maxbubble'}).
 9876:               '</p>'
 9877:     );
 9878:     $r->print('<p>'
 9879:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9880:              .'<br />'
 9881:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9882:              .'</p>');
 9883:     if ($passed) {
 9884:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9885:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9886:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9887:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9888:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9889:                  $okstudents."\n".
 9890:                  &Apache::loncommon::end_data_table().'<br />');
 9891:     }
 9892:     if ($failed) {
 9893:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9894:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9895:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9896:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9897:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9898:                  $badstudents."\n".
 9899:                  &Apache::loncommon::end_data_table()).'<br />'.
 9900:                  &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.');  
 9901:     }
 9902:     $r->print('</form><br />');
 9903:     return;
 9904: }
 9905: 
 9906: sub verify_scantron_grading {
 9907:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9908:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9909:         $respnumlookup,$startline) = @_;
 9910:     my ($record,%expected,%startpos);
 9911:     return ($counter,$record) if (!ref($resource));
 9912:     return ($counter,$record) if (!$resource->is_problem());
 9913:     my $symb = $resource->symb();
 9914:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9915:     foreach my $part_id (@{$partids}) {
 9916:         $counter ++;
 9917:         $expected{$part_id} = 0;
 9918:         my $respnum = $counter;
 9919:         if ($randomorder || $randompick) {
 9920:             $respnum = $respnumlookup->{$counter};
 9921:             $startpos{$part_id} = $startline->{$counter} + 1;
 9922:         } else {
 9923:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9924:         }
 9925:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9926:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9927:             foreach my $item (@sub_lines) {
 9928:                 $expected{$part_id} += $item;
 9929:             }
 9930:         } else {
 9931:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9932:         }
 9933:     }
 9934:     if ($symb) {
 9935:         my %recorded;
 9936:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9937:         if ($returnhash{'version'}) {
 9938:             my %lasthash=();
 9939:             my $version;
 9940:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9941:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9942:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9943:                 }
 9944:             }
 9945:             foreach my $key (keys(%lasthash)) {
 9946:                 if ($key =~ /\.scantron$/) {
 9947:                     my $value = &unescape($lasthash{$key});
 9948:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9949:                     if ($value eq '') {
 9950:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9951:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9952:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9953:                             }
 9954:                         }
 9955:                     } else {
 9956:                         my @tocheck;
 9957:                         my @items = split(//,$value);
 9958:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9959:                             ($scantron_config->{'Qon'} eq 'number')) {
 9960:                             if (@items < $expected{$part_id}) {
 9961:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9962:                                 my @singles = split(//,$fragment);
 9963:                                 foreach my $pos (@singles) {
 9964:                                     if ($pos eq ' ') {
 9965:                                         push(@tocheck,$pos);
 9966:                                     } else {
 9967:                                         my $next = shift(@items);
 9968:                                         push(@tocheck,$next);
 9969:                                     }
 9970:                                 }
 9971:                             } else {
 9972:                                 @tocheck = @items;
 9973:                             }
 9974:                             foreach my $letter (@tocheck) {
 9975:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9976:                                     if ($letter !~ /^[A-J]$/) {
 9977:                                         $letter = $scantron_config->{'Qoff'};
 9978:                                     }
 9979:                                     $recorded{$part_id} .= $letter;
 9980:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9981:                                     my $digit;
 9982:                                     if ($letter !~ /^[A-J]$/) {
 9983:                                         $digit = $scantron_config->{'Qoff'};
 9984:                                     } else {
 9985:                                         $digit = $lettdig->{$letter};
 9986:                                     }
 9987:                                     $recorded{$part_id} .= $digit;
 9988:                                 }
 9989:                             }
 9990:                         } else {
 9991:                             @tocheck = @items;
 9992:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9993:                                 my $curr_sub = shift(@tocheck);
 9994:                                 my $digit;
 9995:                                 if ($curr_sub =~ /^[A-J]$/) {
 9996:                                     $digit = $lettdig->{$curr_sub}-1;
 9997:                                 }
 9998:                                 if ($curr_sub eq 'J') {
 9999:                                     $digit += scalar($numletts);
10000:                                 }
10001:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10002:                                     if ($j == $digit) {
10003:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10004:                                     } else {
10005:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10006:                                     }
10007:                                 }
10008:                             }
10009:                         }
10010:                     }
10011:                 }
10012:             }
10013:         }
10014:         foreach my $part_id (@{$partids}) {
10015:             if ($recorded{$part_id} eq '') {
10016:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10017:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10018:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10019:                     }
10020:                 }
10021:             }
10022:             $record .= $recorded{$part_id};
10023:         }
10024:     }
10025:     return ($counter,$record);
10026: }
10027: 
10028: #-------- end of section for handling grading scantron forms -------
10029: #
10030: #-------------------------------------------------------------------
10031: 
10032: #-------------------------- Menu interface -------------------------
10033: #
10034: #--- Href with symb and command ---
10035: 
10036: sub href_symb_cmd {
10037:     my ($symb,$cmd)=@_;
10038:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10039: }
10040: 
10041: sub grading_menu {
10042:     my ($request,$symb) = @_;
10043:     if (!$symb) {return '';}
10044: 
10045:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10046:                   'command'=>'individual');
10047: 
10048:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10049: 
10050:     $fields{'command'}='ungraded';
10051:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10052: 
10053:     $fields{'command'}='table';
10054:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10055: 
10056:     $fields{'command'}='all_for_one';
10057:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10058: 
10059:     $fields{'command'}='downloadfilesselect';
10060:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10061:     
10062:     $fields{'command'} = 'csvform';
10063:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10064:     
10065:     $fields{'command'} = 'processclicker';
10066:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10067:     
10068:     $fields{'command'} = 'scantron_selectphase';
10069:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10070: 
10071:     $fields{'command'} = 'initialverifyreceipt';
10072:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10073: 
10074:     my %permissions;
10075:     if ($perm{'mgr'}) {
10076:         $permissions{'either'} = 'F';
10077:         $permissions{'mgr'} = 'F';
10078:     }
10079:     if ($perm{'vgr'}) {
10080:         $permissions{'either'} = 'F';
10081:         $permissions{'vgr'} = 'F';
10082:     }
10083: 
10084:     my @menu = ({	categorytitle=>'Hand Grading',
10085:             items =>[
10086:                         {       linktext => 'Select individual students to grade',
10087:                                 url => $url1a,
10088:                                 permission => $permissions{'either'},
10089:                                 icon => 'grade_students.png',
10090:                                 linktitle => 'Grade current resource for a selection of students.'
10091:                         },
10092:                         {       linktext => 'Grade ungraded submissions',
10093:                                 url => $url1b,
10094:                                 permission => $permissions{'either'},
10095:                                 icon => 'ungrade_sub.png',
10096:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10097:                         },
10098: 
10099:                         {       linktext => 'Grading table',
10100:                                 url => $url1c,
10101:                                 permission => $permissions{'either'},
10102:                                 icon => 'grading_table.png',
10103:                                 linktitle => 'Grade current resource for all students.'
10104:                         },
10105:                         {       linktext => 'Grade page/folder for one student',
10106:                                 url => $url1d,
10107:                                 permission => $permissions{'either'},
10108:                                 icon => 'grade_PageFolder.png',
10109:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10110:                         },
10111:                         {       linktext => 'Download submitted files',
10112:                                 url => $url1e,
10113:                                 permission => $permissions{'either'},
10114:                                 icon => 'download_sub.png',
10115:                                 linktitle => 'Download all files submitted by students.'
10116:                         }]},
10117:                          { categorytitle=>'Automated Grading',
10118:                items =>[
10119: 
10120:                 	    {	linktext => 'Upload Scores',
10121:                     		url => $url2,
10122:                     		permission => $permissions{'mgr'},
10123:                     		icon => 'uploadscores.png',
10124:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10125:                 	    },
10126:                 	    {	linktext => 'Process Clicker',
10127:                     		url => $url3,
10128:                     		permission => $permissions{'mgr'},
10129:                     		icon => 'addClickerInfoFile.png',
10130:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10131:                 	    },
10132:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10133:                     		url => $url4,
10134:                     		permission => $permissions{'mgr'},
10135:                     		icon => 'bubblesheet.png',
10136:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10137:                 	    },
10138:                             {   linktext => 'Verify Receipt Number',
10139:                                 url => $url5,
10140:                                 permission => $permissions{'either'},
10141:                                 icon => 'receipt_number.png',
10142:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10143:                             }
10144: 
10145:                     ]
10146:             });
10147: 
10148:     # Create the menu
10149:     my $Str;
10150:     $Str .= '<form method="post" action="" name="gradingMenu">';
10151:     $Str .= '<input type="hidden" name="command" value="" />'.
10152:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10153: 
10154:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10155:     return $Str;    
10156: }
10157: 
10158: sub ungraded {
10159:     my ($request)=@_;
10160:     &submit_options($request);
10161: }
10162: 
10163: sub submit_options_sequence {
10164:     my ($request,$symb) = @_;
10165:     if (!$symb) {return '';}
10166:     &commonJSfunctions($request);
10167:     my $result;
10168: 
10169:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10170:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10171:     $result.=&selectfield(0).
10172:             '<input type="hidden" name="command" value="pickStudentPage" />
10173:             <div>
10174:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10175:             </div>
10176:         </div>
10177:   </form>';
10178:     return $result;
10179: }
10180: 
10181: sub submit_options_table {
10182:     my ($request,$symb) = @_;
10183:     if (!$symb) {return '';}
10184:     &commonJSfunctions($request);
10185:     my $result;
10186: 
10187:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10188:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10189: 
10190:     $result.=&selectfield(1).
10191:             '<input type="hidden" name="command" value="viewgrades" />
10192:             <div>
10193:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10194:             </div>
10195:         </div>
10196:   </form>';
10197:     return $result;
10198: }
10199: 
10200: sub submit_options_download {
10201:     my ($request,$symb) = @_;
10202:     if (!$symb) {return '';}
10203: 
10204:     my $res_error;
10205:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10206:         &response_type($symb,\$res_error);
10207:     if ($res_error) {
10208:         $request->print(&mt('An error occurred retrieving response types'));
10209:         return;
10210:     }
10211:     unless ($numessay) {
10212:         $request->print(&mt('No essayresponse items found'));
10213:         return;
10214:     }
10215:     my $table;
10216:     if (ref($partlist) eq 'ARRAY') {
10217:         if (scalar(@$partlist) > 1 ) {
10218:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10219:         }
10220:     }
10221: 
10222:     &commonJSfunctions($request);
10223: 
10224:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10225:         $table."\n".
10226:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10227:     $result.='
10228: <h2>
10229:   '.&mt('Select Students for whom to Download Submitted Files').'
10230: </h2>'.&selectfield(1).'
10231:                 <input type="hidden" name="command" value="downloadfileslink" />
10232:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10233:             </div>
10234:           </div>
10235: 
10236: 
10237:   </form>';
10238:     return $result;
10239: }
10240: 
10241: #--- Displays the submissions first page -------
10242: sub submit_options {
10243:     my ($request,$symb) = @_;
10244:     if (!$symb) {return '';}
10245: 
10246:     &commonJSfunctions($request);
10247:     my $result;
10248: 
10249:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10250: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10251:     $result.=&selectfield(1).'
10252:                 <input type="hidden" name="command" value="submission" />
10253:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10254:             </div>
10255:           </div>
10256:   </form>';
10257:     return $result;
10258: }
10259: 
10260: sub selectfield {
10261:    my ($full)=@_;
10262:    my %options =
10263:        (&substatus_options,
10264:         'select_form_order' => ['yes','queued','graded','incorrect','all']);
10265: 
10266:   #
10267:   # PrepareClasslist() needs to be called to avoid getting a sections list
10268:   # for a different course from the @Sections global in lonstatistics.pm,
10269:   # populated by an earlier request.
10270:   #
10271:    &Apache::lonstatistics::PrepareClasslist();
10272: 
10273:    my $result='<div class="LC_columnSection">
10274: 
10275:     <fieldset>
10276:       <legend>
10277:        '.&mt('Sections').'
10278:       </legend>
10279:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10280:     </fieldset>
10281: 
10282:     <fieldset>
10283:       <legend>
10284:         '.&mt('Groups').'
10285:       </legend>
10286:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10287:     </fieldset>
10288:  
10289:     <fieldset>
10290:       <legend>
10291:         '.&mt('Access Status').'
10292:       </legend>
10293:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10294:     </fieldset>';
10295:     if ($full) {
10296:         $result.='
10297:     <fieldset>
10298:       <legend>
10299:         '.&mt('Submission Status').'
10300:       </legend>'.
10301:        &Apache::loncommon::select_form('all','submitonly',\%options).
10302:    '</fieldset>';
10303:     }
10304:     $result.='</div><br />';
10305:     return $result;
10306: }
10307: 
10308: sub substatus_options {
10309:     return &Apache::lonlocal::texthash(
10310:                                       'yes'       => 'with submissions',
10311:                                       'queued'    => 'in grading queue',
10312:                                       'graded'    => 'with ungraded submissions',
10313:                                       'incorrect' => 'with incorrect submissions',
10314:                                       'all'       => 'with any status',
10315:                                       );
10316: }
10317: 
10318: sub transtatus_options {
10319:     return &Apache::lonlocal::texthash(
10320:                                        'yes'       => 'with score transactions',
10321:                                        'incorrect' => 'with less than full credit',
10322:                                        'all'       => 'with any status',
10323:                                       );
10324: }
10325: 
10326: sub reset_perm {
10327:     undef(%perm);
10328: }
10329: 
10330: sub init_perm {
10331:     &reset_perm();
10332:     foreach my $test_perm ('vgr','mgr','opa') {
10333: 
10334: 	my $scope = $env{'request.course.id'};
10335: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10336: 
10337: 	    $scope .= '/'.$env{'request.course.sec'};
10338: 	    if ( $perm{$test_perm}=
10339: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10340: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10341: 	    } else {
10342: 		delete($perm{$test_perm});
10343: 	    }
10344: 	}
10345:     }
10346: }
10347: 
10348: sub init_old_essays {
10349:     my ($symb,$apath,$adom,$aname) = @_;
10350:     if ($symb ne '') {
10351:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10352:         if (keys(%essays) > 0) {
10353:             $old_essays{$symb} = \%essays;
10354:         }
10355:     }
10356:     return;
10357: }
10358: 
10359: sub reset_old_essays {
10360:     undef(%old_essays);
10361: }
10362: 
10363: sub gather_clicker_ids {
10364:     my %clicker_ids;
10365: 
10366:     my $classlist = &Apache::loncoursedata::get_classlist();
10367: 
10368:     # Set up a couple variables.
10369:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10370:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10371:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10372: 
10373:     foreach my $student (keys(%$classlist)) {
10374:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10375:         my $username = $classlist->{$student}->[$username_idx];
10376:         my $domain   = $classlist->{$student}->[$domain_idx];
10377:         my $clickers =
10378: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10379:         foreach my $id (split(/\,/,$clickers)) {
10380:             $id=~s/^[\#0]+//;
10381:             $id=~s/[\-\:]//g;
10382:             if (exists($clicker_ids{$id})) {
10383: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10384:             } else {
10385: 		$clicker_ids{$id}=$username.':'.$domain;
10386:             }
10387:         }
10388:     }
10389:     return %clicker_ids;
10390: }
10391: 
10392: sub gather_adv_clicker_ids {
10393:     my %clicker_ids;
10394:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10396:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10397:     foreach my $element (sort(keys(%coursepersonnel))) {
10398:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10399:             my ($puname,$pudom)=split(/\:/,$person);
10400:             my $clickers =
10401: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10402:             foreach my $id (split(/\,/,$clickers)) {
10403: 		$id=~s/^[\#0]+//;
10404:                 $id=~s/[\-\:]//g;
10405: 		if (exists($clicker_ids{$id})) {
10406: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10407: 		} else {
10408: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10409: 		}
10410:             }
10411:         }
10412:     }
10413:     return %clicker_ids;
10414: }
10415: 
10416: sub clicker_grading_parameters {
10417:     return ('gradingmechanism' => 'scalar',
10418:             'upfiletype' => 'scalar',
10419:             'specificid' => 'scalar',
10420:             'pcorrect' => 'scalar',
10421:             'pincorrect' => 'scalar');
10422: }
10423: 
10424: sub process_clicker {
10425:     my ($r,$symb)=@_;
10426:     if (!$symb) {return '';}
10427:     my $result=&checkforfile_js();
10428:     $result.=&Apache::loncommon::start_data_table().
10429:              &Apache::loncommon::start_data_table_header_row().
10430:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10431:              &Apache::loncommon::end_data_table_header_row().
10432:              &Apache::loncommon::start_data_table_row()."<td>\n";
10433: # Attempt to restore parameters from last session, set defaults if not present
10434:     my %Saveable_Parameters=&clicker_grading_parameters();
10435:     &Apache::loncommon::restore_course_settings('grades_clicker',
10436:                                                  \%Saveable_Parameters);
10437:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10438:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10439:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10440:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10441: 
10442:     my %checked;
10443:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10444:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10445:           $checked{$gradingmechanism}=' checked="checked"';
10446:        }
10447:     }
10448: 
10449:     my $upload=&mt("Evaluate File");
10450:     my $type=&mt("Type");
10451:     my $attendance=&mt("Award points just for participation");
10452:     my $personnel=&mt("Correctness determined from response by course personnel");
10453:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10454:     my $given=&mt("Correctness determined from given list of answers").' '.
10455:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10456:     my $pcorrect=&mt("Percentage points for correct solution");
10457:     my $pincorrect=&mt("Percentage points for incorrect solution");
10458:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10459:                                                    {'iclicker' => 'i>clicker',
10460:                                                     'interwrite' => 'interwrite PRS',
10461:                                                     'turning' => 'Turning Technologies'});
10462:     $symb = &Apache::lonenc::check_encrypt($symb);
10463:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10464: function sanitycheck() {
10465: // Accept only integer percentages
10466:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10467:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10468: // Find out grading choice
10469:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10470:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10471:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10472:       }
10473:    }
10474: // By default, new choice equals user selection
10475:    newgradingchoice=gradingchoice;
10476: // Not good to give more points for false answers than correct ones
10477:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10478:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10479:    }
10480: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10481:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10482:       document.forms.gradesupload.pcorrect.value=100;
10483:       document.forms.gradesupload.pincorrect.value=100;
10484:    }
10485: // If the values are different, cannot be attendance only
10486:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10487:        (gradingchoice=='attendance')) {
10488:        newgradingchoice='personnel';
10489:    }
10490: // Change grading choice to new one
10491:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10492:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10493:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10494:       } else {
10495:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10496:       }
10497:    }
10498: // Remember the old state
10499:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10500: }
10501: ENDUPFORM
10502:     $result.= <<ENDUPFORM;
10503: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10504: <input type="hidden" name="symb" value="$symb" />
10505: <input type="hidden" name="command" value="processclickerfile" />
10506: <input type="file" name="upfile" size="50" />
10507: <br /><label>$type: $selectform</label>
10508: ENDUPFORM
10509:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10510:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10511:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10512: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10513: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10514: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10515: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10516: <br />&nbsp;&nbsp;&nbsp;
10517: <input type="text" name="givenanswer" size="50" />
10518: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10519: ENDGRADINGFORM
10520:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10521:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10522:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10523: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10524: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10525: </form>
10526: ENDPERCFORM
10527:     $result.='</td>'.
10528:              &Apache::loncommon::end_data_table_row().
10529:              &Apache::loncommon::end_data_table();
10530:     return $result;
10531: }
10532: 
10533: sub process_clicker_file {
10534:     my ($r,$symb) = @_;
10535:     if (!$symb) {return '';}
10536: 
10537:     my %Saveable_Parameters=&clicker_grading_parameters();
10538:     &Apache::loncommon::store_course_settings('grades_clicker',
10539:                                               \%Saveable_Parameters);
10540:     my $result='';
10541:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10542: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10543: 	return $result;
10544:     }
10545:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10546:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10547:         return $result;
10548:     }
10549:     my $foundgiven=0;
10550:     if ($env{'form.gradingmechanism'} eq 'given') {
10551:         $env{'form.givenanswer'}=~s/^\s*//gs;
10552:         $env{'form.givenanswer'}=~s/\s*$//gs;
10553:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10554:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10555:         my @answers=split(/\,/,$env{'form.givenanswer'});
10556:         $foundgiven=$#answers+1;
10557:     }
10558:     my %clicker_ids=&gather_clicker_ids();
10559:     my %correct_ids;
10560:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10561: 	%correct_ids=&gather_adv_clicker_ids();
10562:     }
10563:     if ($env{'form.gradingmechanism'} eq 'specific') {
10564: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10565: 	   $correct_id=~tr/a-z/A-Z/;
10566: 	   $correct_id=~s/\s//gs;
10567: 	   $correct_id=~s/^[\#0]+//;
10568:            $correct_id=~s/[\-\:]//g;
10569:            if ($correct_id) {
10570: 	      $correct_ids{$correct_id}='specified';
10571:            }
10572:         }
10573:     }
10574:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10575: 	$result.=&mt('Score based on attendance only');
10576:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10577:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10578:     } else {
10579: 	my $number=0;
10580: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10581: 	foreach my $id (sort(keys(%correct_ids))) {
10582: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10583: 	    if ($correct_ids{$id} eq 'specified') {
10584: 		$result.=&mt('specified');
10585: 	    } else {
10586: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10587: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10588: 	    }
10589: 	    $number++;
10590: 	}
10591:         $result.="</p>\n";
10592:         if ($number==0) {
10593:             $result .=
10594:                  &Apache::lonhtmlcommon::confirm_success(
10595:                      &mt('No IDs found to determine correct answer'),1);
10596:             return $result;
10597:         }
10598:     }
10599:     if (length($env{'form.upfile'}) < 2) {
10600:         $result .=
10601:             &Apache::lonhtmlcommon::confirm_success(
10602:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10603:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10604:         return $result;
10605:     }
10606:     my $mimetype;
10607:     if ($env{'form.upfiletype'} eq 'iclicker') {
10608:         my $mm = new File::MMagic;
10609:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10610:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10611:             $result.= '<p>'.
10612:                 &Apache::lonhtmlcommon::confirm_success(
10613:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10614:             return $result;
10615:         }
10616:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10617:         $result .= '<p>'.
10618:             &Apache::lonhtmlcommon::confirm_success(
10619:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10620:         return $result;
10621:     }
10622: 
10623: # Were able to get all the info needed, now analyze the file
10624: 
10625:     $result.=&Apache::loncommon::studentbrowser_javascript();
10626:     $symb = &Apache::lonenc::check_encrypt($symb);
10627:     $result.=&Apache::loncommon::start_data_table().
10628:              &Apache::loncommon::start_data_table_header_row().
10629:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10630:              &Apache::loncommon::end_data_table_header_row().
10631:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10632: <td>
10633: <form method="post" action="/adm/grades" name="clickeranalysis">
10634: <input type="hidden" name="symb" value="$symb" />
10635: <input type="hidden" name="command" value="assignclickergrades" />
10636: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10637: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10638: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10639: ENDHEADER
10640:     if ($env{'form.gradingmechanism'} eq 'given') {
10641:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10642:     } 
10643:     my %responses;
10644:     my @questiontitles;
10645:     my $errormsg='';
10646:     my $number=0;
10647:     if ($env{'form.upfiletype'} eq 'iclicker') {
10648:         if ($mimetype eq 'text/plain') {
10649:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10650:         } elsif ($mimetype eq 'text/html') {
10651:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10652:         }
10653:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10654:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10655:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10656:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10657:     }
10658:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10659:              '<input type="hidden" name="number" value="'.$number.'" />'.
10660:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10661:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10662:              '<br />';
10663:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10664:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10665:        return $result;
10666:     } 
10667: # Remember Question Titles
10668: # FIXME: Possibly need delimiter other than ":"
10669:     for (my $i=0;$i<$number;$i++) {
10670:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10671:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10672:     }
10673:     my $correct_count=0;
10674:     my $student_count=0;
10675:     my $unknown_count=0;
10676: # Match answers with usernames
10677: # FIXME: Possibly need delimiter other than ":"
10678:     foreach my $id (keys(%responses)) {
10679:        if ($correct_ids{$id}) {
10680:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10681:           $correct_count++;
10682:        } elsif ($clicker_ids{$id}) {
10683:           if ($clicker_ids{$id}=~/\,/) {
10684: # More than one user with the same clicker!
10685:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10686:                            &Apache::loncommon::start_data_table_row()."<td>".
10687:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10688:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10689:                            "<select name='multi".$id."'>";
10690:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10691:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10692:              }
10693:              $result.='</select>';
10694:              $unknown_count++;
10695:           } else {
10696: # Good: found one and only one user with the right clicker
10697:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10698:              $student_count++;
10699:           }
10700:        } else {
10701:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10702:                            &Apache::loncommon::start_data_table_row()."<td>".
10703:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10704:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10705:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10706:                    "\n".&mt("Domain").": ".
10707:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10708:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10709:           $unknown_count++;
10710:        }
10711:     }
10712:     $result.='<hr />'.
10713:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10714:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10715:        if ($correct_count==0) {
10716:           $errormsg.="Found no correct answers for grading!";
10717:        } elsif ($correct_count>1) {
10718:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10719:        }
10720:     }
10721:     if ($number<1) {
10722:        $errormsg.="Found no questions.";
10723:     }
10724:     if ($errormsg) {
10725:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10726:     } else {
10727:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10728:     }
10729:     $result.='</form></td>'.
10730:              &Apache::loncommon::end_data_table_row().
10731:              &Apache::loncommon::end_data_table();
10732:     return $result;
10733: }
10734: 
10735: sub iclicker_eval {
10736:     my ($questiontitles,$responses)=@_;
10737:     my $number=0;
10738:     my $errormsg='';
10739:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10740:         my %components=&Apache::loncommon::record_sep($line);
10741:         my @entries=map {$components{$_}} (sort(keys(%components)));
10742: 	if ($entries[0] eq 'Question') {
10743: 	    for (my $i=3;$i<$#entries;$i+=6) {
10744: 		$$questiontitles[$number]=$entries[$i];
10745: 		$number++;
10746: 	    }
10747: 	}
10748: 	if ($entries[0]=~/^\#/) {
10749: 	    my $id=$entries[0];
10750: 	    my @idresponses;
10751: 	    $id=~s/^[\#0]+//;
10752: 	    for (my $i=0;$i<$number;$i++) {
10753: 		my $idx=3+$i*6;
10754:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10755: 		push(@idresponses,$entries[$idx]);
10756: 	    }
10757: 	    $$responses{$id}=join(',',@idresponses);
10758: 	}
10759:     }
10760:     return ($errormsg,$number);
10761: }
10762: 
10763: sub iclickerxml_eval {
10764:     my ($questiontitles,$responses)=@_;
10765:     my $number=0;
10766:     my $errormsg='';
10767:     my @state;
10768:     my %respbyid;
10769:     my $p = HTML::Parser->new
10770:     (
10771:         xml_mode => 1,
10772:         start_h =>
10773:             [sub {
10774:                  my ($tagname,$attr) = @_;
10775:                  push(@state,$tagname);
10776:                  if ("@state" eq "ssn p") {
10777:                      my $title = $attr->{qn};
10778:                      $title =~ s/(^\s+|\s+$)//g;
10779:                      $questiontitles->[$number]=$title;
10780:                  } elsif ("@state" eq "ssn p v") {
10781:                      my $id = $attr->{id};
10782:                      my $entry = $attr->{ans};
10783:                      $id=~s/^[\#0]+//;
10784:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10785:                      $respbyid{$id}[$number] = $entry;
10786:                  }
10787:             }, "tagname, attr"],
10788:          end_h =>
10789:                [sub {
10790:                    my ($tagname) = @_;
10791:                    if ("@state" eq "ssn p") {
10792:                        $number++;
10793:                    }
10794:                    pop(@state);
10795:                 }, "tagname"],
10796:     );
10797: 
10798:     $p->parse($env{'form.upfile'});
10799:     $p->eof;
10800:     foreach my $id (keys(%respbyid)) {
10801:         $responses->{$id}=join(',',@{$respbyid{$id}});
10802:     }
10803:     return ($errormsg,$number);
10804: }
10805: 
10806: sub interwrite_eval {
10807:     my ($questiontitles,$responses)=@_;
10808:     my $number=0;
10809:     my $errormsg='';
10810:     my $skipline=1;
10811:     my $questionnumber=0;
10812:     my %idresponses=();
10813:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10814:         my %components=&Apache::loncommon::record_sep($line);
10815:         my @entries=map {$components{$_}} (sort(keys(%components)));
10816:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10817:         if ($entries[1] eq 'Response') { $skipline=1; }
10818:         next if $skipline;
10819:         if ($entries[0]!=$questionnumber) {
10820:            $questionnumber=$entries[0];
10821:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10822:            $number++;
10823:         }
10824:         my $id=$entries[4];
10825:         $id=~s/^[\#0]+//;
10826:         $id=~s/^v\d*\://i;
10827:         $id=~s/[\-\:]//g;
10828:         $idresponses{$id}[$number]=$entries[6];
10829:     }
10830:     foreach my $id (keys(%idresponses)) {
10831:        $$responses{$id}=join(',',@{$idresponses{$id}});
10832:        $$responses{$id}=~s/^\s*\,//;
10833:     }
10834:     return ($errormsg,$number);
10835: }
10836: 
10837: sub turning_eval {
10838:     my ($questiontitles,$responses)=@_;
10839:     my $number=0;
10840:     my $errormsg='';
10841:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10842:         my %components=&Apache::loncommon::record_sep($line);
10843:         my @entries=map {$components{$_}} (sort(keys(%components)));
10844:         if ($#entries>$number) { $number=$#entries; }
10845:         my $id=$entries[0];
10846:         my @idresponses;
10847:         $id=~s/^[\#0]+//;
10848:         unless ($id) { next; }
10849:         for (my $idx=1;$idx<=$#entries;$idx++) {
10850:             $entries[$idx]=~s/\,/\;/g;
10851:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10852:             push(@idresponses,$entries[$idx]);
10853:         }
10854:         $$responses{$id}=join(',',@idresponses);
10855:     }
10856:     for (my $i=1; $i<=$number; $i++) {
10857:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10858:     }
10859:     return ($errormsg,$number);
10860: }
10861: 
10862: sub assign_clicker_grades {
10863:     my ($r,$symb) = @_;
10864:     if (!$symb) {return '';}
10865: # See which part we are saving to
10866:     my $res_error;
10867:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10868:     if ($res_error) {
10869:         return &navmap_errormsg();
10870:     }
10871: # FIXME: This should probably look for the first handgradeable part
10872:     my $part=$$partlist[0];
10873: # Start screen output
10874:     my $result = &Apache::loncommon::start_data_table(). 
10875:                  &Apache::loncommon::start_data_table_header_row().
10876:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10877:                  &Apache::loncommon::end_data_table_header_row().
10878:                  &Apache::loncommon::start_data_table_row().'<td>';
10879: # Get correct result
10880: # FIXME: Possibly need delimiter other than ":"
10881:     my @correct=();
10882:     my $gradingmechanism=$env{'form.gradingmechanism'};
10883:     my $number=$env{'form.number'};
10884:     if ($gradingmechanism ne 'attendance') {
10885:        foreach my $key (keys(%env)) {
10886:           if ($key=~/^form\.correct\:/) {
10887:              my @input=split(/\,/,$env{$key});
10888:              for (my $i=0;$i<=$#input;$i++) {
10889:                  if (($correct[$i]) && ($input[$i]) &&
10890:                      ($correct[$i] ne $input[$i])) {
10891:                     $result.='<br /><span class="LC_warning">'.
10892:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10893:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10894:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10895:                     $correct[$i]=$input[$i];
10896:                  }
10897:              }
10898:           }
10899:        }
10900:        for (my $i=0;$i<$number;$i++) {
10901:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10902:              $result.='<br /><span class="LC_error">'.
10903:                       &mt('No correct result given for question "[_1]"!',
10904:                           $env{'form.question:'.$i}).'</span>';
10905:           }
10906:        }
10907:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10908:     }
10909: # Start grading
10910:     my $pcorrect=$env{'form.pcorrect'};
10911:     my $pincorrect=$env{'form.pincorrect'};
10912:     my $storecount=0;
10913:     my %users=();
10914:     foreach my $key (keys(%env)) {
10915:        my $user='';
10916:        if ($key=~/^form\.student\:(.*)$/) {
10917:           $user=$1;
10918:        }
10919:        if ($key=~/^form\.unknown\:(.*)$/) {
10920:           my $id=$1;
10921:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10922:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10923:           } elsif ($env{'form.multi'.$id}) {
10924:              $user=$env{'form.multi'.$id};
10925:           }
10926:        }
10927:        if ($user) {
10928:           if ($users{$user}) {
10929:              $result.='<br /><span class="LC_warning">'.
10930:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10931:                       '</span><br />';
10932:           }
10933:           $users{$user}=1;
10934:           my @answer=split(/\,/,$env{$key});
10935:           my $sum=0;
10936:           my $realnumber=$number;
10937:           for (my $i=0;$i<$number;$i++) {
10938:              if  ($correct[$i] eq '-') {
10939:                 $realnumber--;
10940:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10941:                 if ($gradingmechanism eq 'attendance') {
10942:                    $sum+=$pcorrect;
10943:                 } elsif ($correct[$i] eq '*') {
10944:                    $sum+=$pcorrect;
10945:                 } else {
10946: # We actually grade if correct or not
10947:                    my $increment=$pincorrect;
10948: # Special case: numerical answer "0"
10949:                    if ($correct[$i] eq '0') {
10950:                       if ($answer[$i]=~/^[0\.]+$/) {
10951:                          $increment=$pcorrect;
10952:                       }
10953: # General numerical answer, both evaluate to something non-zero
10954:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10955:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10956:                          $increment=$pcorrect;
10957:                       }
10958: # Must be just alphanumeric
10959:                    } elsif ($answer[$i] eq $correct[$i]) {
10960:                       $increment=$pcorrect;
10961:                    }
10962:                    $sum+=$increment;
10963:                 }
10964:              }
10965:           }
10966:           my $ave=$sum/(100*$realnumber);
10967: # Store
10968:           my ($username,$domain)=split(/\:/,$user);
10969:           my %grades=();
10970:           $grades{"resource.$part.solved"}='correct_by_override';
10971:           $grades{"resource.$part.awarded"}=$ave;
10972:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10973:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10974:                                                  $env{'request.course.id'},
10975:                                                  $domain,$username);
10976:           if ($returncode ne 'ok') {
10977:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10978:           } else {
10979:              $storecount++;
10980:           }
10981:        }
10982:     }
10983: # We are done
10984:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10985:              '</td>'.
10986:              &Apache::loncommon::end_data_table_row().
10987:              &Apache::loncommon::end_data_table();
10988:     return $result;
10989: }
10990: 
10991: sub navmap_errormsg {
10992:     return '<div class="LC_error">'.
10993:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10994:            &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>').
10995:            '</div>';
10996: }
10997: 
10998: sub startpage {
10999:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11000:     my %args;
11001:     if ($onload) {
11002:          my %loaditems = (
11003:                         'onload' => $onload,
11004:                       );
11005:          $args{'add_entries'} = \%loaditems;
11006:     }
11007:     if ($nomenu) {
11008:         $args{'only_body'} = 1;
11009:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11010:     } else {
11011:         if ($env{'request.course.id'}) {
11012:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11013:         }
11014:         $args{'bread_crumbs'} = $crumbs;
11015:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11016:     }
11017:     unless ($nodisplayflag) {
11018:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11019:     }
11020: }
11021: 
11022: sub select_problem {
11023:     my ($r)=@_;
11024:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11025:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
11026:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11027:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11028: }
11029: 
11030: sub handler {
11031:     my $request=$_[0];
11032:     &reset_caches();
11033:     if ($request->header_only) {
11034:         &Apache::loncommon::content_type($request,'text/html');
11035:         $request->send_http_header;
11036:         return OK;
11037:     }
11038:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11039: 
11040: # see what command we need to execute
11041:  
11042:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11043:     my $command=$commands[0];
11044: 
11045:     &init_perm();
11046:     if (!$env{'request.course.id'}) {
11047:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11048:                 ($command =~ /^scantronupload/)) {
11049:             # Not in a course.
11050:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11051:             return HTTP_NOT_ACCEPTABLE;
11052:         }
11053:     } elsif (!%perm) {
11054:         $request->internal_redirect('/adm/quickgrades');
11055:         return OK;
11056:     }
11057:     &Apache::loncommon::content_type($request,'text/html');
11058:     $request->send_http_header;
11059: 
11060:     if ($#commands > 0) {
11061: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11062:     }
11063: 
11064: # see what the symb is
11065: 
11066:     my $symb=$env{'form.symb'};
11067:     unless ($symb) {
11068:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11069:        $symb=&Apache::lonnet::symbread($url);
11070:     }
11071:     &Apache::lonenc::check_decrypt(\$symb);
11072: 
11073:     $ssi_error = 0;
11074:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11075: #
11076: # Not called from a resource, but inside a course
11077: #
11078:         &startpage($request,undef,[],1,1);
11079:         &select_problem($request);
11080:     } else {
11081:         if ($command eq 'submission' && $perm{'vgr'}) {
11082:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11083:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11084:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11085:                     &choose_task_version_form($symb,$env{'form.student'},
11086:                                               $env{'form.userdom'});
11087:             }
11088:             my $divforres;
11089:             if ($env{'form.student'} eq '') {
11090:                 $js .= &part_selector_js();
11091:                 $onload = "toggleParts('gradesub');";
11092:             } else {
11093:                 $divforres = 1;
11094:             }
11095:             my $head_extra = $js;
11096:             unless ($env{'form.vProb'} eq 'no') {
11097:                 my $csslinks = &Apache::loncommon::css_links($symb);
11098:                 if ($csslinks) {
11099:                     $head_extra .= "\n$csslinks";
11100:                 }
11101:             }
11102:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11103:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11104:             if ($versionform) {
11105:                 if ($divforres) {
11106:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11107:                 }
11108:                 $request->print($versionform);
11109:             }
11110:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11111:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11112:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11113:                 &choose_task_version_form($symb,$env{'form.student'},
11114:                                           $env{'form.userdom'},
11115:                                           $env{'form.inhibitmenu'});
11116:             my $head_extra = $js;
11117:             unless ($env{'form.vProb'} eq 'no') {
11118:                 my $csslinks = &Apache::loncommon::css_links($symb);
11119:                 if ($csslinks) {
11120:                     $head_extra .= "\n$csslinks";
11121:                 }
11122:             }
11123:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11124:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11125:             if ($versionform) {
11126:                 $request->print($versionform);
11127:             }
11128:             $request->print('<br clear="all" />');
11129:             $request->print(&show_previous_task_version($request,$symb));
11130:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11131:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11132:                                        {href=>'',text=>'Select student'}],1,1);
11133:             &pickStudentPage($request,$symb);
11134:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11135:             my $csslinks;
11136:             unless ($env{'form.vProb'} eq 'no') {
11137:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11138:             }
11139:             &startpage($request,$symb,
11140:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11141:                                        {href=>'',text=>'Select student'},
11142:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11143:             &displayPage($request,$symb);
11144:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11145:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11146:                                        {href=>'',text=>'Select student'},
11147:                                        {href=>'',text=>'Grade student'},
11148:                                        {href=>'',text=>'Store grades'}],1,1);
11149:             &updateGradeByPage($request,$symb);
11150:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11151:             my $csslinks;
11152:             unless ($env{'form.vProb'} eq 'no') {
11153:                 $csslinks = &Apache::loncommon::css_links($symb);
11154:             }
11155:             &startpage($request,$symb,[{href=>'',text=>'...'},
11156:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11157:             &processGroup($request,$symb);
11158:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11159:             &startpage($request,$symb);
11160:             $request->print(&grading_menu($request,$symb));
11161:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
11162:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11163:             $request->print(&submit_options($request,$symb));
11164:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11165:             my $js = &part_selector_js();
11166:             my $onload = "toggleParts('gradesub');";
11167:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11168:                        undef,undef,undef,undef,undef,$js,$onload);
11169:             $request->print(&listStudents($request,$symb,'graded'));
11170:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11171:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11172:             $request->print(&submit_options_table($request,$symb));
11173:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11174:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11175:             $request->print(&submit_options_sequence($request,$symb));
11176:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11177:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11178:             $request->print(&viewgrades($request,$symb));
11179:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11180:             &startpage($request,$symb,[{href=>'',text=>'...'},
11181:                                        {href=>'',text=>'Store grades'}]);
11182:             $request->print(&processHandGrade($request,$symb));
11183:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11184:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11185:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11186:                                                                              text=>"Modify grades"},
11187:                                        {href=>'', text=>"Store grades"}]);
11188:             $request->print(&editgrades($request,$symb));
11189:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11190:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11191:             $request->print(&initialverifyreceipt($request,$symb));
11192:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
11193:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11194:                                        {href=>'',text=>'Verification Result'}]);
11195:             $request->print(&verifyreceipt($request,$symb));
11196:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11197:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11198:             $request->print(&process_clicker($request,$symb));
11199:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11200:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11201:                                        {href=>'', text=>'Process clicker file'}]);
11202:             $request->print(&process_clicker_file($request,$symb));
11203:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11204:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11205:                                        {href=>'', text=>'Process clicker file'},
11206:                                        {href=>'', text=>'Store grades'}]);
11207:             $request->print(&assign_clicker_grades($request,$symb));
11208:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
11209:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11210:             $request->print(&upcsvScores_form($request,$symb));
11211:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11212:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11213:             $request->print(&csvupload($request,$symb));
11214:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11215:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11216:             $request->print(&csvuploadmap($request,$symb));
11217:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11218:             if ($env{'form.associate'} ne 'Reverse Association') {
11219:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11220:                 $request->print(&csvuploadoptions($request,$symb));
11221:             } else {
11222:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11223:                     $env{'form.upfile_associate'} = 'reverse';
11224:                 } else {
11225:                     $env{'form.upfile_associate'} = 'forward';
11226:                 }
11227:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11228:                 $request->print(&csvuploadmap($request,$symb));
11229:             }
11230:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11231:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11232:             $request->print(&csvuploadassign($request,$symb));
11233:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11234:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11235:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11236:             $request->print(&scantron_selectphase($request,undef,$symb));
11237:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11238:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11239:             $request->print(&scantron_do_warning($request,$symb));
11240:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11241:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11242:             $request->print(&scantron_validate_file($request,$symb));
11243:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11244:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11245:             $request->print(&scantron_process_students($request,$symb));
11246:         } elsif ($command eq 'scantronupload' &&
11247:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11248:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11249:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11250:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11251:             $request->print(&scantron_upload_scantron_data($request,$symb));
11252:         } elsif ($command eq 'scantronupload_save' &&
11253:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11254:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11255:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11256:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11257:         } elsif ($command eq 'scantron_download' &&
11258:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11259:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11260:             $request->print(&scantron_download_scantron_data($request,$symb));
11261:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11262:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11263:             $request->print(&checkscantron_results($request,$symb));
11264:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11265:             my $js = &part_selector_js();
11266:             my $onload = "toggleParts('gradingMenu');";
11267:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11268:                        undef,undef,undef,undef,undef,$js,$onload);
11269:             $request->print(&submit_options_download($request,$symb));
11270:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11271:             &startpage($request,$symb,
11272:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11273:     {href=>'', text=>'Download submitted files'}],
11274:                undef,undef,undef,undef,undef,undef,undef,1);
11275:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11276:             &submit_download_link($request,$symb);
11277:         } elsif ($command) {
11278:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11279:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11280:         }
11281:     }
11282:     if ($ssi_error) {
11283: 	&ssi_print_error($request);
11284:     }
11285:     $request->print(&Apache::loncommon::end_page());
11286:     &reset_caches();
11287:     return OK;
11288: }
11289: 
11290: 1;
11291: 
11292: __END__;
11293: 
11294: 
11295: =head1 NAME
11296: 
11297: Apache::grades
11298: 
11299: =head1 SYNOPSIS
11300: 
11301: Handles the viewing of grades.
11302: 
11303: This is part of the LearningOnline Network with CAPA project
11304: described at http://www.lon-capa.org.
11305: 
11306: =head1 OVERVIEW
11307: 
11308: Do an ssi with retries:
11309: While I'd love to factor out this with the vesrion in lonprintout,
11310: 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
11311: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11312: 
11313: At least the logic that drives this has been pulled out into loncommon.
11314: 
11315: 
11316: 
11317: ssi_with_retries - Does the server side include of a resource.
11318:                      if the ssi call returns an error we'll retry it up to
11319:                      the number of times requested by the caller.
11320:                      If we still have a problem, no text is appended to the
11321:                      output and we set some global variables.
11322:                      to indicate to the caller an SSI error occurred.  
11323:                      All of this is supposed to deal with the issues described
11324:                      in LON-CAPA BZ 5631 see:
11325:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11326:                      by informing the user that this happened.
11327: 
11328: Parameters:
11329:   resource   - The resource to include.  This is passed directly, without
11330:                interpretation to lonnet::ssi.
11331:   form       - The form hash parameters that guide the interpretation of the resource
11332:                
11333:   retries    - Number of retries allowed before giving up completely.
11334: Returns:
11335:   On success, returns the rendered resource identified by the resource parameter.
11336: Side Effects:
11337:   The following global variables can be set:
11338:    ssi_error                - If an unrecoverable error occurred this becomes true.
11339:                               It is up to the caller to initialize this to false
11340:                               if desired.
11341:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11342:                               of the resource that could not be rendered by the ssi
11343:                               call.
11344:    ssi_error_message   - The error string fetched from the ssi response
11345:                               in the event of an error.
11346: 
11347: 
11348: =head1 HANDLER SUBROUTINE
11349: 
11350: ssi_with_retries()
11351: 
11352: =head1 SUBROUTINES
11353: 
11354: =over
11355: 
11356: =item scantron_get_correction() : 
11357: 
11358:    Builds the interface screen to interact with the operator to fix a
11359:    specific error condition in a specific scanline
11360: 
11361:  Arguments:
11362:     $r           - Apache request object
11363:     $i           - number of the current scanline
11364:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11365:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11366:     $line        - full contents of the current scanline
11367:     $error       - error condition, valid values are
11368:                    'incorrectCODE', 'duplicateCODE',
11369:                    'doublebubble', 'missingbubble',
11370:                    'duplicateID', 'incorrectID'
11371:     $arg         - extra information needed
11372:        For errors:
11373:          - duplicateID   - paper number that this studentID was seen before on
11374:          - duplicateCODE - array ref of the paper numbers this CODE was
11375:                            seen on before
11376:          - incorrectCODE - current incorrect CODE 
11377:          - doublebubble  - array ref of the bubble lines that have double
11378:                            bubble errors
11379:          - missingbubble - array ref of the bubble lines that have missing
11380:                            bubble errors
11381: 
11382:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
11383:    $randompick  - True if exam folder (or a sub-folder) has randompick set
11384:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11385:                      for current line to question number used for same question
11386:                      in "Master Seqence" (as seen by Course Coordinator).
11387:    $startline   - Reference to hash where key is question number (0 is first)
11388:                   and value is number of first bubble line for current student
11389:                   or code-based randompick and/or randomorder.
11390: 
11391: 
11392: =item  scantron_get_maxbubble() : 
11393: 
11394:    Arguments:
11395:        $nav_error  - Reference to scalar which is a flag to indicate a
11396:                       failure to retrieve a navmap object.
11397:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11398:        calling routine should trap the error condition and display the warning
11399:        found in &navmap_errormsg().
11400: 
11401:        $scantron_config - Reference to bubblesheet format configuration hash.
11402: 
11403:    Returns the maximum number of bubble lines that are expected to
11404:    occur. Does this by walking the selected sequence rendering the
11405:    resource and then checking &Apache::lonxml::get_problem_counter()
11406:    for what the current value of the problem counter is.
11407: 
11408:    Caches the results to $env{'form.scantron_maxbubble'},
11409:    $env{'form.scantron.bubble_lines.n'}, 
11410:    $env{'form.scantron.first_bubble_line.n'} and
11411:    $env{"form.scantron.sub_bubblelines.n"}
11412:    which are the total number of bubble lines, the number of bubble
11413:    lines for response n and number of the first bubble line for response n,
11414:    and a comma separated list of numbers of bubble lines for sub-questions
11415:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11416: 
11417: 
11418: =item  scantron_validate_missingbubbles() : 
11419: 
11420:    Validates all scanlines in the selected file to not have any
11421:     answers that don't have bubbles that have not been verified
11422:     to be bubble free.
11423: 
11424: =item  scantron_process_students() : 
11425: 
11426:    Routine that does the actual grading of the bubblesheet information.
11427: 
11428:    The parsed scanline hash is added to %env 
11429: 
11430:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11431:    foreach resource , with the form data of
11432: 
11433: 	'submitted'     =>'scantron' 
11434: 	'grade_target'  =>'grade',
11435: 	'grade_username'=> username of student
11436: 	'grade_domain'  => domain of student
11437: 	'grade_courseid'=> of course
11438: 	'grade_symb'    => symb of resource to grade
11439: 
11440:     This triggers a grading pass. The problem grading code takes care
11441:     of converting the bubbled letter information (now in %env) into a
11442:     valid submission.
11443: 
11444: =item  scantron_upload_scantron_data() :
11445: 
11446:     Creates the screen for adding a new bubblesheet data file to a course.
11447: 
11448: =item  scantron_upload_scantron_data_save() : 
11449: 
11450:    Adds a provided bubble information data file to the course if user
11451:    has the correct privileges to do so. 
11452: 
11453: =item  valid_file() :
11454: 
11455:    Validates that the requested bubble data file exists in the course.
11456: 
11457: =item  scantron_download_scantron_data() : 
11458: 
11459:    Shows a list of the three internal files (original, corrected,
11460:    skipped) for a specific bubblesheet data file that exists in the
11461:    course.
11462: 
11463: =item  scantron_validate_ID() : 
11464: 
11465:    Validates all scanlines in the selected file to not have any
11466:    invalid or underspecified student/employee IDs
11467: 
11468: =item navmap_errormsg() :
11469: 
11470:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11471:    Should be called whenever the request to instantiate a navmap object fails.  
11472: 
11473: =back
11474: 
11475: =cut

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