File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.57: download - view: text, annotated - select for diffs
Mon Jan 25 14:25:55 2021 UTC (3 years, 3 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  Backport 1.782, 1.783, 1.784

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.57 2021/01/25 14:25:55 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,$timestamp)= &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)= &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:         $lastsubonly =
 2534:             '<div class="LC_grade_submissions_body">'
 2535:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2536: 
 2537: 	my %seenparts;
 2538: 	my @part_response_id = &flatten_responseType($responseType);
 2539: 	foreach my $part (@part_response_id) {
 2540: 	    my ($partid,$respid) = @{ $part };
 2541: 	    my $display_part=&get_display_part($partid,$symb);
 2542: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2543: 		if (exists($seenparts{$partid})) { next; }
 2544: 		$seenparts{$partid}=1;
 2545:                 $request->print(
 2546:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2547:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2548:                                '<a href="javascript:viewSubmitter(\''.
 2549:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2550:                                '\');" target="_self">'.
 2551:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2552:                     '<br />');
 2553: 		next;
 2554: 	    }
 2555: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2556: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2557:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2558:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2559:                     ' <span class="LC_internal_info">'.
 2560:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2561:                     '</span>&nbsp; &nbsp;'.
 2562: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2563: 		next;
 2564: 	    }
 2565: 	    foreach my $submission (@$string) {
 2566: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2567: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2568: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2569: 		# Similarity check
 2570:                 my $similar='';
 2571:                 my ($type,$trial,$rndseed);
 2572:                 if ($hide eq 'rand') {
 2573:                     $type = 'randomizetry';
 2574:                     $trial = $record{"resource.$partid.tries"};
 2575:                     $rndseed = $record{"resource.$partid.rndseed"};
 2576:                 }
 2577: 		if ($env{'form.checkPlag'}) {
 2578: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2579: 		        &most_similar($uname,$udom,$symb,$subval);
 2580: 		    if ($osim) {
 2581: 		        $osim=int($osim*100.0);
 2582:                         if ($hide eq 'anon') {
 2583:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2584:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2585:                         } else {
 2586: 			    $similar='<hr />';
 2587:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2588:                                 $similar .= '<h3><span class="LC_warning">'.
 2589:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2590:                                                 $osim,
 2591:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2592:                                             '</span></h3>';
 2593:                             } elsif ($ocrsid ne '') {
 2594:                                 my %old_course_desc;
 2595:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2596:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2597:                                 } else {
 2598:                                     my $args;
 2599:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2600:                                         $args = {'one_time' => 1};
 2601:                                     }
 2602:                                     %old_course_desc =
 2603:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2604:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2605:                                 }
 2606:                                 $similar .=
 2607:                                     '<h3><span class="LC_warning">'.
 2608: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2609: 				        $osim,
 2610: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2611: 				        $old_course_desc{'description'},
 2612: 				        $old_course_desc{'num'},
 2613: 				        $old_course_desc{'domain'}).
 2614: 				    '</span></h3>';
 2615:                             } else {
 2616:                                 $similar .=
 2617:                                     '<h3><span class="LC_warning">'.
 2618:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2619:                                         $osim,
 2620:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2621:                                     '</span></h3>';
 2622:                             }
 2623:                             $similar .= '<blockquote><i>'.
 2624:                                         &keywords_highlight($oessay).
 2625:                                         '</i></blockquote><hr />';
 2626: 		        }
 2627:                     }
 2628:                 }
 2629: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2630:                                      undef,$type,$trial,$rndseed);
 2631:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2632:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2633:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2634: 		    my $display_part=&get_display_part($partid,$symb);
 2635:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2636:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2637:                         ' <span class="LC_internal_info">'.
 2638:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2639:                         '</span>&nbsp; &nbsp;';
 2640: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2641: 		    if (@$files) {
 2642:                         if ($hide eq 'anon') {
 2643:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2644:                         } else {
 2645:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2646:                                          .'<br /><span class="LC_warning">';
 2647:                             if(@$files == 1) {
 2648:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2649:                             } else {
 2650:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2651:                             }
 2652:                             $lastsubonly .= '</span>';
 2653:                             foreach my $file (@$files) {
 2654:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2655:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2656:                             }
 2657:                         }
 2658: 			$lastsubonly.='<br />';
 2659: 		    }
 2660:                     if ($hide eq 'anon') {
 2661:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2662:                     } else {
 2663:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2664:                         if ($draft) {
 2665:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2666:                         }
 2667:                         $subval =
 2668: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2669: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2670:                         if ($responsetype eq 'essay') {
 2671:                             $subval =~ s{\n}{<br />}g;
 2672:                         }
 2673:                         $lastsubonly.=$subval."\n";
 2674:                     }
 2675:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2676: 		    $lastsubonly.='</div>';
 2677: 		}
 2678: 	    }
 2679: 	}
 2680: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2681:     }
 2682:     $request->print($lastsubonly);
 2683:     if ($env{'form.lastSub'} eq 'datesub') {
 2684:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2685: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2686:     }
 2687:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2688:         my $identifier = (&canmodify($usec)? $counter : '');
 2689: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2690: 								 $env{'request.course.id'},
 2691: 								 $last,'.submission',
 2692: 								 'Apache::grades::keywords_highlight',
 2693:                                                                  $usec,$identifier));
 2694:     }
 2695:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2696: 	.$udom.'" />'."\n");
 2697:     # return if view submission with no grading option
 2698:     if (!&canmodify($usec)) {
 2699:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2700:         return;
 2701:     } else {
 2702: 	$request->print('</div>'."\n");
 2703:     }
 2704: 
 2705:     # grading message center
 2706: 
 2707:     if ($env{'form.compmsg'}) {
 2708:         my $result='<div class="LC_Box">'.
 2709:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2710:                    '<div class="LC_grade_message_center_body">';
 2711:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2712:         my $msgfor = $givenn.' '.$lastname;
 2713:         if (scalar(@$col_fullnames) > 0) {
 2714:             my $lastone = pop(@$col_fullnames);
 2715:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2716:         }
 2717:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2718:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2719:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2720: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2721:                  ',\''.$msgfor.'\');" target="_self">'.
 2722:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2723:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2724:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2725:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2726:                  '<br />&nbsp;('.
 2727:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2728: 	         '</div></div>';
 2729:         $request->print($result);
 2730:     }
 2731: 
 2732:     my %seen = ();
 2733:     my @partlist;
 2734:     my @gradePartRespid;
 2735:     my @part_response_id = &flatten_responseType($responseType);
 2736:     $request->print(
 2737:         '<div class="LC_Box">'
 2738:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2739:     );
 2740:     $request->print(&gradeBox_start());
 2741:     foreach my $part_response_id (@part_response_id) {
 2742:     	my ($partid,$respid) = @{ $part_response_id };
 2743: 	my $part_resp = join('_',@{ $part_response_id });
 2744: 	next if ($seen{$partid} > 0);
 2745: 	$seen{$partid}++;
 2746: 	push(@partlist,$partid);
 2747: 	push(@gradePartRespid,$partid.'.'.$respid);
 2748: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2749:     }
 2750:     $request->print(&gradeBox_end()); # </div>
 2751:     $request->print('</div>');
 2752: 
 2753:     $request->print('<div class="LC_grade_info_links">');
 2754:     $request->print('</div>');
 2755: 
 2756:     $result='<input type="hidden" name="partlist'.$counter.
 2757: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2758:     $result.='<input type="hidden" name="gradePartRespid'.
 2759: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2760:     my $ctr = 0;
 2761:     while ($ctr < scalar(@partlist)) {
 2762: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2763: 	    $partlist[$ctr].'" />'."\n";
 2764: 	$ctr++;
 2765:     }
 2766:     $request->print($result.''."\n");
 2767: 
 2768: # Done with printing info for one student
 2769: 
 2770:     $request->print('</div>');#LC_grade_show_user
 2771: 
 2772: 
 2773:     # print end of form
 2774:     if ($counter == $total) {
 2775:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2776: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2777: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2778: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2779: 	my $ntstu ='<select name="NTSTU">'.
 2780: 	    '<option>1</option><option>2</option>'.
 2781: 	    '<option>3</option><option>5</option>'.
 2782: 	    '<option>7</option><option>10</option></select>'."\n";
 2783: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2784: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2785:         $endform.=&mt('[_1]student(s)',$ntstu);
 2786: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2787: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2788: 	    '<input type="button" value="'.&mt('Next').'" '.
 2789: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2790:         $endform.='<span class="LC_warning">'.
 2791:                   &mt('(Next and Previous (student) do not save the scores.)').
 2792:                   '</span>'."\n" ;
 2793:         $endform.="<input type='hidden' value='".&get_increment().
 2794:             "' name='increment' />";
 2795: 	$endform.='</td></tr></table></form>';
 2796: 	$request->print($endform);
 2797:     }
 2798:     return '';
 2799: }
 2800: 
 2801: sub check_collaborators {
 2802:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2803:     my ($result,@col_fullnames);
 2804:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2805:     foreach my $part (keys(%$handgrade)) {
 2806: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2807: 					'.maxcollaborators',
 2808: 					$symb,$udom,$uname);
 2809: 	next if ($ncol <= 0);
 2810: 	$part =~ s/\_/\./g;
 2811: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2812: 	my (@good_collaborators, @bad_collaborators);
 2813: 	foreach my $possible_collaborator
 2814: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2815: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2816: 	    next if ($possible_collaborator eq '');
 2817: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2818: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2819: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2820: 	    # Doing this grep allows 'fuzzy' specification
 2821: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2822: 			       keys(%$classlist));
 2823: 	    if (! scalar(@matches)) {
 2824: 		push(@bad_collaborators, $possible_collaborator);
 2825: 	    } else {
 2826: 		push(@good_collaborators, @matches);
 2827: 	    }
 2828: 	}
 2829: 	if (scalar(@good_collaborators) != 0) {
 2830: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2831: 	    foreach my $name (@good_collaborators) {
 2832: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2833: 		push(@col_fullnames, $givenn.' '.$lastname);
 2834: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2835: 	    }
 2836: 	    $result.='</ol><br />'."\n";
 2837: 	    my ($part)=split(/\./,$part);
 2838: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2839: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2840: 		"\n";
 2841: 	}
 2842: 	if (scalar(@bad_collaborators) > 0) {
 2843: 	    $result.='<div class="LC_warning">';
 2844: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2845: 	    $result .= '</div>';
 2846: 	}         
 2847: 	if (scalar(@bad_collaborators > $ncol)) {
 2848: 	    $result .= '<div class="LC_warning">';
 2849: 	    $result .= &mt('This student has submitted too many '.
 2850: 		'collaborators.  Maximum is [_1].',$ncol);
 2851: 	    $result .= '</div>';
 2852: 	}
 2853:     }
 2854:     return ($result,$fullname,\@col_fullnames);
 2855: }
 2856: 
 2857: #--- Retrieve the last submission for all the parts
 2858: sub get_last_submission {
 2859:     my ($returnhash)=@_;
 2860:     my (@string,$timestamp,%lasthidden);
 2861:     if ($$returnhash{'version'}) {
 2862: 	my %lasthash=();
 2863: 	my ($version);
 2864: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2865: 	    foreach my $key (sort(split(/\:/,
 2866: 					$$returnhash{$version.':keys'}))) {
 2867: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2868: 		$timestamp = 
 2869: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2870: 	    }
 2871: 	}
 2872:         my (%typeparts,%randombytry);
 2873:         my $showsurv = 
 2874:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2875:         foreach my $key (sort(keys(%lasthash))) {
 2876:             if ($key =~ /\.type$/) {
 2877:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2878:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2879:                     ($lasthash{$key} eq 'randomizetry')) {
 2880:                     my ($ign,@parts) = split(/\./,$key);
 2881:                     pop(@parts);
 2882:                     my $id = join('.',@parts);
 2883:                     if ($lasthash{$key} eq 'randomizetry') {
 2884:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2885:                     } else {
 2886:                         unless ($showsurv) {
 2887:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2888:                         }
 2889:                     }
 2890:                     delete($lasthash{$key});
 2891:                 }
 2892:             }
 2893:         }
 2894:         my @hidden = keys(%typeparts);
 2895:         my @randomize = keys(%randombytry);
 2896: 	foreach my $key (keys(%lasthash)) {
 2897: 	    next if ($key !~ /\.submission$/);
 2898:             my $hide;
 2899:             if (@hidden) {
 2900:                 foreach my $id (@hidden) {
 2901:                     if ($key =~ /^\Q$id\E/) {
 2902:                         $hide = 'anon';
 2903:                         last;
 2904:                     }
 2905:                 }
 2906:             }
 2907:             unless ($hide) {
 2908:                 if (@randomize) {
 2909:                     foreach my $id (@randomize) {
 2910:                         if ($key =~ /^\Q$id\E/) {
 2911:                             $hide = 'rand';
 2912:                             last;
 2913:                         }
 2914:                     }
 2915:                 }
 2916:             }
 2917: 	    my ($partid,$foo) = split(/submission$/,$key);
 2918: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2919:             push(@string, join(':', $key, $hide, $draft, (
 2920:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2921:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2922: 	}
 2923:     }
 2924:     if (!@string) {
 2925: 	$string[0] =
 2926: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2927:     }
 2928:     return (\@string,\$timestamp);
 2929: }
 2930: 
 2931: #--- High light keywords, with style choosen by user.
 2932: sub keywords_highlight {
 2933:     my $string    = shift;
 2934:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2935:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2936:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2937:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2938:     foreach my $keyword (@keylist) {
 2939: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2940:     }
 2941:     return $string;
 2942: }
 2943: 
 2944: # For Tasks provide a mechanism to display previous version for one specific student
 2945: 
 2946: sub show_previous_task_version {
 2947:     my ($request,$symb) = @_;
 2948:     if ($symb eq '') {
 2949:         $request->print(
 2950:             '<span class="LC_error">'.
 2951:             &mt('Unable to handle ambiguous references.').
 2952:             '</span>');
 2953:         return '';
 2954:     }
 2955:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2956:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2957:     if (!&canview($usec)) {
 2958:         $request->print('<span class="LC_warning">'.
 2959:                         &mt('Unable to view previous version for requested student.').
 2960:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2961:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2962:                         '</span>');
 2963:         return;
 2964:     }
 2965:     my $mode = 'both';
 2966:     my $isTask = ($symb =~/\.task$/);
 2967:     if ($isTask) {
 2968:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2969:             if ($env{'form.fullname'} eq '') {
 2970:                 $env{'form.fullname'} =
 2971:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2972:             }
 2973:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2974:             $request->print("\n\n".
 2975:                             '<div class="LC_grade_show_user">'.
 2976:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2977:                             '</h2>'."\n");
 2978:             &Apache::lonxml::clear_problem_counter();
 2979:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2980:                             {'previousversion' => $env{'form.previousversion'} }));
 2981:             $request->print("\n</div>");
 2982:         }
 2983:     }
 2984:     return;
 2985: }
 2986: 
 2987: sub choose_task_version_form {
 2988:     my ($symb,$uname,$udom,$nomenu) = @_;
 2989:     my $isTask = ($symb =~/\.task$/);
 2990:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2991:     if ($isTask) {
 2992:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2993:                                               $udom,$uname);
 2994:         if (($record{'resource.0.version'} eq '') ||
 2995:             ($record{'resource.0.version'} < 2)) {
 2996:             return ($record{'resource.0.version'},
 2997:                     $record{'resource.0.version'},$result,$js);
 2998:         } else {
 2999:             $current = $record{'resource.0.version'};
 3000:         }
 3001:         if ($env{'form.previousversion'}) {
 3002:             $displayed = $env{'form.previousversion'};
 3003:             $rowtitle = &mt('Choose another version:')
 3004:         } else {
 3005:             $displayed = $current;
 3006:             $rowtitle = &mt('Show earlier version:');
 3007:         }
 3008:         $result = '<div class="LC_left_float">';
 3009:         my $list;
 3010:         my $numversions = 0;
 3011:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3012:             if ($i == $current) {
 3013:                 if (!$env{'form.previousversion'} || $nomenu) {
 3014:                     next;
 3015:                 } else {
 3016:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3017:                     $numversions ++;
 3018:                 }
 3019:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3020:                 unless ($i == $env{'form.previousversion'}) {
 3021:                     $numversions ++;
 3022:                 }
 3023:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3024:             }
 3025:         }
 3026:         if ($numversions) {
 3027:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3028:             $result .=
 3029:                 '<form name="getprev" method="post" action=""'.
 3030:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3031:                 &Apache::loncommon::start_data_table().
 3032:                 &Apache::loncommon::start_data_table_row().
 3033:                 '<th align="left">'.$rowtitle.'</th>'.
 3034:                 '<td><select name="version">'.
 3035:                 '<option>'.&mt('Select').'</option>'.
 3036:                 $list.
 3037:                 '</select></td>'.
 3038:                 &Apache::loncommon::end_data_table_row();
 3039:             unless ($nomenu) {
 3040:                 $result .= &Apache::loncommon::start_data_table_row().
 3041:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3042:                 '<td><span class="LC_nobreak">'.
 3043:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3044:                 &mt('Yes').'</label>'.
 3045:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3046:                 '</span></td>'.
 3047:                 &Apache::loncommon::end_data_table_row();
 3048:             }
 3049:             $result .=
 3050:                 &Apache::loncommon::start_data_table_row().
 3051:                 '<th align="left">&nbsp;</th>'.
 3052:                 '<td>'.
 3053:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3054:                 '</td>'.
 3055:                 &Apache::loncommon::end_data_table_row().
 3056:                 &Apache::loncommon::end_data_table().
 3057:                 '</form>';
 3058:             $js = &previous_display_javascript($nomenu,$current);
 3059:         } elsif ($displayed && $nomenu) {
 3060:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3061:         } else {
 3062:             $result .= &mt('No previous versions to show for this student');
 3063:         }
 3064:         $result .= '</div>';
 3065:     }
 3066:     return ($current,$displayed,$result,$js);
 3067: }
 3068: 
 3069: sub previous_display_javascript {
 3070:     my ($nomenu,$current) = @_;
 3071:     my $js = <<"JSONE";
 3072: <script type="text/javascript">
 3073: // <![CDATA[
 3074: function previousVersion(uname,udom,symb) {
 3075:     var current = '$current';
 3076:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3077:     var prevstr = new RegExp("^\\\\d+\$");
 3078:     if (!prevstr.test(version)) {
 3079:         return false;
 3080:     }
 3081:     var url = '';
 3082:     if (version == current) {
 3083:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3084:     } else {
 3085:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3086:     }
 3087: JSONE
 3088:     if ($nomenu) {
 3089:         $js .= <<"JSTWO";
 3090:     document.location.href = url;
 3091: JSTWO
 3092:     } else {
 3093:         $js .= <<"JSTHREE";
 3094:     var newwin = 0;
 3095:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3096:         if (document.getprev.prevwin[i].checked == true) {
 3097:             newwin = document.getprev.prevwin[i].value;
 3098:         }
 3099:     }
 3100:     if (newwin == 1) {
 3101:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3102:         url = url+'&inhibitmenu=yes';
 3103:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3104:             previousWin = window.open(url,'',options,1);
 3105:         } else {
 3106:             previousWin.location.href = url;
 3107:         }
 3108:         previousWin.focus();
 3109:         return false;
 3110:     } else {
 3111:         document.location.href = url;
 3112:         return false;
 3113:     }
 3114: JSTHREE
 3115:     }
 3116:     $js .= <<"ENDJS";
 3117:     return false;
 3118: }
 3119: // ]]>
 3120: </script>
 3121: ENDJS
 3122: 
 3123: }
 3124: 
 3125: #--- Called from submission routine
 3126: sub processHandGrade {
 3127:     my ($request,$symb) = @_;
 3128:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3129:     my $button = $env{'form.gradeOpt'};
 3130:     my $ngrade = $env{'form.NCT'};
 3131:     my $ntstu  = $env{'form.NTSTU'};
 3132:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3133:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3134: 
 3135:     if ($button eq 'Save & Next') {
 3136: 	my $ctr = 0;
 3137: 	while ($ctr < $ngrade) {
 3138: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3139: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3140:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3141: 	    if ($errorflag eq 'no_score') {
 3142: 		$ctr++;
 3143: 		next;
 3144: 	    }
 3145: 	    if ($errorflag eq 'not_allowed') {
 3146:                 $request->print(
 3147:                     '<span class="LC_error">'
 3148:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3149:                    .'</span>');
 3150: 		$ctr++;
 3151: 		next;
 3152: 	    }
 3153:             if ($numhidden) {
 3154:                 $request->print(
 3155:                     '<span class="LC_info">'
 3156:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3157:                    .'</span><br />');
 3158:             }
 3159: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3160: 	    my ($subject,$message,$msgstatus) = ('','','');
 3161: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3162:             my ($feedurl,$showsymb) =
 3163: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3164: 	    my $messagetail;
 3165: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3166: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3167: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3168: 		$subject.=' ['.$restitle.']';
 3169: 		my (@msgnum) = split(/,/,$includemsg);
 3170: 		foreach (@msgnum) {
 3171: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3172: 		}
 3173: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3174: 		if ($env{'form.withgrades'.$ctr}) {
 3175: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3176: 		    $messagetail = " for <a href=\"".
 3177: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3178: 		}
 3179: 		$msgstatus = 
 3180:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3181: 						     $message.$messagetail,
 3182:                                                      undef,$feedurl,undef,
 3183:                                                      undef,undef,$showsymb,
 3184:                                                      $restitle);
 3185: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3186: 				$msgstatus.'<br />');
 3187: 	    }
 3188: 	    if ($env{'form.collaborator'.$ctr}) {
 3189: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3190: 		foreach my $collabstr (@collabstrs) {
 3191: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3192: 		    foreach my $collaborator (@collaborators) {
 3193: 			my ($errorflag,$pts,$wgt) = 
 3194: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3195: 					   $env{'form.unamedom'.$ctr},$part);
 3196: 			if ($errorflag eq 'not_allowed') {
 3197: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3198: 			    next;
 3199: 			} elsif ($message ne '') {
 3200: 			    my ($baseurl,$showsymb) = 
 3201: 				&get_feedurl_and_symb($symb,$collaborator,
 3202: 						      $udom);
 3203: 			    if ($env{'form.withgrades'.$ctr}) {
 3204: 				$messagetail = " for <a href=\"".
 3205:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3206: 			    }
 3207: 			    $msgstatus = 
 3208: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3209: 			}
 3210: 		    }
 3211: 		}
 3212: 	    }
 3213: 	    $ctr++;
 3214: 	}
 3215:     }
 3216: 
 3217:     my $res_error;
 3218:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3219:     if ($res_error) {
 3220:         $request->print(&navmap_errormsg());
 3221:         return;
 3222:     }
 3223: 
 3224:     my %keyhash = ();
 3225:     if ($numessay) {
 3226: 	# Keywords sorted in alphabatical order
 3227: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3228: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3229: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3230: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3231: 	$env{'form.keywords'} = join(' ',@keywords);
 3232: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3233: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3234: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3235: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3236: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3237:     }
 3238: 
 3239:     if ($env{'form.compmsg'}) {
 3240: 	# message center - Order of message gets changed. Blank line is eliminated.
 3241: 	# New messages are saved in env for the next student.
 3242: 	# All messages are saved in nohist_handgrade.db
 3243: 	my ($ctr,$idx) = (1,1);
 3244: 	while ($ctr <= $env{'form.savemsgN'}) {
 3245: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3246: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3247: 		$idx++;
 3248: 	    }
 3249: 	    $ctr++;
 3250: 	}
 3251: 	$ctr = 0;
 3252: 	while ($ctr < $ngrade) {
 3253: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3254: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3255: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3256: 		$idx++;
 3257: 	    }
 3258: 	    $ctr++;
 3259: 	}
 3260: 	$env{'form.savemsgN'} = --$idx;
 3261: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3262:     }
 3263:     if (($numessay) || ($env{'form.compmsg'})) {
 3264: 	my $putresult = &Apache::lonnet::put
 3265: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3266:     }
 3267: 
 3268:     # Called by Save & Refresh from Highlight Attribute Window
 3269:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3270:     if ($env{'form.refresh'} eq 'on') {
 3271: 	my ($ctr,$total) = (0,0);
 3272: 	while ($ctr < $ngrade) {
 3273: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3274: 	    $ctr++;
 3275: 	}
 3276: 	$env{'form.NTSTU'}=$ngrade;
 3277: 	$ctr = 0;
 3278: 	while ($ctr < $total) {
 3279: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3280: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3281: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3282: 	    &submission($request,$ctr,$total-1,$symb);
 3283: 	    $ctr++;
 3284: 	}
 3285: 	return '';
 3286:     }
 3287: 
 3288:     # Get the next/previous one or group of students
 3289:     my $firststu = $env{'form.unamedom0'};
 3290:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3291:     my $ctr = 2;
 3292:     while ($laststu eq '') {
 3293: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3294: 	$ctr++;
 3295: 	$laststu = $firststu if ($ctr > $ngrade);
 3296:     }
 3297: 
 3298:     my (@parsedlist,@nextlist);
 3299:     my ($nextflg) = 0;
 3300:     foreach my $item (sort 
 3301: 	     {
 3302: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3303: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3304: 		 }
 3305: 		 return $a cmp $b;
 3306: 	     } (keys(%$fullname))) {
 3307: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3308: 	    push(@parsedlist,$item);
 3309: 	}
 3310: 	$nextflg = 1 if ($item eq $laststu);
 3311: 	if ($button eq 'Previous') {
 3312: 	    last if ($item eq $firststu);
 3313: 	    push(@parsedlist,$item);
 3314: 	}
 3315:     }
 3316:     $ctr = 0;
 3317:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3318:     foreach my $student (@parsedlist) {
 3319: 	my $submitonly=$env{'form.submitonly'};
 3320: 	my ($uname,$udom) = split(/:/,$student);
 3321: 	
 3322: 	if ($submitonly eq 'queued') {
 3323: 	    my %queue_status = 
 3324: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3325: 							$udom,$uname);
 3326: 	    next if (!defined($queue_status{'gradingqueue'}));
 3327: 	}
 3328: 
 3329: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3330: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3331: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3332: 	    my $submitted = 0;
 3333: 	    my $ungraded = 0;
 3334: 	    my $incorrect = 0;
 3335: 	    foreach my $item (keys(%status)) {
 3336: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3337: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3338: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3339: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3340: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3341: 		    $submitted = 0;
 3342: 		}
 3343: 	    }
 3344: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3345: 				     $submitonly eq 'incorrect' ||
 3346: 				     $submitonly eq 'graded'));
 3347: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3348: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3349: 	}
 3350: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3351: 	last if ($ctr == $ntstu);
 3352: 	$ctr++;
 3353:     }
 3354: 
 3355:     $ctr = 0;
 3356:     my $total = scalar(@nextlist)-1;
 3357: 
 3358:     foreach (sort(@nextlist)) {
 3359: 	my ($uname,$udom,$submitter) = split(/:/);
 3360: 	$env{'form.student'}  = $uname;
 3361: 	$env{'form.userdom'}  = $udom;
 3362: 	$env{'form.fullname'} = $$fullname{$_};
 3363: 	&submission($request,$ctr,$total,$symb);
 3364: 	$ctr++;
 3365:     }
 3366:     if ($total < 0) {
 3367:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3368: 	$request->print($the_end);
 3369:     }
 3370:     return '';
 3371: }
 3372: 
 3373: #---- Save the score and award for each student, if changed
 3374: sub saveHandGrade {
 3375:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3376:     my @version_parts;
 3377:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3378: 					   $env{'request.course.id'});
 3379:     if (!&canmodify($usec)) { return('not_allowed'); }
 3380:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3381:     my @parts_graded;
 3382:     my %newrecord  = ();
 3383:     my ($pts,$wgt,$totchg) = ('','',0);
 3384:     my %aggregate = ();
 3385:     my $aggregateflag = 0;
 3386:     if ($env{'form.HIDE'.$newflg}) {
 3387:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3388:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3389:         $totchg += $numchgs;
 3390:     }
 3391:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3392:     foreach my $new_part (@parts) {
 3393: 	#collaborator ($submi may vary for different parts
 3394: 	if ($submitter && $new_part ne $part) { next; }
 3395: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3396: 	if ($dropMenu eq 'excused') {
 3397: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3398: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3399: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3400: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3401: 		}
 3402: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3403: 	    }
 3404: 	} elsif ($dropMenu eq 'reset status'
 3405: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3406: 	    foreach my $key (keys(%record)) {
 3407: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3408: 	    }
 3409: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3410: 		"$env{'user.name'}:$env{'user.domain'}";
 3411:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3412: 
 3413:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3414: 					       [$new_part]);
 3415:             my $aggtries =$totaltries;
 3416:             if ($last_resets{$new_part}) {
 3417:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3418: 					   $new_part);
 3419:             }
 3420: 
 3421:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3422:             if ($aggtries > 0) {
 3423:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3424:                 $aggregateflag = 1;
 3425:             }
 3426: 	} elsif ($dropMenu eq '') {
 3427: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3428: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3429: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3430: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3431: 		next;
 3432: 	    }
 3433: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3434: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3435: 	    my $partial= $pts/$wgt;
 3436: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3437: 		#do not update score for part if not changed.
 3438:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3439: 		next;
 3440: 	    } else {
 3441: 	        push(@parts_graded,$new_part);
 3442: 	    }
 3443: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3444: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3445: 	    }
 3446: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3447: 	    if ($partial == 0) {
 3448: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3449: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3450: 		}
 3451: 	    } else {
 3452: 		if ($record{$reckey} ne 'correct_by_override') {
 3453: 		    $newrecord{$reckey} = 'correct_by_override';
 3454: 		}
 3455: 	    }	    
 3456: 	    if ($submitter && 
 3457: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3458: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3459: 	    }
 3460: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3461: 		"$env{'user.name'}:$env{'user.domain'}";
 3462: 	}
 3463: 	# unless problem has been graded, set flag to version the submitted files
 3464: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3465: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3466: 	        $dropMenu eq 'reset status')
 3467: 	   {
 3468: 	    push(@version_parts,$new_part);
 3469: 	}
 3470:     }
 3471:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3472:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3473: 
 3474:     if (%newrecord) {
 3475:         if (@version_parts) {
 3476:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3477:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3478: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3479: 	    foreach my $new_part (@version_parts) {
 3480: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3481: 				$new_part,\%newrecord);
 3482: 	    }
 3483:         }
 3484: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3485: 				$env{'request.course.id'},$domain,$stuname);
 3486: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3487: 				     $cdom,$cnum,$domain,$stuname);
 3488:     }
 3489:     if ($aggregateflag) {
 3490:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3491: 			      $cdom,$cnum);
 3492:     }
 3493:     return ('',$pts,$wgt,$totchg);
 3494: }
 3495: 
 3496: sub makehidden {
 3497:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3498:     return unless (ref($record) eq 'HASH');
 3499:     my %modified;
 3500:     my $numchanged = 0;
 3501:     if (exists($record->{$version.':keys'})) {
 3502:         my $partsregexp = $parts;
 3503:         $partsregexp =~ s/,/|/g;
 3504:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3505:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3506:                  my $item = $1;
 3507:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3508:                      $modified{$key} = $record->{$version.':'.$key};
 3509:                  }
 3510:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3511:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3512:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3513:                 $modified{$key} = $record->{$version.':'.$key};
 3514:             }
 3515:         }
 3516:         if (keys(%modified)) {
 3517:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3518:                                           $domain,$stuname,$tolog) eq 'ok') {
 3519:                 $numchanged ++;
 3520:             }
 3521:         }
 3522:     }
 3523:     return $numchanged;
 3524: }
 3525: 
 3526: sub check_and_remove_from_queue {
 3527:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3528:     my @ungraded_parts;
 3529:     foreach my $part (@{$parts}) {
 3530: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3531: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3532: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3533: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3534: 		) {
 3535: 	    push(@ungraded_parts, $part);
 3536: 	}
 3537:     }
 3538:     if ( !@ungraded_parts ) {
 3539: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3540: 					       $cnum,$domain,$stuname);
 3541:     }
 3542: }
 3543: 
 3544: sub handback_files {
 3545:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3546:     my $portfolio_root = '/userfiles/portfolio';
 3547:     my $res_error;
 3548:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3549:     if ($res_error) {
 3550:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3551:         return;
 3552:     }
 3553:     my @handedback;
 3554:     my $file_msg;
 3555:     my @part_response_id = &flatten_responseType($responseType);
 3556:     foreach my $part_response_id (@part_response_id) {
 3557:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3558: 	my $part_resp = join('_',@{ $part_response_id });
 3559:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3560:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3561:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3562: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3563:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3564:                     my ($directory,$answer_file) = 
 3565:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3566:                     my ($answer_name,$answer_ver,$answer_ext) =
 3567: 		        &file_name_version_ext($answer_file);
 3568: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3569:                     my $getpropath = 1;
 3570:                     my ($dir_list,$listerror) =
 3571:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3572:                                                  $domain,$stuname,$getpropath);
 3573: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3574:                     # fix filename
 3575:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3576:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3577:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3578:             	                                $save_file_name);
 3579:                     if ($result !~ m|^/uploaded/|) {
 3580:                         $request->print('<br /><span class="LC_error">'.
 3581:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3582:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3583:                                         '</span>');
 3584:                     } else {
 3585:                         # mark the file as read only
 3586:                         push(@handedback,$save_file_name);
 3587: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3588: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3589: 			}
 3590:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3591: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3592: 
 3593:                     }
 3594:                     $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>'));
 3595:                 }
 3596:             }
 3597:         }
 3598:     }
 3599:     if (@handedback > 0) {
 3600:         $request->print('<br />');
 3601:         my @what = ($symb,$env{'request.course.id'},'handback');
 3602:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3603:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3604:         my ($subject,$message);
 3605:         if (scalar(@handedback) == 1) {
 3606:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3607:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3608:         } else {
 3609:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3610:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3611:         }
 3612:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3613:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3614:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3615:         my ($feedurl,$showsymb) =
 3616:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3617:         my $restitle = &Apache::lonnet::gettitle($symb);
 3618:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3619:         my $msgstatus =
 3620:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3621:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3622:                  $restitle);
 3623:         if ($msgstatus) {
 3624:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3625:         }
 3626:     }
 3627:     return;
 3628: }
 3629: 
 3630: sub get_feedurl_and_symb {
 3631:     my ($symb,$uname,$udom) = @_;
 3632:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3633:     $url = &Apache::lonnet::clutter($url);
 3634:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3635: 					$symb,$udom,$uname);
 3636:     if ($encrypturl =~ /^yes$/i) {
 3637: 	&Apache::lonenc::encrypted(\$url,1);
 3638: 	&Apache::lonenc::encrypted(\$symb,1);
 3639:     }
 3640:     return ($url,$symb);
 3641: }
 3642: 
 3643: sub get_submitted_files {
 3644:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3645:     my @files;
 3646:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3647:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3648:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3649:     	    push(@files,$file_url.$file);
 3650:         }
 3651:     }
 3652:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3653:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3654:     }
 3655:     return (\@files);
 3656: }
 3657: 
 3658: # ----------- Provides number of tries since last reset.
 3659: sub get_num_tries {
 3660:     my ($record,$last_reset,$part) = @_;
 3661:     my $timestamp = '';
 3662:     my $num_tries = 0;
 3663:     if ($$record{'version'}) {
 3664:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3665:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3666:                 $timestamp = $$record{$version.':timestamp'};
 3667:                 if ($timestamp > $last_reset) {
 3668:                     $num_tries ++;
 3669:                 } else {
 3670:                     last;
 3671:                 }
 3672:             }
 3673:         }
 3674:     }
 3675:     return $num_tries;
 3676: }
 3677: 
 3678: # ----------- Determine decrements required in aggregate totals 
 3679: sub decrement_aggs {
 3680:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3681:     my %decrement = (
 3682:                         attempts => 0,
 3683:                         users => 0,
 3684:                         correct => 0
 3685:                     );
 3686:     $decrement{'attempts'} = $aggtries;
 3687:     if ($solvedstatus =~ /^correct/) {
 3688:         $decrement{'correct'} = 1;
 3689:     }
 3690:     if ($aggtries == $totaltries) {
 3691:         $decrement{'users'} = 1;
 3692:     }
 3693:     foreach my $type (keys(%decrement)) {
 3694:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3695:     }
 3696:     return;
 3697: }
 3698: 
 3699: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3700: sub get_last_resets {
 3701:     my ($symb,$courseid,$partids) =@_;
 3702:     my %last_resets;
 3703:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3704:     my $cname = $env{'course.'.$courseid.'.num'};
 3705:     my @keys;
 3706:     foreach my $part (@{$partids}) {
 3707: 	push(@keys,"$symb\0$part\0resettime");
 3708:     }
 3709:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3710: 				     $cdom,$cname);
 3711:     foreach my $part (@{$partids}) {
 3712: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3713:     }
 3714:     return %last_resets;
 3715: }
 3716: 
 3717: # ----------- Handles creating versions for portfolio files as answers
 3718: sub version_portfiles {
 3719:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3720:     my $version_parts = join('|',@$v_flag);
 3721:     my @returned_keys;
 3722:     my $parts = join('|', @$parts_graded);
 3723:     my $portfolio_root = '/userfiles/portfolio';
 3724:     foreach my $key (keys(%$record)) {
 3725:         my $new_portfiles;
 3726:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3727:             my @versioned_portfiles;
 3728:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3729:             foreach my $file (@portfiles) {
 3730:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3731:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3732: 		my ($answer_name,$answer_ver,$answer_ext) =
 3733: 		    &file_name_version_ext($answer_file);
 3734:                 my $getpropath = 1;
 3735:                 my ($dir_list,$listerror) =
 3736:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3737:                                              $stu_name,$getpropath);
 3738:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3739:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3740:                 if ($new_answer ne 'problem getting file') {
 3741:                     push(@versioned_portfiles, $directory.$new_answer);
 3742:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3743:                         [$directory.$new_answer],
 3744:                         [$symb,$env{'request.course.id'},'graded']);
 3745:                 }
 3746:             }
 3747:             $$record{$key} = join(',',@versioned_portfiles);
 3748:             push(@returned_keys,$key);
 3749:         }
 3750:     } 
 3751:     return (@returned_keys);   
 3752: }
 3753: 
 3754: sub get_next_version {
 3755:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3756:     my $version;
 3757:     if (ref($dir_list) eq 'ARRAY') {
 3758:         foreach my $row (@{$dir_list}) {
 3759:             my ($file) = split(/\&/,$row,2);
 3760:             my ($file_name,$file_version,$file_ext) =
 3761: 	        &file_name_version_ext($file);
 3762:             if (($file_name eq $answer_name) && 
 3763: 	        ($file_ext eq $answer_ext)) {
 3764:                 # gets here if filename and extension match, 
 3765:                 # regardless of version
 3766:                 if ($file_version ne '') {
 3767:                     # a versioned file is found  so save it for later
 3768:                     if ($file_version > $version) {
 3769: 		        $version = $file_version;
 3770:                     }
 3771: 	        }
 3772:             }
 3773:         }
 3774:     }
 3775:     $version ++;
 3776:     return($version);
 3777: }
 3778: 
 3779: sub version_selected_portfile {
 3780:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3781:     my ($answer_name,$answer_ver,$answer_ext) =
 3782:         &file_name_version_ext($file_name);
 3783:     my $new_answer;
 3784:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3785:     if($env{'form.copy'} eq '-1') {
 3786:         $new_answer = 'problem getting file';
 3787:     } else {
 3788:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3789:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3790:                             $stu_name,$domain,'copy',
 3791: 		        '/portfolio'.$directory.$new_answer);
 3792:     }    
 3793:     return ($new_answer);
 3794: }
 3795: 
 3796: sub file_name_version_ext {
 3797:     my ($file)=@_;
 3798:     my @file_parts = split(/\./, $file);
 3799:     my ($name,$version,$ext);
 3800:     if (@file_parts > 1) {
 3801: 	$ext=pop(@file_parts);
 3802: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3803: 	    $version=pop(@file_parts);
 3804: 	}
 3805: 	$name=join('.',@file_parts);
 3806:     } else {
 3807: 	$name=join('.',@file_parts);
 3808:     }
 3809:     return($name,$version,$ext);
 3810: }
 3811: 
 3812: #--------------------------------------------------------------------------------------
 3813: #
 3814: #-------------------------- Next few routines handles grading by section or whole class
 3815: #
 3816: #--- Javascript to handle grading by section or whole class
 3817: sub viewgrades_js {
 3818:     my ($request) = shift;
 3819: 
 3820:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3821:     &js_escape(\$alertmsg);
 3822:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3823:    function writePoint(partid,weight,point) {
 3824: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3825: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3826: 	if (point == "textval") {
 3827: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3828: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3829: 		alert("$alertmsg"+parseFloat(point));
 3830: 		var resetbox = false;
 3831: 		for (var i=0; i<radioButton.length; i++) {
 3832: 		    if (radioButton[i].checked) {
 3833: 			textbox.value = i;
 3834: 			resetbox = true;
 3835: 		    }
 3836: 		}
 3837: 		if (!resetbox) {
 3838: 		    textbox.value = "";
 3839: 		}
 3840: 		return;
 3841: 	    }
 3842: 	    if (parseFloat(point) > parseFloat(weight)) {
 3843: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3844: 				   ") greater than the weight for the part. Accept?");
 3845: 		if (resp == false) {
 3846: 		    textbox.value = "";
 3847: 		    return;
 3848: 		}
 3849: 	    }
 3850: 	    for (var i=0; i<radioButton.length; i++) {
 3851: 		radioButton[i].checked=false;
 3852: 		if (parseFloat(point) == i) {
 3853: 		    radioButton[i].checked=true;
 3854: 		}
 3855: 	    }
 3856: 
 3857: 	} else {
 3858: 	    textbox.value = parseFloat(point);
 3859: 	}
 3860: 	for (i=0;i<document.classgrade.total.value;i++) {
 3861: 	    var user = document.classgrade["ctr"+i].value;
 3862: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3863: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3864: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3865: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3866: 	    if (saveval != "correct") {
 3867: 		scorename.value = point;
 3868: 		if (selname[0].selected != true) {
 3869: 		    selname[0].selected = true;
 3870: 		}
 3871: 	    }
 3872: 	}
 3873: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3874:     }
 3875: 
 3876:     function writeRadText(partid,weight) {
 3877: 	var selval   = document.classgrade["SELVAL_"+partid];
 3878: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3879:         var override = document.classgrade["FORCE_"+partid].checked;
 3880: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3881: 	if (selval[1].selected || selval[2].selected) {
 3882: 	    for (var i=0; i<radioButton.length; i++) {
 3883: 		radioButton[i].checked=false;
 3884: 
 3885: 	    }
 3886: 	    textbox.value = "";
 3887: 
 3888: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3889: 		var user = document.classgrade["ctr"+i].value;
 3890: 		user = user.replace(new RegExp(':', 'g'),"_");
 3891: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3892: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3893: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3894: 		if ((saveval != "correct") || override) {
 3895: 		    scorename.value = "";
 3896: 		    if (selval[1].selected) {
 3897: 			selname[1].selected = true;
 3898: 		    } else {
 3899: 			selname[2].selected = true;
 3900: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3901: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3902: 		    }
 3903: 		}
 3904: 	    }
 3905: 	} else {
 3906: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3907: 		var user = document.classgrade["ctr"+i].value;
 3908: 		user = user.replace(new RegExp(':', 'g'),"_");
 3909: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3910: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3911: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3912: 		if ((saveval != "correct") || override) {
 3913: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3914: 		    selname[0].selected = true;
 3915: 		}
 3916: 	    }
 3917: 	}	    
 3918:     }
 3919: 
 3920:     function changeSelect(partid,user) {
 3921: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3922: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3923: 	var point  = textbox.value;
 3924: 	var weight = document.classgrade["weight_"+partid].value;
 3925: 
 3926: 	if (isNaN(point) || parseFloat(point) < 0) {
 3927: 	    alert("$alertmsg"+parseFloat(point));
 3928: 	    textbox.value = "";
 3929: 	    return;
 3930: 	}
 3931: 	if (parseFloat(point) > parseFloat(weight)) {
 3932: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3933: 			       ") greater than the weight of the part. Accept?");
 3934: 	    if (resp == false) {
 3935: 		textbox.value = "";
 3936: 		return;
 3937: 	    }
 3938: 	}
 3939: 	selval[0].selected = true;
 3940:     }
 3941: 
 3942:     function changeOneScore(partid,user) {
 3943: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3944: 	if (selval[1].selected || selval[2].selected) {
 3945: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3946: 	    if (selval[2].selected) {
 3947: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3948: 	    }
 3949:         }
 3950:     }
 3951: 
 3952:     function resetEntry(numpart) {
 3953: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3954: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3955: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3956: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3957: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3958: 	    for (var i=0; i<radioButton.length; i++) {
 3959: 		radioButton[i].checked=false;
 3960: 
 3961: 	    }
 3962: 	    textbox.value = "";
 3963: 	    selval[0].selected = true;
 3964: 
 3965: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3966: 		var user = document.classgrade["ctr"+i].value;
 3967: 		user = user.replace(new RegExp(':', 'g'),"_");
 3968: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3969: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3970: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3971: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3972: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3973: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3974: 		if (saveselval == "excused") {
 3975: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3976: 		} else {
 3977: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3978: 		}
 3979: 	    }
 3980: 	}
 3981:     }
 3982: 
 3983: VIEWJAVASCRIPT
 3984: }
 3985: 
 3986: #--- show scores for a section or whole class w/ option to change/update a score
 3987: sub viewgrades {
 3988:     my ($request,$symb) = @_;
 3989:     &viewgrades_js($request);
 3990: 
 3991:     #need to make sure we have the correct data for later EXT calls, 
 3992:     #thus invalidate the cache
 3993:     &Apache::lonnet::devalidatecourseresdata(
 3994:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3995:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3996:     &Apache::lonnet::clear_EXT_cache_status();
 3997: 
 3998:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3999: 
 4000:     #view individual student submission form - called using Javascript viewOneStudent
 4001:     $result.=&jscriptNform($symb);
 4002: 
 4003:     #beginning of class grading form
 4004:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4005:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4006: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4007: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4008: 	&build_section_inputs().
 4009: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4010: 
 4011:     #retrieve selected groups
 4012:     my (@groups,$group_display);
 4013:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4014:     if (grep(/^all$/,@groups)) {
 4015:         @groups = ('all');
 4016:     } elsif (grep(/^none$/,@groups)) {
 4017:         @groups = ('none');
 4018:     } elsif (@groups > 0) {
 4019:         $group_display = join(', ',@groups);
 4020:     }
 4021: 
 4022:     my ($common_header,$specific_header,@sections,$section_display);
 4023:     if ($env{'request.course.sec'} ne '') {
 4024:         @sections = ($env{'request.course.sec'});
 4025:     } else {
 4026:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4027:     }
 4028: 
 4029: # Check if Save button should be usable
 4030:     my $disabled = ' disabled="disabled"';
 4031:     if ($perm{'mgr'}) {
 4032:         if (grep(/^all$/,@sections)) {
 4033:             undef($disabled);
 4034:         } else {
 4035:             foreach my $sec (@sections) {
 4036:                 if (&canmodify($sec)) {
 4037:                     undef($disabled);
 4038:                     last;
 4039:                 }
 4040:             }
 4041:         }
 4042:     }
 4043:     if (grep(/^all$/,@sections)) {
 4044:         @sections = ('all');
 4045:         if ($group_display) {
 4046:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4047:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4048:         } elsif (grep(/^none$/,@groups)) {
 4049:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4050:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4051:         } else {
 4052:             $common_header = &mt('Assign Common Grade to Class');
 4053:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4054:         }
 4055:     } elsif (grep(/^none$/,@sections)) {
 4056:         @sections = ('none');
 4057:         if ($group_display) {
 4058:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4059:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4060:         } elsif (grep(/^none$/,@groups)) {
 4061:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4062:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4063:         } else {
 4064:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4065:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4066:         }
 4067:     } else {
 4068:         $section_display = join (", ",@sections);
 4069:         if ($group_display) {
 4070:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4071:                                  $section_display,$group_display);
 4072:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4073:                                    $section_display,$group_display);
 4074:         } elsif (grep(/^none$/,@groups)) {
 4075:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4076:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4077:         } else {
 4078:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4079:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4080:         }
 4081:     }
 4082:     my %submit_types = &substatus_options();
 4083:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4084: 
 4085:     if ($env{'form.submitonly'} eq 'all') {
 4086:         $result.= '<h3>'.$common_header.'</h3>';
 4087:     } else {
 4088:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 4089:     }
 4090:     $result .= &Apache::loncommon::start_data_table();
 4091:     #radio buttons/text box for assigning points for a section or class.
 4092:     #handles different parts of a problem
 4093:     my $res_error;
 4094:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4095:     if ($res_error) {
 4096:         return &navmap_errormsg();
 4097:     }
 4098:     my %weight = ();
 4099:     my $ctsparts = 0;
 4100:     my %seen = ();
 4101:     my @part_response_id = &flatten_responseType($responseType);
 4102:     foreach my $part_response_id (@part_response_id) {
 4103:     	my ($partid,$respid) = @{ $part_response_id };
 4104: 	my $part_resp = join('_',@{ $part_response_id });
 4105: 	next if $seen{$partid};
 4106: 	$seen{$partid}++;
 4107: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4108: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4109: 
 4110: 	my $display_part=&get_display_part($partid,$symb);
 4111: 	my $radio.='<table border="0"><tr>';  
 4112: 	my $ctr = 0;
 4113: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4114: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4115: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4116: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4117: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4118: 	    $ctr++;
 4119: 	}
 4120: 	$radio.='</tr></table>';
 4121: 	my $line = '<input type="text" name="TEXTVAL_'.
 4122: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4123: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4124: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4125: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4126:                 '<select name="SELVAL_'.$partid.'" '.
 4127: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4128: 		$weight{$partid}.')"> '.
 4129: 	    '<option selected="selected"> </option>'.
 4130: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4131: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4132: 	    '</select></td>'.
 4133:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4134: 	$line.='<input type="hidden" name="partid_'.
 4135: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4136: 	$line.='<input type="hidden" name="weight_'.
 4137: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4138: 
 4139: 	$result.=
 4140: 	    &Apache::loncommon::start_data_table_row()."\n".
 4141: 	    '<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>'.
 4142: 	    &Apache::loncommon::end_data_table_row()."\n";
 4143: 	$ctsparts++;
 4144:     }
 4145:     $result.=&Apache::loncommon::end_data_table()."\n".
 4146: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4147:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4148: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4149: 
 4150:     #table listing all the students in a section/class
 4151:     #header of table
 4152:     if ($env{'form.submitonly'} eq 'all') { 
 4153:         $result.= '<h3>'.$specific_header.'</h3>';
 4154:     } else {
 4155:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 4156:     }
 4157:     $result.= &Apache::loncommon::start_data_table().
 4158: 	      &Apache::loncommon::start_data_table_header_row().
 4159: 	      '<th>'.&mt('No.').'</th>'.
 4160: 	      '<th>'.&nameUserString('header')."</th>\n";
 4161:     my $partserror;
 4162:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4163:     if ($partserror) {
 4164:         return &navmap_errormsg();
 4165:     }
 4166:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4167:     my @partids = ();
 4168:     foreach my $part (@parts) {
 4169: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4170:         my $narrowtext = &mt('Tries');
 4171: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4172: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 4173: 	my ($partid) = &split_part_type($part);
 4174:         push(@partids,$partid);
 4175: #
 4176: # FIXME: Looks like $display looks at English text
 4177: #
 4178: 	my $display_part=&get_display_part($partid,$symb);
 4179: 	if ($display =~ /^Partial Credit Factor/) {
 4180: 	    $result.='<th>'.
 4181:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4182:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4183: 	    next;
 4184: 	    
 4185: 	} else {
 4186: 	    if ($display =~ /Problem Status/) {
 4187: 		my $grade_status_mt = &mt('Grade Status');
 4188: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4189: 	    }
 4190: 	    my $part_mt = &mt('Part:');
 4191: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4192: 	}
 4193: 
 4194: 	$result.='<th>'.$display.'</th>'."\n";
 4195:     }
 4196:     $result.=&Apache::loncommon::end_data_table_header_row();
 4197: 
 4198:     my %last_resets = 
 4199: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4200: 
 4201:     #get info for each student
 4202:     #list all the students - with points and grade status
 4203:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4204:     my $ctr = 0;
 4205:     foreach (sort 
 4206: 	     {
 4207: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4208: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4209: 		 }
 4210: 		 return $a cmp $b;
 4211: 	     } (keys(%$fullname))) {
 4212: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4213: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 4214:     }
 4215:     $result.=&Apache::loncommon::end_data_table();
 4216:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4217:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4218: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4219:     if ($ctr == 0) {
 4220:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4221:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4222:                 '<span class="LC_warning">';
 4223:         if ($env{'form.submitonly'} eq 'all') {
 4224:             if (grep(/^all$/,@sections)) {
 4225:                 if (grep(/^all$/,@groups)) {
 4226:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4227:                                    $stu_status);
 4228:                 } elsif (grep(/^none$/,@groups)) {
 4229:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4230:                                    $stu_status);
 4231:                 } else {
 4232:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4233:                                    $group_display,$stu_status);
 4234:                 }
 4235:             } elsif (grep(/^none$/,@sections)) {
 4236:                 if (grep(/^all$/,@groups)) {
 4237:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4238:                                    $stu_status);
 4239:                 } elsif (grep(/^none$/,@groups)) {
 4240:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4241:                                    $stu_status);
 4242:                 } else {
 4243:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4244:                                    $group_display,$stu_status);
 4245:                 }
 4246:             } else {
 4247:                 if (grep(/^all$/,@groups)) {
 4248:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4249:                                    $section_display,$stu_status);
 4250:                 } elsif (grep(/^none$/,@groups)) {
 4251:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4252:                                    $section_display,$stu_status);
 4253:                 } else {
 4254:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4255:                                    $section_display,$group_display,$stu_status);
 4256:                 }
 4257:             }
 4258:         } else {
 4259:             if (grep(/^all$/,@sections)) {
 4260:                 if (grep(/^all$/,@groups)) {
 4261:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4262:                                    $stu_status,$submission_status);
 4263:                 } elsif (grep(/^none$/,@groups)) {
 4264:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4265:                                    $stu_status,$submission_status);
 4266:                 } else {
 4267:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4268:                                    $group_display,$stu_status,$submission_status);
 4269:                 }
 4270:             } elsif (grep(/^none$/,@sections)) {
 4271:                 if (grep(/^all$/,@groups)) {
 4272:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4273:                                    $stu_status,$submission_status);
 4274:                 } elsif (grep(/^none$/,@groups)) {
 4275:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4276:                                    $stu_status,$submission_status);
 4277:                 } else {
 4278:                     $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.',
 4279:                                    $group_display,$stu_status,$submission_status);
 4280:                 }
 4281:             } else {
 4282:                 if (grep(/^all$/,@groups)) {
 4283:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4284:                                    $section_display,$stu_status,$submission_status);
 4285:                 } elsif (grep(/^none$/,@groups)) {
 4286:                     $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.',
 4287:                                    $section_display,$stu_status,$submission_status);
 4288:                 } else {
 4289:                     $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.',
 4290:                                    $section_display,$group_display,$stu_status,$submission_status);
 4291:                 }
 4292:             }
 4293: 	}
 4294: 	$result .= '</span><br />';
 4295:     }
 4296:     return $result;
 4297: }
 4298: 
 4299: #--- call by previous routine to display each student who satisfies submission filter.
 4300: sub viewstudentgrade {
 4301:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4302:     my ($uname,$udom) = split(/:/,$student);
 4303:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4304:     my $submitonly = $env{'form.submitonly'};
 4305:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4306:         my %partstatus = ();
 4307:         if (ref($parts) eq 'ARRAY') {
 4308:             foreach my $apart (@{$parts}) {
 4309:                 my ($part,$type) = &split_part_type($apart);
 4310:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4311:                 $status = 'nothing' if ($status eq '');
 4312:                 $partstatus{$part}      = $status;
 4313:                 my $subkey = "resource.$part.submitted_by";
 4314:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4315:             }
 4316:             my $submitted = 0;
 4317:             my $graded = 0;
 4318:             my $incorrect = 0;
 4319:             foreach my $key (keys(%partstatus)) {
 4320:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4321:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4322:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4323: 
 4324:                 my $partid = (split(/\./,$key))[1];
 4325:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4326:                     $submitted = 0;
 4327:                 }
 4328:             }
 4329:             return if (!$submitted && ($submitonly eq 'yes' ||
 4330:                                        $submitonly eq 'incorrect' ||
 4331:                                        $submitonly eq 'graded'));
 4332:             return if (!$graded && ($submitonly eq 'graded'));
 4333:             return if (!$incorrect && $submitonly eq 'incorrect');
 4334:         }
 4335:     }
 4336:     if ($submitonly eq 'queued') {
 4337:         my ($cdom,$cnum) = split(/_/,$courseid);
 4338:         my %queue_status =
 4339:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4340:                                                     $udom,$uname);
 4341:         return if (!defined($queue_status{'gradingqueue'}));
 4342:     }
 4343:     $$ctr++;
 4344:     my %aggregates = ();
 4345:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4346: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4347: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4348: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4349: 	'\');" target="_self">'.$fullname.'</a> '.
 4350: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4351:     $student=~s/:/_/; # colon doen't work in javascript for names
 4352:     foreach my $apart (@$parts) {
 4353: 	my ($part,$type) = &split_part_type($apart);
 4354: 	my $score=$record{"resource.$part.$type"};
 4355:         $result.='<td align="center">';
 4356:         my ($aggtries,$totaltries);
 4357:         unless (exists($aggregates{$part})) {
 4358: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4359: 
 4360: 	    $aggtries = $totaltries;
 4361:             if ($$last_resets{$part}) {  
 4362:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4363: 					   $part);
 4364:             }
 4365:             $result.='<input type="hidden" name="'.
 4366:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4367:             $result.='<input type="hidden" name="'.
 4368:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4369:             $aggregates{$part} = 1;
 4370:         }
 4371: 	if ($type eq 'awarded') {
 4372: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4373: 	    $result.='<input type="hidden" name="'.
 4374: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4375: 	    $result.='<input type="text" name="'.
 4376: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4377:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4378: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4379: 	} elsif ($type eq 'solved') {
 4380: 	    my ($status,$foo)=split(/_/,$score,2);
 4381: 	    $status = 'nothing' if ($status eq '');
 4382: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4383: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4384: 	    $result.='&nbsp;<select name="'.
 4385: 		'GD_'.$student.'_'.$part.'_solved" '.
 4386:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4387: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4388: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4389: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4390: 	    $result.="</select>&nbsp;</td>\n";
 4391: 	} else {
 4392: 	    $result.='<input type="hidden" name="'.
 4393: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4394: 		    "\n";
 4395: 	    $result.='<input type="text" name="'.
 4396: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4397: 		'value="'.$score.'" size="4" /></td>'."\n";
 4398: 	}
 4399:     }
 4400:     $result.=&Apache::loncommon::end_data_table_row();
 4401:     return $result;
 4402: }
 4403: 
 4404: #--- change scores for all the students in a section/class
 4405: #    record does not get update if unchanged
 4406: sub editgrades {
 4407:     my ($request,$symb) = @_;
 4408: 
 4409:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4410:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4411:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4412: 
 4413:     my $result= &Apache::loncommon::start_data_table().
 4414: 	&Apache::loncommon::start_data_table_header_row().
 4415: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4416: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4417:     my %scoreptr = (
 4418: 		    'correct'  =>'correct_by_override',
 4419: 		    'incorrect'=>'incorrect_by_override',
 4420: 		    'excused'  =>'excused',
 4421: 		    'ungraded' =>'ungraded_attempted',
 4422:                     'credited' =>'credit_attempted',
 4423: 		    'nothing'  => '',
 4424: 		    );
 4425:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4426: 
 4427:     my (@partid);
 4428:     my %weight = ();
 4429:     my %columns = ();
 4430:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4431: 
 4432:     my $partserror;
 4433:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4434:     if ($partserror) {
 4435:         return &navmap_errormsg();
 4436:     }
 4437:     my $header;
 4438:     while ($ctr < $env{'form.totalparts'}) {
 4439: 	my $partid = $env{'form.partid_'.$ctr};
 4440: 	push(@partid,$partid);
 4441: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4442: 	$ctr++;
 4443:     }
 4444:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4445:     my $totcolspan = 0;
 4446:     foreach my $partid (@partid) {
 4447: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4448: 	    '<th align="center">'.&mt('New Score').'</th>';
 4449: 	$columns{$partid}=2;
 4450: 	foreach my $stores (@parts) {
 4451: 	    my ($part,$type) = &split_part_type($stores);
 4452: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4453: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4454: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4455: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4456:             my $narrowtext = &mt('Tries');
 4457: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4458: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4459: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4460: 	    $columns{$partid}+=2;
 4461: 	}
 4462:         $totcolspan += $columns{$partid};
 4463:     }
 4464:     foreach my $partid (@partid) {
 4465: 	my $display_part=&get_display_part($partid,$symb);
 4466: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4467: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4468: 	    '</th>';
 4469: 
 4470:     }
 4471:     $result .= &Apache::loncommon::end_data_table_header_row().
 4472: 	&Apache::loncommon::start_data_table_header_row().
 4473: 	$header.
 4474: 	&Apache::loncommon::end_data_table_header_row();
 4475:     my @noupdate;
 4476:     my ($updateCtr,$noupdateCtr) = (1,1);
 4477:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4478: 	my $user = $env{'form.ctr'.$i};
 4479: 	my ($uname,$udom)=split(/:/,$user);
 4480: 	my %newrecord;
 4481: 	my $updateflag = 0;
 4482:         my $usec=$classlist->{"$uname:$udom"}[5];
 4483:         my $canmodify = &canmodify($usec);
 4484:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4485:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4486:         if (!$canmodify) {
 4487:             push(@noupdate,
 4488:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4489:                  &mt('Not allowed to modify student')."</span></td>");
 4490:             next;
 4491:         }
 4492:         my %aggregate = ();
 4493:         my $aggregateflag = 0;
 4494: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4495: 	foreach (@partid) {
 4496: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4497: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4498: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4499: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4500: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4501: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4502: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4503: 	    my $score;
 4504: 	    if ($partial eq '') {
 4505: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4506: 	    } elsif ($partial > 0) {
 4507: 		$score = 'correct_by_override';
 4508: 	    } elsif ($partial == 0) {
 4509: 		$score = 'incorrect_by_override';
 4510: 	    }
 4511: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4512: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4513: 
 4514: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4515: 		"$env{'user.name'}:$env{'user.domain'}";
 4516: 	    if ($dropMenu eq 'reset status' &&
 4517: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4518: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4519: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4520: 		$newrecord{'resource.'.$_.'.award'} = '';
 4521: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4522: 		$updateflag = 1;
 4523:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4524:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4525:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4526:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4527:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4528:                     $aggregateflag = 1;
 4529:                 }
 4530: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4531: 		$updateflag = 1;
 4532: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4533: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4534: 		$rec_update++;
 4535: 	    }
 4536: 
 4537: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4538: 		'<td align="center">'.$awarded.
 4539: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4540: 
 4541: 
 4542: 	    my $partid=$_;
 4543: 	    foreach my $stores (@parts) {
 4544: 		my ($part,$type) = &split_part_type($stores);
 4545: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4546: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4547: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4548: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4549: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4550: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4551: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4552: 		    $updateflag=1;
 4553: 		}
 4554: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4555: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4556: 	    }
 4557: 	}
 4558: 	$line.="\n";
 4559: 
 4560: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4561: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4562: 
 4563: 	if ($updateflag) {
 4564: 	    $count++;
 4565: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4566: 				    $udom,$uname);
 4567: 
 4568: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4569: 					      $cnum,$udom,$uname)) {
 4570: 		# need to figure out if should be in queue.
 4571: 		my %record =  
 4572: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4573: 					     $udom,$uname);
 4574: 		my $all_graded = 1;
 4575: 		my $none_graded = 1;
 4576: 		foreach my $part (@parts) {
 4577: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4578: 			$all_graded = 0;
 4579: 		    } else {
 4580: 			$none_graded = 0;
 4581: 		    }
 4582: 		}
 4583: 
 4584: 		if ($all_graded || $none_graded) {
 4585: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4586: 							   $symb,$cdom,$cnum,
 4587: 							   $udom,$uname);
 4588: 		}
 4589: 	    }
 4590: 
 4591: 	    $result.=&Apache::loncommon::start_data_table_row().
 4592: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4593: 		&Apache::loncommon::end_data_table_row();
 4594: 	    $updateCtr++;
 4595: 	} else {
 4596: 	    push(@noupdate,
 4597: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4598: 	    $noupdateCtr++;
 4599: 	}
 4600:         if ($aggregateflag) {
 4601:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4602: 				  $cdom,$cnum);
 4603:         }
 4604:     }
 4605:     if (@noupdate) {
 4606:         my $numcols=$totcolspan+2;
 4607: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4608: 	    '<td align="center" colspan="'.$numcols.'">'.
 4609: 	    &mt('No Changes Occurred For the Students Below').
 4610: 	    '</td>'.
 4611: 	    &Apache::loncommon::end_data_table_row();
 4612: 	foreach my $line (@noupdate) {
 4613: 	    $result.=
 4614: 		&Apache::loncommon::start_data_table_row().
 4615: 		$line.
 4616: 		&Apache::loncommon::end_data_table_row();
 4617: 	}
 4618:     }
 4619:     $result .= &Apache::loncommon::end_data_table();
 4620:     my $msg = '<p><b>'.
 4621: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4622: 	    $rec_update,$count).'</b><br />'.
 4623: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4624: 	'</b></p>';
 4625:     return $title.$msg.$result;
 4626: }
 4627: 
 4628: sub split_part_type {
 4629:     my ($partstr) = @_;
 4630:     my ($temp,@allparts)=split(/_/,$partstr);
 4631:     my $type=pop(@allparts);
 4632:     my $part=join('_',@allparts);
 4633:     return ($part,$type);
 4634: }
 4635: 
 4636: #------------- end of section for handling grading by section/class ---------
 4637: #
 4638: #----------------------------------------------------------------------------
 4639: 
 4640: 
 4641: #----------------------------------------------------------------------------
 4642: #
 4643: #-------------------------- Next few routines handles grading by csv upload
 4644: #
 4645: #--- Javascript to handle csv upload
 4646: sub csvupload_javascript_reverse_associate {
 4647:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4648:     my $error2=&mt('You need to specify at least one grading field');
 4649:   &js_escape(\$error1);
 4650:   &js_escape(\$error2);
 4651:   return(<<ENDPICK);
 4652:   function verify(vf) {
 4653:     var foundsomething=0;
 4654:     var founduname=0;
 4655:     var foundID=0;
 4656:     for (i=0;i<=vf.nfields.value;i++) {
 4657:       tw=eval('vf.f'+i+'.selectedIndex');
 4658:       if (i==0 && tw!=0) { foundID=1; }
 4659:       if (i==1 && tw!=0) { founduname=1; }
 4660:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4661:     }
 4662:     if (founduname==0 && foundID==0) {
 4663: 	alert('$error1');
 4664: 	return;
 4665:     }
 4666:     if (foundsomething==0) {
 4667: 	alert('$error2');
 4668: 	return;
 4669:     }
 4670:     vf.submit();
 4671:   }
 4672:   function flip(vf,tf) {
 4673:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4674:     var i;
 4675:     for (i=0;i<=vf.nfields.value;i++) {
 4676:       //can not pick the same destination field for both name and domain
 4677:       if (((i ==0)||(i ==1)) && 
 4678:           ((tf==0)||(tf==1)) && 
 4679:           (i!=tf) &&
 4680:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4681:         eval('vf.f'+i+'.selectedIndex=0;')
 4682:       }
 4683:     }
 4684:   }
 4685: ENDPICK
 4686: }
 4687: 
 4688: sub csvupload_javascript_forward_associate {
 4689:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4690:     my $error2=&mt('You need to specify at least one grading field');
 4691:   &js_escape(\$error1);
 4692:   &js_escape(\$error2);
 4693:   return(<<ENDPICK);
 4694:   function verify(vf) {
 4695:     var foundsomething=0;
 4696:     var founduname=0;
 4697:     var foundID=0;
 4698:     for (i=0;i<=vf.nfields.value;i++) {
 4699:       tw=eval('vf.f'+i+'.selectedIndex');
 4700:       if (tw==1) { foundID=1; }
 4701:       if (tw==2) { founduname=1; }
 4702:       if (tw>3) { foundsomething=1; }
 4703:     }
 4704:     if (founduname==0 && foundID==0) {
 4705: 	alert('$error1');
 4706: 	return;
 4707:     }
 4708:     if (foundsomething==0) {
 4709: 	alert('$error2');
 4710: 	return;
 4711:     }
 4712:     vf.submit();
 4713:   }
 4714:   function flip(vf,tf) {
 4715:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4716:     var i;
 4717:     //can not pick the same destination field twice
 4718:     for (i=0;i<=vf.nfields.value;i++) {
 4719:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4720:         eval('vf.f'+i+'.selectedIndex=0;')
 4721:       }
 4722:     }
 4723:   }
 4724: ENDPICK
 4725: }
 4726: 
 4727: sub csvuploadmap_header {
 4728:     my ($request,$symb,$datatoken,$distotal)= @_;
 4729:     my $javascript;
 4730:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4731: 	$javascript=&csvupload_javascript_reverse_associate();
 4732:     } else {
 4733: 	$javascript=&csvupload_javascript_forward_associate();
 4734:     }
 4735: 
 4736:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4737:     my $ignore=&mt('Ignore First Line');
 4738:     $symb = &Apache::lonenc::check_encrypt($symb);
 4739:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4740:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4741:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4742:     my $reverse=&mt("Reverse Association");
 4743:     $request->print(<<ENDPICK);
 4744: <br />
 4745: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4746: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4747: <input type="hidden" name="associate"  value="" />
 4748: <input type="hidden" name="phase"      value="three" />
 4749: <input type="hidden" name="datatoken"  value="$datatoken" />
 4750: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4751: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4752: <input type="hidden" name="upfile_associate" 
 4753:                                        value="$env{'form.upfile_associate'}" />
 4754: <input type="hidden" name="symb"       value="$symb" />
 4755: <input type="hidden" name="command"    value="csvuploadoptions" />
 4756: <hr />
 4757: ENDPICK
 4758:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4759:     return '';
 4760: 
 4761: }
 4762: 
 4763: sub csvupload_fields {
 4764:     my ($symb,$errorref) = @_;
 4765:     my (@parts) = &getpartlist($symb,$errorref);
 4766:     if (ref($errorref)) {
 4767:         if ($$errorref) {
 4768:             return;
 4769:         }
 4770:     }
 4771: 
 4772:     my @fields=(['ID','Student/Employee ID'],
 4773: 		['username','Student Username'],
 4774: 		['domain','Student Domain']);
 4775:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4776:     foreach my $part (sort(@parts)) {
 4777: 	my @datum;
 4778: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4779: 	my $name=$part;
 4780: 	if  (!$display) { $display = $name; }
 4781: 	@datum=($name,$display);
 4782: 	if ($name=~/^stores_(.*)_awarded/) {
 4783: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4784: 	}
 4785: 	push(@fields,\@datum);
 4786:     }
 4787:     return (@fields);
 4788: }
 4789: 
 4790: sub csvuploadmap_footer {
 4791:     my ($request,$i,$keyfields) =@_;
 4792:     my $buttontext = &mt('Assign Grades');
 4793:     $request->print(<<ENDPICK);
 4794: </table>
 4795: <input type="hidden" name="nfields" value="$i" />
 4796: <input type="hidden" name="keyfields" value="$keyfields" />
 4797: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4798: </form>
 4799: ENDPICK
 4800: }
 4801: 
 4802: sub checkforfile_js {
 4803:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4804:     &js_escape(\$alertmsg);
 4805:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4806:     function checkUpload(formname) {
 4807: 	if (formname.upfile.value == "") {
 4808: 	    alert("$alertmsg");
 4809: 	    return false;
 4810: 	}
 4811: 	formname.submit();
 4812:     }
 4813: CSVFORMJS
 4814:     return $result;
 4815: }
 4816: 
 4817: sub upcsvScores_form {
 4818:     my ($request,$symb) = @_;
 4819:     if (!$symb) {return '';}
 4820:     my $result=&checkforfile_js();
 4821:     $result.=&Apache::loncommon::start_data_table().
 4822:              &Apache::loncommon::start_data_table_header_row().
 4823:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4824:              &Apache::loncommon::end_data_table_header_row().
 4825:              &Apache::loncommon::start_data_table_row().'<td>';
 4826:     my $upload=&mt("Upload Scores");
 4827:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4828:     my $ignore=&mt('Ignore First Line');
 4829:     $symb = &Apache::lonenc::check_encrypt($symb);
 4830:     $result.=<<ENDUPFORM;
 4831: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4832: <input type="hidden" name="symb" value="$symb" />
 4833: <input type="hidden" name="command" value="csvuploadmap" />
 4834: $upfile_select
 4835: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4836: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4837: </form>
 4838: ENDUPFORM
 4839:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4840:                            &mt("How do I create a CSV file from a spreadsheet")).
 4841:             '</td>'.
 4842:             &Apache::loncommon::end_data_table_row().
 4843:             &Apache::loncommon::end_data_table();
 4844:     return $result;
 4845: }
 4846: 
 4847: 
 4848: sub csvuploadmap {
 4849:     my ($request,$symb) = @_;
 4850:     if (!$symb) {return '';}
 4851: 
 4852:     my $datatoken;
 4853:     if (!$env{'form.datatoken'}) {
 4854: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4855:     } else {
 4856:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4857:         if ($datatoken ne '') { 
 4858: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4859:         }
 4860:     }
 4861:     my @records=&Apache::loncommon::upfile_record_sep();
 4862:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4863:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4864:     my ($i,$keyfields);
 4865:     if (@records) {
 4866:         my $fieldserror;
 4867: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4868:         if ($fieldserror) {
 4869:             $request->print(&navmap_errormsg());
 4870:             return;
 4871:         }
 4872: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4873: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4874: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4875: 							  \@fields);
 4876: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4877: 	    chop($keyfields);
 4878: 	} else {
 4879: 	    unshift(@fields,['none','']);
 4880: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4881: 							    \@fields);
 4882:             foreach my $rec (@records) {
 4883:                 my %temp = &Apache::loncommon::record_sep($rec);
 4884:                 if (%temp) {
 4885:                     $keyfields=join(',',sort(keys(%temp)));
 4886:                     last;
 4887:                 }
 4888:             }
 4889: 	}
 4890:     }
 4891:     &csvuploadmap_footer($request,$i,$keyfields);
 4892: 
 4893:     return '';
 4894: }
 4895: 
 4896: sub csvuploadoptions {
 4897:     my ($request,$symb)= @_;
 4898:     my $overwrite=&mt('Overwrite any existing score');
 4899:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4900:     my $ignore=&mt('Ignore First Line');
 4901:     $request->print(<<ENDPICK);
 4902: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4903: <input type="hidden" name="command"    value="csvuploadassign" />
 4904: <p>
 4905: <label>
 4906:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4907:    $overwrite
 4908: </label>
 4909: </p>
 4910: ENDPICK
 4911:     my %fields=&get_fields();
 4912:     if (!defined($fields{'domain'})) {
 4913: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4914:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4915:     }
 4916:     foreach my $key (sort(keys(%env))) {
 4917: 	if ($key !~ /^form\.(.*)$/) { next; }
 4918: 	my $cleankey=$1;
 4919: 	if ($cleankey eq 'command') { next; }
 4920: 	$request->print('<input type="hidden" name="'.$cleankey.
 4921: 			'"  value="'.$env{$key}.'" />'."\n");
 4922:     }
 4923:     # FIXME do a check for any duplicated user ids...
 4924:     # FIXME do a check for any invalid user ids?...
 4925:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4926: <hr /></form>'."\n");
 4927:     return '';
 4928: }
 4929: 
 4930: sub get_fields {
 4931:     my %fields;
 4932:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4933:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4934: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4935: 	    if ($env{'form.f'.$i} ne 'none') {
 4936: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4937: 	    }
 4938: 	} else {
 4939: 	    if ($env{'form.f'.$i} ne 'none') {
 4940: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4941: 	    }
 4942: 	}
 4943:     }
 4944:     return %fields;
 4945: }
 4946: 
 4947: sub csvuploadassign {
 4948:     my ($request,$symb) = @_;
 4949:     if (!$symb) {return '';}
 4950:     my $error_msg = '';
 4951:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4952:     if ($datatoken ne '') {
 4953:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4954:     }
 4955:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4956:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4957:     my %fields=&get_fields();
 4958:     my $courseid=$env{'request.course.id'};
 4959:     my ($classlist) = &getclasslist('all',0);
 4960:     my @notallowed;
 4961:     my @skipped;
 4962:     my @warnings;
 4963:     my $countdone=0;
 4964:     foreach my $grade (@gradedata) {
 4965: 	my %entries=&Apache::loncommon::record_sep($grade);
 4966: 	my $domain;
 4967: 	if ($entries{$fields{'domain'}}) {
 4968: 	    $domain=$entries{$fields{'domain'}};
 4969: 	} else {
 4970: 	    $domain=$env{'form.default_domain'};
 4971: 	}
 4972: 	$domain=~s/\s//g;
 4973: 	my $username=$entries{$fields{'username'}};
 4974: 	$username=~s/\s//g;
 4975: 	if (!$username) {
 4976: 	    my $id=$entries{$fields{'ID'}};
 4977: 	    $id=~s/\s//g;
 4978: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4979: 	    $username=$ids{$id};
 4980: 	}
 4981: 	if (!exists($$classlist{"$username:$domain"})) {
 4982: 	    my $id=$entries{$fields{'ID'}};
 4983: 	    $id=~s/\s//g;
 4984: 	    if ($id) {
 4985: 		push(@skipped,"$id:$domain");
 4986: 	    } else {
 4987: 		push(@skipped,"$username:$domain");
 4988: 	    }
 4989: 	    next;
 4990: 	}
 4991: 	my $usec=$classlist->{"$username:$domain"}[5];
 4992: 	if (!&canmodify($usec)) {
 4993: 	    push(@notallowed,"$username:$domain");
 4994: 	    next;
 4995: 	}
 4996: 	my %points;
 4997: 	my %grades;
 4998: 	foreach my $dest (keys(%fields)) {
 4999: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5000: 		$dest eq 'domain') { next; }
 5001: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5002: 	    if ($dest=~/stores_(.*)_points/) {
 5003: 		my $part=$1;
 5004: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5005: 					      $symb,$domain,$username);
 5006:                 if ($wgt) {
 5007:                     $entries{$fields{$dest}}=~s/\s//g;
 5008:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5009:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5010:                                           : 'correct_by_override';
 5011:                     if ($pcr>1) {
 5012:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5013:                     }
 5014:                     $grades{"resource.$part.awarded"}=$pcr;
 5015:                     $grades{"resource.$part.solved"}=$award;
 5016:                     $points{$part}=1;
 5017:                 } else {
 5018:                     $error_msg = "<br />" .
 5019:                         &mt("Some point values were assigned"
 5020:                             ." for problems with a weight "
 5021:                             ."of zero. These values were "
 5022:                             ."ignored.");
 5023:                 }
 5024: 	    } else {
 5025: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5026: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5027: 		my $store_key=$dest;
 5028: 		$store_key=~s/^stores/resource/;
 5029: 		$store_key=~s/_/\./g;
 5030: 		$grades{$store_key}=$entries{$fields{$dest}};
 5031: 	    }
 5032: 	}
 5033: 	if (! %grades) {
 5034:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5035:         } else {
 5036: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5037: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5038: 					   $env{'request.course.id'},
 5039: 					   $domain,$username);
 5040: 	   if ($result eq 'ok') {
 5041: # Successfully stored
 5042: 	      $request->print('.');
 5043: # Remove from grading queue
 5044:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5045:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5046:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5047:                                              $domain,$username);
 5048: 	   } else {
 5049: 	      $request->print("<p><span class=\"LC_error\">".
 5050:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5051:                                   "$username:$domain",$result)."</span></p>");
 5052: 	   }
 5053: 	   $request->rflush();
 5054: 	   $countdone++;
 5055:         }
 5056:     }
 5057:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5058:     if (@warnings) {
 5059:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5060:         $request->print(join(', ',@warnings));
 5061:     }
 5062:     if (@skipped) {
 5063: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5064:         $request->print(join(', ',@skipped));
 5065:     }
 5066:     if (@notallowed) {
 5067: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5068: 	$request->print(join(', ',@notallowed));
 5069:     }
 5070:     $request->print("<br />\n");
 5071:     return $error_msg;
 5072: }
 5073: #------------- end of section for handling csv file upload ---------
 5074: #
 5075: #-------------------------------------------------------------------
 5076: #
 5077: #-------------- Next few routines handle grading by page/sequence
 5078: #
 5079: #--- Select a page/sequence and a student to grade
 5080: sub pickStudentPage {
 5081:     my ($request,$symb) = @_;
 5082: 
 5083:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5084:     &js_escape(\$alertmsg);
 5085:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5086: 
 5087: function checkPickOne(formname) {
 5088:     if (radioSelection(formname.student) == null) {
 5089: 	alert("$alertmsg");
 5090: 	return;
 5091:     }
 5092:     ptr = pullDownSelection(formname.selectpage);
 5093:     formname.page.value = formname["page"+ptr].value;
 5094:     formname.title.value = formname["title"+ptr].value;
 5095:     formname.submit();
 5096: }
 5097: 
 5098: LISTJAVASCRIPT
 5099:     &commonJSfunctions($request);
 5100: 
 5101:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5102:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5103:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5104:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5105: 
 5106:     my $result='<h3><span class="LC_info">&nbsp;'.
 5107: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5108: 
 5109:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5110:     my $map_error;
 5111:     my ($titles,$symbx) = &getSymbMap($map_error);
 5112:     if ($map_error) {
 5113:         $request->print(&navmap_errormsg());
 5114:         return; 
 5115:     }
 5116:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5117: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5118: #    my $type=($curpage =~ /\.(page|sequence)/);
 5119: 
 5120:     # Collection of hidden fields
 5121:     my $ctr=0;
 5122:     foreach (@$titles) {
 5123: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5124: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5125: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5126: 	$ctr++;
 5127:     }
 5128:     $result.='<input type="hidden" name="page" />'."\n".
 5129: 	'<input type="hidden" name="title" />'."\n";
 5130: 
 5131:     $result.=&build_section_inputs();
 5132:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5133:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5134:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5135:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5136: 
 5137:     # Show grading options
 5138:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5139:     my $select = '<select name="selectpage">'."\n";
 5140:     $ctr=0;
 5141:     foreach (@$titles) {
 5142:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5143:         $select.='<option value="'.$ctr.'"'.
 5144:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5145:             '>'.$showtitle.'</option>'."\n";
 5146:         $ctr++;
 5147:     }
 5148:     $select.= '</select>';
 5149: 
 5150:     $result.=
 5151:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5152:        .$select
 5153:        .&Apache::lonhtmlcommon::row_closure();
 5154: 
 5155:     $result.=
 5156:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5157:        .'<label><input type="radio" name="vProb" value="no"'
 5158:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5159:        .'<label><input type="radio" name="vProb" value="yes" />'
 5160:            .&mt('yes').'</label>'."\n"
 5161:        .&Apache::lonhtmlcommon::row_closure();
 5162: 
 5163:     $result.=
 5164:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5165:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5166:            .&mt('none').' </label>'."\n"
 5167:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5168:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5169:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5170:            .&mt('all submissions with details').' </label>'
 5171:        .&Apache::lonhtmlcommon::row_closure();
 5172: 
 5173:     $result.=
 5174:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5175:        .'<input type="text" name="CODE" value="" />'
 5176:        .&Apache::lonhtmlcommon::row_closure(1)
 5177:        .&Apache::lonhtmlcommon::end_pick_box();
 5178: 
 5179:     # Show list of students to select for grading
 5180:     $result.='<br /><input type="button" '.
 5181:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5182: 
 5183:     $request->print($result);
 5184: 
 5185:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5186: 	&Apache::loncommon::start_data_table().
 5187: 	&Apache::loncommon::start_data_table_header_row().
 5188: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5189: 	'<th>'.&nameUserString('header').'</th>'.
 5190: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5191: 	'<th>'.&nameUserString('header').'</th>'.
 5192: 	&Apache::loncommon::end_data_table_header_row();
 5193:  
 5194:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5195:     my $ptr = 1;
 5196:     foreach my $student (sort 
 5197: 			 {
 5198: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5199: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5200: 			     }
 5201: 			     return $a cmp $b;
 5202: 			 } (keys(%$fullname))) {
 5203: 	my ($uname,$udom) = split(/:/,$student);
 5204: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5205:                                   : '</td>');
 5206: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5207: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5208: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5209: 	$studentTable.=
 5210: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5211:                          : '');
 5212: 	$ptr++;
 5213:     }
 5214:     if ($ptr%2 == 0) {
 5215: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5216: 	    &Apache::loncommon::end_data_table_row();
 5217:     }
 5218:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5219:     $studentTable.='<input type="button" '.
 5220:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5221: 
 5222:     $request->print($studentTable);
 5223: 
 5224:     return '';
 5225: }
 5226: 
 5227: sub getSymbMap {
 5228:     my ($map_error) = @_;
 5229:     my $navmap = Apache::lonnavmaps::navmap->new();
 5230:     unless (ref($navmap)) {
 5231:         if (ref($map_error)) {
 5232:             $$map_error = 'navmap';
 5233:         }
 5234:         return;
 5235:     }
 5236:     my %symbx = ();
 5237:     my @titles = ();
 5238:     my $minder = 0;
 5239: 
 5240:     # Gather every sequence that has problems.
 5241:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5242: 					       1,0,1);
 5243:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5244: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5245: 	    my $title = $minder.'.'.
 5246: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5247: 	    push(@titles, $title); # minder in case two titles are identical
 5248: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5249: 	    $minder++;
 5250: 	}
 5251:     }
 5252:     return \@titles,\%symbx;
 5253: }
 5254: 
 5255: #
 5256: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5257: sub displayPage {
 5258:     my ($request,$symb) = @_;
 5259:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5260:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5261:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5262:     my $pageTitle = $env{'form.page'};
 5263:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5264:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5265:     my $usec=$classlist->{$env{'form.student'}}[5];
 5266: 
 5267:     #need to make sure we have the correct data for later EXT calls, 
 5268:     #thus invalidate the cache
 5269:     &Apache::lonnet::devalidatecourseresdata(
 5270:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5271:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5272:     &Apache::lonnet::clear_EXT_cache_status();
 5273: 
 5274:     if (!&canview($usec)) {
 5275: 	$request->print(
 5276:             '<span class="LC_warning">'.
 5277:             &mt('Unable to view requested student. ([_1])',
 5278:                 $env{'form.student'}).
 5279:             '</span>');
 5280:         return;
 5281:     }
 5282:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5283:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5284: 	'</h3>'."\n";
 5285:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5286:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5287: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5288:     } else {
 5289: 	delete($env{'form.CODE'});
 5290:     }
 5291:     &sub_page_js($request);
 5292:     $request->print($result);
 5293: 
 5294:     my $navmap = Apache::lonnavmaps::navmap->new();
 5295:     unless (ref($navmap)) {
 5296:         $request->print(&navmap_errormsg());
 5297:         return;
 5298:     }
 5299:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5300:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5301:     if (!$map) {
 5302: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5303: 	return; 
 5304:     }
 5305:     my $iterator = $navmap->getIterator($map->map_start(),
 5306: 					$map->map_finish());
 5307: 
 5308:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5309: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5310: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5311: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5312: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5313: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5314: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5315: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5316: 
 5317:     if (defined($env{'form.CODE'})) {
 5318: 	$studentTable.=
 5319: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5320:     }
 5321:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5322: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5323: 
 5324:     $studentTable.='&nbsp;<span class="LC_info">'.
 5325:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5326:         '</span>'."\n".
 5327: 	&Apache::loncommon::start_data_table().
 5328: 	&Apache::loncommon::start_data_table_header_row().
 5329: 	'<th>'.&mt('Prob.').'</th>'.
 5330: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5331: 	&Apache::loncommon::end_data_table_header_row();
 5332: 
 5333:     &Apache::lonxml::clear_problem_counter();
 5334:     my ($depth,$question,$prob) = (1,1,1);
 5335:     $iterator->next(); # skip the first BEGIN_MAP
 5336:     my $curRes = $iterator->next(); # for "current resource"
 5337:     while ($depth > 0) {
 5338:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5339:         if($curRes == $iterator->END_MAP) { $depth--; }
 5340: 
 5341:         if (ref($curRes) && $curRes->is_problem()) {
 5342: 	    my $parts = $curRes->parts();
 5343:             my $title = $curRes->compTitle();
 5344: 	    my $symbx = $curRes->symb();
 5345: 	    $studentTable.=
 5346: 		&Apache::loncommon::start_data_table_row().
 5347: 		'<td align="center" valign="top" >'.$prob.
 5348: 		(scalar(@{$parts}) == 1 ? '' 
 5349: 		                        : '<br />('.&mt('[_1]parts',
 5350: 							scalar(@{$parts}).'&nbsp;').')'
 5351: 		 ).
 5352: 		 '</td>';
 5353: 	    $studentTable.='<td valign="top">';
 5354: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5355: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5356: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5357: 					     undef,'both',\%form);
 5358: 	    } else {
 5359: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5360: 		$companswer =~ s|<form(.*?)>||g;
 5361: 		$companswer =~ s|</form>||g;
 5362: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5363: #		    $companswer =~ s/$1/ /ms;
 5364: #		    $request->print('match='.$1."<br />\n");
 5365: #		}
 5366: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5367: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5368: 	    }
 5369: 
 5370: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5371: 
 5372: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5373: 		if ($record{'version'} eq '') {
 5374: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5375: 		} else {
 5376: 		    my %responseType = ();
 5377: 		    foreach my $partid (@{$parts}) {
 5378: 			my @responseIds =$curRes->responseIds($partid);
 5379: 			my @responseType =$curRes->responseType($partid);
 5380: 			my %responseIds;
 5381: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5382: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5383: 			}
 5384: 			$responseType{$partid} = \%responseIds;
 5385: 		    }
 5386: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5387: 
 5388: 		}
 5389: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5390: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5391:                 my $identifier = (&canmodify($usec)? $prob : '');
 5392: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5393: 									$env{'request.course.id'},
 5394: 									'','.submission',undef,
 5395:                                                                         $usec,$identifier);
 5396:  
 5397: 	    }
 5398: 	    if (&canmodify($usec)) {
 5399:             $studentTable.=&gradeBox_start();
 5400: 		foreach my $partid (@{$parts}) {
 5401: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5402: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5403: 		    $question++;
 5404: 		}
 5405:             $studentTable.=&gradeBox_end();
 5406: 		$prob++;
 5407: 	    }
 5408: 	    $studentTable.='</td></tr>';
 5409: 
 5410: 	}
 5411:         $curRes = $iterator->next();
 5412:     }
 5413:     my $disabled;
 5414:     unless (&canmodify($usec)) {
 5415:         $disabled = ' disabled="disabled"';
 5416:     }
 5417: 
 5418:     $studentTable.=
 5419:         '</table>'."\n".
 5420:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5421:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5422:         '</form>'."\n";
 5423:     $request->print($studentTable);
 5424: 
 5425:     return '';
 5426: }
 5427: 
 5428: sub displaySubByDates {
 5429:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5430:     my $isCODE=0;
 5431:     my $isTask = ($symb =~/\.task$/);
 5432:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5433:     my $studentTable=&Apache::loncommon::start_data_table().
 5434: 	&Apache::loncommon::start_data_table_header_row().
 5435: 	'<th>'.&mt('Date/Time').'</th>'.
 5436: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5437:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5438: 	'<th>'.&mt('Submission').'</th>'.
 5439: 	'<th>'.&mt('Status').'</th>'.
 5440: 	&Apache::loncommon::end_data_table_header_row();
 5441:     my ($version);
 5442:     my %mark;
 5443:     my %orders;
 5444:     $mark{'correct_by_student'} = $checkIcon;
 5445:     if (!exists($$record{'1:timestamp'})) {
 5446: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5447:     }
 5448: 
 5449:     my $interaction;
 5450:     my $no_increment = 1;
 5451:     my (%lastrndseed,%lasttype);
 5452:     for ($version=1;$version<=$$record{'version'};$version++) {
 5453: 	my $timestamp = 
 5454: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5455: 	if (exists($$record{$version.':resource.0.version'})) {
 5456: 	    $interaction = $$record{$version.':resource.0.version'};
 5457: 	}
 5458:         if ($isTask && $env{'form.previousversion'}) {
 5459:             next unless ($interaction == $env{'form.previousversion'});
 5460:         }
 5461: 	my $where = ($isTask ? "$version:resource.$interaction"
 5462: 		             : "$version:resource");
 5463: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5464: 	    '<td>'.$timestamp.'</td>';
 5465: 	if ($isCODE) {
 5466: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5467: 	}
 5468:         if ($isTask) {
 5469:             $studentTable.='<td>'.$interaction.'</td>';
 5470:         }
 5471: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5472: 	my @displaySub = ();
 5473: 	foreach my $partid (@{$parts}) {
 5474:             my ($hidden,$type);
 5475:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5476:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5477:                 $hidden = 1;
 5478:             }
 5479: 	    my @matchKey;
 5480:             if ($isTask) {
 5481:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5482:             } else {
 5483: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5484:             }
 5485: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5486: 	    my $display_part=&get_display_part($partid,$symb);
 5487: 	    foreach my $matchKey (@matchKey) {
 5488: 		if (exists($$record{$version.':'.$matchKey}) &&
 5489: 		    $$record{$version.':'.$matchKey} ne '') {
 5490:                     
 5491: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5492: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5493:                     $displaySub[0].='<span class="LC_nobreak">';
 5494:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5495:                                    .' <span class="LC_internal_info">'
 5496:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5497:                                    .'</span>'
 5498:                                    .' <b>';
 5499:                     if ($hidden) {
 5500:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5501:                     } else {
 5502:                         my ($trial,$rndseed,$newvariation);
 5503:                         if ($type eq 'randomizetry') {
 5504:                             $trial = $$record{"$where.$partid.tries"};
 5505:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5506:                         }
 5507: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5508: 			    $displaySub[0].=&mt('Trial not counted');
 5509: 		        } else {
 5510: 			    $displaySub[0].=&mt('Trial: [_1]',
 5511: 					    $$record{"$where.$partid.tries"});
 5512:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5513:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5514:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5515:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5516:                                 }
 5517:                             }
 5518:                             $lastrndseed{$partid} = $rndseed;
 5519:                             $lasttype{$partid} = $type;
 5520: 		        }
 5521: 		        my $responseType=($isTask ? 'Task'
 5522:                                               : $responseType->{$partid}->{$responseId});
 5523: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5524: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5525: 			    $orders{$partid}->{$responseId}=
 5526: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5527:                                            $no_increment,$type,$trial,$rndseed);
 5528: 		        }
 5529: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5530: 		        $displaySub[0].='&nbsp; '.
 5531: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5532:                     }
 5533: 		}
 5534: 	    }
 5535: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5536: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5537: 				    $$record{"$where.$partid.checkedin"},
 5538: 				    $$record{"$where.$partid.checkedin.slot"}).
 5539: 					'<br />';
 5540: 	    }
 5541: 	    if (exists $$record{"$where.$partid.award"}) {
 5542: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5543: 		    lc($$record{"$where.$partid.award"}).' '.
 5544: 		    $mark{$$record{"$where.$partid.solved"}}.
 5545: 		    '<br />';
 5546: 	    }
 5547: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5548: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5549: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5550: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5551: 		$displaySub[2].=
 5552: 		    $$record{"$version:resource.$partid.regrader"}.
 5553: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5554: 	    }
 5555: 	}
 5556: 	# needed because old essay regrader has not parts info
 5557: 	if (exists $$record{"$version:resource.regrader"}) {
 5558: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5559: 	}
 5560: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5561: 	if ($displaySub[2]) {
 5562: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5563: 	}
 5564: 	$studentTable.='&nbsp;</td>'.
 5565: 	    &Apache::loncommon::end_data_table_row();
 5566:     }
 5567:     $studentTable.=&Apache::loncommon::end_data_table();
 5568:     return $studentTable;
 5569: }
 5570: 
 5571: sub updateGradeByPage {
 5572:     my ($request,$symb) = @_;
 5573: 
 5574:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5575:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5576:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5577:     my $pageTitle = $env{'form.page'};
 5578:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5579:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5580:     my $usec=$classlist->{$env{'form.student'}}[5];
 5581:     if (!&canmodify($usec)) {
 5582: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5583: 	return;
 5584:     }
 5585:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5586:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5587: 	'</h3>'."\n";
 5588: 
 5589:     $request->print($result);
 5590: 
 5591: 
 5592:     my $navmap = Apache::lonnavmaps::navmap->new();
 5593:     unless (ref($navmap)) {
 5594:         $request->print(&navmap_errormsg());
 5595:         return;
 5596:     }
 5597:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5598:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5599:     if (!$map) {
 5600: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5601: 	return; 
 5602:     }
 5603:     my $iterator = $navmap->getIterator($map->map_start(),
 5604: 					$map->map_finish());
 5605: 
 5606:     my $studentTable=
 5607: 	&Apache::loncommon::start_data_table().
 5608: 	&Apache::loncommon::start_data_table_header_row().
 5609: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5610: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5611: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5612: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5613: 	&Apache::loncommon::end_data_table_header_row();
 5614: 
 5615:     $iterator->next(); # skip the first BEGIN_MAP
 5616:     my $curRes = $iterator->next(); # for "current resource"
 5617:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5618:     while ($depth > 0) {
 5619:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5620:         if($curRes == $iterator->END_MAP) { $depth--; }
 5621: 
 5622:         if (ref($curRes) && $curRes->is_problem()) {
 5623: 	    my $parts = $curRes->parts();
 5624:             my $title = $curRes->compTitle();
 5625: 	    my $symbx = $curRes->symb();
 5626: 	    $studentTable.=
 5627: 		&Apache::loncommon::start_data_table_row().
 5628: 		'<td align="center" valign="top" >'.$prob.
 5629: 		(scalar(@{$parts}) == 1 ? '' 
 5630:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5631: 		.')').'</td>';
 5632: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5633: 
 5634: 	    my %newrecord=();
 5635: 	    my @displayPts=();
 5636:             my %aggregate = ();
 5637:             my $aggregateflag = 0;
 5638:             if ($env{'form.HIDE'.$prob}) {
 5639:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5640:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5641:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5642:                 $hideflag += $numchgs;
 5643:             }
 5644: 	    foreach my $partid (@{$parts}) {
 5645: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5646: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5647: 
 5648: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5649: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5650: 		my $partial = $newpts/$wgt;
 5651: 		my $score;
 5652: 		if ($partial > 0) {
 5653: 		    $score = 'correct_by_override';
 5654: 		} elsif ($newpts ne '') { #empty is taken as 0
 5655: 		    $score = 'incorrect_by_override';
 5656: 		}
 5657: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5658: 		if ($dropMenu eq 'excused') {
 5659: 		    $partial = '';
 5660: 		    $score = 'excused';
 5661: 		} elsif ($dropMenu eq 'reset status'
 5662: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5663: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5664: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5665: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5666: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5667: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5668: 		    $changeflag++;
 5669: 		    $newpts = '';
 5670:                     
 5671:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5672:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5673:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5674:                     if ($aggtries > 0) {
 5675:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5676:                         $aggregateflag = 1;
 5677:                     }
 5678: 		}
 5679: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5680: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5681: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5682: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5683: 		    '&nbsp;<br />';
 5684: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5685: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5686: 		    '&nbsp;<br />';
 5687: 		$question++;
 5688: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5689: 
 5690: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5691: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5692: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5693: 		    if (scalar(keys(%newrecord)) > 0);
 5694: 
 5695: 		$changeflag++;
 5696: 	    }
 5697: 	    if (scalar(keys(%newrecord)) > 0) {
 5698: 		my %record = 
 5699: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5700: 					     $udom,$uname);
 5701: 
 5702: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5703: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5704: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5705: 		    $newrecord{'resource.CODE'} = '';
 5706: 		}
 5707: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5708: 					$udom,$uname);
 5709: 		%record = &Apache::lonnet::restore($symbx,
 5710: 						   $env{'request.course.id'},
 5711: 						   $udom,$uname);
 5712: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5713: 					     $cdom,$cnum,$udom,$uname);
 5714: 	    }
 5715: 	    
 5716:             if ($aggregateflag) {
 5717:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5718:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5719:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5720:             }
 5721: 
 5722: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5723: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5724: 		&Apache::loncommon::end_data_table_row();
 5725: 
 5726: 	    $prob++;
 5727: 	}
 5728:         $curRes = $iterator->next();
 5729:     }
 5730: 
 5731:     $studentTable.=&Apache::loncommon::end_data_table();
 5732:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5733: 		  &mt('The scores were changed for [quant,_1,problem].',
 5734: 		  $changeflag).'<br />');
 5735:     my $hidemsg=($hideflag == 0 ? '' :
 5736:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5737:                      $hideflag).'<br />');
 5738:     $request->print($hidemsg.$grademsg.$studentTable);
 5739: 
 5740:     return '';
 5741: }
 5742: 
 5743: #-------- end of section for handling grading by page/sequence ---------
 5744: #
 5745: #-------------------------------------------------------------------
 5746: 
 5747: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5748: #
 5749: #------ start of section for handling grading by page/sequence ---------
 5750: 
 5751: =pod
 5752: 
 5753: =head1 Bubble sheet grading routines
 5754: 
 5755:   For this documentation:
 5756: 
 5757:    'scanline' refers to the full line of characters
 5758:    from the file that we are parsing that represents one entire sheet
 5759: 
 5760:    'bubble line' refers to the data
 5761:    representing the line of bubbles that are on the physical bubblesheet
 5762: 
 5763: 
 5764: The overall process is that a scanned in bubblesheet data is uploaded
 5765: into a course. When a user wants to grade, they select a
 5766: sequence/folder of resources, a file of bubblesheet info, and pick
 5767: one of the predefined configurations for what each scanline looks
 5768: like.
 5769: 
 5770: Next each scanline is checked for any errors of either 'missing
 5771: bubbles' (it's an error because it may have been mis-scanned
 5772: because too light bubbling), 'double bubble' (each bubble line should
 5773: have no more than one letter picked), invalid or duplicated CODE,
 5774: invalid student/employee ID
 5775: 
 5776: If the CODE option is used that determines the randomization of the
 5777: homework problems, either way the student/employee ID is looked up into a
 5778: username:domain.
 5779: 
 5780: During the validation phase the instructor can choose to skip scanlines. 
 5781: 
 5782: After the validation phase, there are now 3 bubblesheet files
 5783: 
 5784:   scantron_original_filename (unmodified original file)
 5785:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5786:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5787: 
 5788: Also there is a separate hash nohist_scantrondata that contains extra
 5789: correction information that isn't representable in the bubblesheet
 5790: file (see &scantron_getfile() for more information)
 5791: 
 5792: After all scanlines are either valid, marked as valid or skipped, then
 5793: foreach line foreach problem in the picked sequence, an ssi request is
 5794: made that simulates a user submitting their selected letter(s) against
 5795: the homework problem.
 5796: 
 5797: =over 4
 5798: 
 5799: 
 5800: 
 5801: =item defaultFormData
 5802: 
 5803:   Returns html hidden inputs used to hold context/default values.
 5804: 
 5805:  Arguments:
 5806:   $symb - $symb of the current resource 
 5807: 
 5808: =cut
 5809: 
 5810: sub defaultFormData {
 5811:     my ($symb)=@_;
 5812:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5813: }
 5814: 
 5815: 
 5816: =pod 
 5817: 
 5818: =item getSequenceDropDown
 5819: 
 5820:    Return html dropdown of possible sequences to grade
 5821:  
 5822:  Arguments:
 5823:    $symb - $symb of the current resource
 5824:    $map_error - ref to scalar which will container error if
 5825:                 $navmap object is unavailable in &getSymbMap().
 5826: 
 5827: =cut
 5828: 
 5829: sub getSequenceDropDown {
 5830:     my ($symb,$map_error)=@_;
 5831:     my $result='<select name="selectpage">'."\n";
 5832:     my ($titles,$symbx) = &getSymbMap($map_error);
 5833:     if (ref($map_error)) {
 5834:         return if ($$map_error);
 5835:     }
 5836:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5837:     my $ctr=0;
 5838:     foreach (@$titles) {
 5839: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5840: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5841: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5842: 	    '>'.$showtitle.'</option>'."\n";
 5843: 	$ctr++;
 5844:     }
 5845:     $result.= '</select>';
 5846:     return $result;
 5847: }
 5848: 
 5849: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5850:                                    # key is zero-based index - 0, 1, 2 ...
 5851: 
 5852: my %first_bubble_line;             # First bubble line no. for each bubble.
 5853: 
 5854: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5855:                                    # matchresponse or rankresponse, where 
 5856:                                    # an individual response can have multiple 
 5857:                                    # lines
 5858: 
 5859: my %responsetype_per_response;     # responsetype for each response
 5860: 
 5861: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5862:                                    # numbered response. Needed when randomorder
 5863:                                    # or randompick are in use. Key is ID, value 
 5864:                                    # is response number.
 5865: 
 5866: # Save and restore the bubble lines array to the form env.
 5867: 
 5868: 
 5869: sub save_bubble_lines {
 5870:     foreach my $line (keys(%bubble_lines_per_response)) {
 5871: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5872: 	$env{"form.scantron.first_bubble_line.$line"} =
 5873: 	    $first_bubble_line{$line};
 5874:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5875:             $subdivided_bubble_lines{$line};
 5876:         $env{"form.scantron.responsetype.$line"} =
 5877:             $responsetype_per_response{$line};
 5878:     }
 5879:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5880:         my $line = $masterseq_id_responsenum{$resid};
 5881:         $env{"form.scantron.residpart.$line"} = $resid;
 5882:     }
 5883: }
 5884: 
 5885: 
 5886: sub restore_bubble_lines {
 5887:     my $line = 0;
 5888:     %bubble_lines_per_response = ();
 5889:     %masterseq_id_responsenum = ();
 5890:     while ($env{"form.scantron.bubblelines.$line"}) {
 5891: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5892: 	$bubble_lines_per_response{$line} = $value;
 5893: 	$first_bubble_line{$line}  =
 5894: 	    $env{"form.scantron.first_bubble_line.$line"};
 5895:         $subdivided_bubble_lines{$line} =
 5896:             $env{"form.scantron.sub_bubblelines.$line"};
 5897:         $responsetype_per_response{$line} =
 5898:             $env{"form.scantron.responsetype.$line"};
 5899:         my $id = $env{"form.scantron.residpart.$line"};
 5900:         $masterseq_id_responsenum{$id} = $line;
 5901: 	$line++;
 5902:     }
 5903: }
 5904: 
 5905: =pod 
 5906: 
 5907: =item scantron_filenames
 5908: 
 5909:    Returns a list of the scantron files in the current course 
 5910: 
 5911: =cut
 5912: 
 5913: sub scantron_filenames {
 5914:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5915:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5916:     my $getpropath = 1;
 5917:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5918:                                                         $cname,$getpropath);
 5919:     my @possiblenames;
 5920:     if (ref($dirlist) eq 'ARRAY') {
 5921:         foreach my $filename (sort(@{$dirlist})) {
 5922: 	    ($filename)=split(/&/,$filename);
 5923: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5924: 	    $filename=~s/^scantron_orig_//;
 5925: 	    push(@possiblenames,$filename);
 5926:         }
 5927:     }
 5928:     return @possiblenames;
 5929: }
 5930: 
 5931: =pod 
 5932: 
 5933: =item scantron_uploads
 5934: 
 5935:    Returns  html drop-down list of scantron files in current course.
 5936: 
 5937:  Arguments:
 5938:    $file2grade - filename to set as selected in the dropdown
 5939: 
 5940: =cut
 5941: 
 5942: sub scantron_uploads {
 5943:     my ($file2grade) = @_;
 5944:     my $result=	'<select name="scantron_selectfile">';
 5945:     $result.="<option></option>";
 5946:     foreach my $filename (sort(&scantron_filenames())) {
 5947: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5948:     }
 5949:     $result.="</select>";
 5950:     return $result;
 5951: }
 5952: 
 5953: =pod 
 5954: 
 5955: =item scantron_scantab
 5956: 
 5957:   Returns html drop down of the scantron formats in the scantronformat.tab
 5958:   file.
 5959: 
 5960: =cut
 5961: 
 5962: sub scantron_scantab {
 5963:     my $result='<select name="scantron_format">'."\n";
 5964:     $result.='<option></option>'."\n";
 5965:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5966:     if (@lines > 0) {
 5967:         foreach my $line (@lines) {
 5968:             next if (($line =~ /^\#/) || ($line eq ''));
 5969: 	    my ($name,$descrip)=split(/:/,$line);
 5970: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5971:         }
 5972:     }
 5973:     $result.='</select>'."\n";
 5974:     return $result;
 5975: }
 5976: 
 5977: =pod 
 5978: 
 5979: =item scantron_CODElist
 5980: 
 5981:   Returns html drop down of the saved CODE lists from current course,
 5982:   generated from earlier printings.
 5983: 
 5984: =cut
 5985: 
 5986: sub scantron_CODElist {
 5987:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5988:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5989:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5990:     my $namechoice='<option></option>';
 5991:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5992: 	if ($name =~ /^error: 2 /) { next; }
 5993: 	if ($name =~ /^type\0/) { next; }
 5994: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5995:     }
 5996:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5997:     return $namechoice;
 5998: }
 5999: 
 6000: =pod 
 6001: 
 6002: =item scantron_CODEunique
 6003: 
 6004:   Returns the html for "Each CODE to be used once" radio.
 6005: 
 6006: =cut
 6007: 
 6008: sub scantron_CODEunique {
 6009:     my $result='<span class="LC_nobreak">
 6010:                  <label><input type="radio" name="scantron_CODEunique"
 6011:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6012:                 </span>
 6013:                 <span class="LC_nobreak">
 6014:                  <label><input type="radio" name="scantron_CODEunique"
 6015:                         value="no" />'.&mt('No').' </label>
 6016:                 </span>';
 6017:     return $result;
 6018: }
 6019: 
 6020: =pod 
 6021: 
 6022: =item scantron_selectphase
 6023: 
 6024:   Generates the initial screen to start the bubblesheet process.
 6025:   Allows for - starting a grading run.
 6026:              - downloading existing scan data (original, corrected
 6027:                                                 or skipped info)
 6028: 
 6029:              - uploading new scan data
 6030: 
 6031:  Arguments:
 6032:   $r          - The Apache request object
 6033:   $file2grade - name of the file that contain the scanned data to score
 6034: 
 6035: =cut
 6036: 
 6037: sub scantron_selectphase {
 6038:     my ($r,$file2grade,$symb) = @_;
 6039:     if (!$symb) {return '';}
 6040:     my $map_error;
 6041:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6042:     if ($map_error) {
 6043:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6044:         return;
 6045:     }
 6046:     my $default_form_data=&defaultFormData($symb);
 6047:     my $file_selector=&scantron_uploads($file2grade);
 6048:     my $format_selector=&scantron_scantab();
 6049:     my $CODE_selector=&scantron_CODElist();
 6050:     my $CODE_unique=&scantron_CODEunique();
 6051:     my $result;
 6052: 
 6053:     $ssi_error = 0;
 6054: 
 6055:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6056:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6057: 
 6058:         # Chunk of form to prompt for a scantron file upload.
 6059: 
 6060:         $r->print('
 6061:     <br />');
 6062:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6063:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6064:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6065:         &js_escape(\$alertmsg);
 6066:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6067:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6068:     function checkUpload(formname) {
 6069:         if (formname.upfile.value == "") {
 6070:             alert("'.$alertmsg.'");
 6071:             return false;
 6072:         }
 6073:         formname.submit();
 6074:     }'."\n".$formatjs));
 6075:         $r->print('
 6076:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6077:                 '.$default_form_data.'
 6078:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6079:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6080:                 <input name="command" value="scantronupload_save" type="hidden" />
 6081:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6082:               '.&Apache::loncommon::start_data_table_header_row().'
 6083:                 <th>
 6084:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6085:                 </th>
 6086:               '.&Apache::loncommon::end_data_table_header_row().'
 6087:               '.&Apache::loncommon::start_data_table_row().'
 6088:             <td>
 6089:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6090:         if ($formatoptions) {
 6091:             $r->print('</td>
 6092:                  '.&Apache::loncommon::end_data_table_row().'
 6093:                  '.&Apache::loncommon::start_data_table_row().'
 6094:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6095:                  </td>
 6096:                  '.&Apache::loncommon::end_data_table_row().'
 6097:                  '.&Apache::loncommon::start_data_table_row().'
 6098:                  <td>'
 6099:             );
 6100:         } else {
 6101:             $r->print(' <br />');
 6102:         }
 6103:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6104:               </td>
 6105:              '.&Apache::loncommon::end_data_table_row().'
 6106:              '.&Apache::loncommon::end_data_table().'
 6107:              </form>'
 6108:         );
 6109: 
 6110:     }
 6111: 
 6112:     # Chunk of form to prompt for a file to grade and how:
 6113: 
 6114:     $result.= '
 6115:     <br />
 6116:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6117:     <input type="hidden" name="command" value="scantron_warning" />
 6118:     '.$default_form_data.'
 6119:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6120:        '.&Apache::loncommon::start_data_table_header_row().'
 6121:             <th colspan="2">
 6122:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6123:             </th>
 6124:        '.&Apache::loncommon::end_data_table_header_row().'
 6125:        '.&Apache::loncommon::start_data_table_row().'
 6126:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6127:        '.&Apache::loncommon::end_data_table_row().'
 6128:        '.&Apache::loncommon::start_data_table_row().'
 6129:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6130:        '.&Apache::loncommon::end_data_table_row().'
 6131:        '.&Apache::loncommon::start_data_table_row().'
 6132:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6133:        '.&Apache::loncommon::end_data_table_row().'
 6134:        '.&Apache::loncommon::start_data_table_row().'
 6135:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6136:        '.&Apache::loncommon::end_data_table_row().'
 6137:        '.&Apache::loncommon::start_data_table_row().'
 6138:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6139:        '.&Apache::loncommon::end_data_table_row().'
 6140:        '.&Apache::loncommon::start_data_table_row().'
 6141: 	    <td> '.&mt('Options:').' </td>
 6142:             <td>
 6143: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6144:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6145:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6146: 	    </td>
 6147:        '.&Apache::loncommon::end_data_table_row().'
 6148:        '.&Apache::loncommon::start_data_table_row().'
 6149:             <td colspan="2">
 6150:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6151:             </td>
 6152:        '.&Apache::loncommon::end_data_table_row().'
 6153:     '.&Apache::loncommon::end_data_table().'
 6154:     </form>
 6155: ';
 6156:    
 6157:     $r->print($result);
 6158: 
 6159:     # Chunk of the form that prompts to view a scoring office file,
 6160:     # corrected file, skipped records in a file.
 6161: 
 6162:     $r->print('
 6163:    <br />
 6164:    <form action="/adm/grades" name="scantron_download">
 6165:      '.$default_form_data.'
 6166:      <input type="hidden" name="command" value="scantron_download" />
 6167:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6168:        '.&Apache::loncommon::start_data_table_header_row().'
 6169:               <th>
 6170:                 &nbsp;'.&mt('Download a scoring office file').'
 6171:               </th>
 6172:        '.&Apache::loncommon::end_data_table_header_row().'
 6173:        '.&Apache::loncommon::start_data_table_row().'
 6174:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6175:                 <br />
 6176:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6177:        '.&Apache::loncommon::end_data_table_row().'
 6178:      '.&Apache::loncommon::end_data_table().'
 6179:    </form>
 6180:    <br />
 6181: ');
 6182: 
 6183:     &Apache::lonpickcode::code_list($r,2);
 6184: 
 6185:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6186:              $default_form_data."\n".
 6187:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6188:              &Apache::loncommon::start_data_table_header_row()."\n".
 6189:              '<th colspan="2">
 6190:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6191:              '</th>'."\n".
 6192:               &Apache::loncommon::end_data_table_header_row()."\n".
 6193:               &Apache::loncommon::start_data_table_row()."\n".
 6194:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6195:               '<td> '.$sequence_selector.' </td>'.
 6196:               &Apache::loncommon::end_data_table_row()."\n".
 6197:               &Apache::loncommon::start_data_table_row()."\n".
 6198:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6199:               '<td> '.$file_selector.' </td>'."\n".
 6200:               &Apache::loncommon::end_data_table_row()."\n".
 6201:               &Apache::loncommon::start_data_table_row()."\n".
 6202:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6203:               '<td> '.$format_selector.' </td>'."\n".
 6204:               &Apache::loncommon::end_data_table_row()."\n".
 6205:               &Apache::loncommon::start_data_table_row()."\n".
 6206:               '<td> '.&mt('Options').' </td>'."\n".
 6207:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6208:               &Apache::loncommon::end_data_table_row()."\n".
 6209:               &Apache::loncommon::start_data_table_row()."\n".
 6210:               '<td colspan="2">'."\n".
 6211:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6212:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6213:               '</td>'."\n".
 6214:               &Apache::loncommon::end_data_table_row()."\n".
 6215:               &Apache::loncommon::end_data_table()."\n".
 6216:               '</form><br />');
 6217:     return;
 6218: }
 6219: 
 6220: =pod 
 6221: 
 6222: =item username_to_idmap
 6223: 
 6224:     creates a hash keyed by student/employee ID with values of the corresponding
 6225:     student username:domain.
 6226: 
 6227:   Arguments:
 6228: 
 6229:     $classlist - reference to the class list hash. This is a hash
 6230:                  keyed by student name:domain  whose elements are references
 6231:                  to arrays containing various chunks of information
 6232:                  about the student. (See loncoursedata for more info).
 6233: 
 6234:   Returns
 6235:     %idmap - the constructed hash
 6236: 
 6237: =cut
 6238: 
 6239: sub username_to_idmap {
 6240:     my ($classlist)= @_;
 6241:     my %idmap;
 6242:     foreach my $student (keys(%$classlist)) {
 6243:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6244:         unless ($id eq '') {
 6245:             if (!exists($idmap{$id})) {
 6246:                 $idmap{$id} = $student;
 6247:             } else {
 6248:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6249:                 if ($status eq 'Active') {
 6250:                     $idmap{$id} = $student;
 6251:                 }
 6252:             }
 6253:         }
 6254:     }
 6255:     return %idmap;
 6256: }
 6257: 
 6258: =pod
 6259: 
 6260: =item scantron_fixup_scanline
 6261: 
 6262:    Process a requested correction to a scanline.
 6263: 
 6264:   Arguments:
 6265:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6266:     $scan_data         - hash of correction information 
 6267:                           (see &scantron_getfile())
 6268:     $line              - existing scanline
 6269:     $whichline         - line number of the passed in scanline
 6270:     $field             - type of change to process 
 6271:                          (either 
 6272:                           'ID'     -> correct the student/employee ID
 6273:                           'CODE'   -> correct the CODE
 6274:                           'answer' -> fixup the submitted answers)
 6275:     
 6276:    $args               - hash of additional info,
 6277:                           - 'ID' 
 6278:                                'newid' -> studentID to use in replacement
 6279:                                           of existing one
 6280:                           - 'CODE' 
 6281:                                'CODE_ignore_dup' - set to true if duplicates
 6282:                                                    should be ignored.
 6283: 	                       'CODE' - is new code or 'use_unfound'
 6284:                                         if the existing unfound code should
 6285:                                         be used as is
 6286:                           - 'answer'
 6287:                                'response' - new answer or 'none' if blank
 6288:                                'question' - the bubble line to change
 6289:                                'questionnum' - the question identifier,
 6290:                                                may include subquestion. 
 6291: 
 6292:   Returns:
 6293:     $line - the modified scanline
 6294: 
 6295:   Side effects: 
 6296:     $scan_data - may be updated
 6297: 
 6298: =cut
 6299: 
 6300: 
 6301: sub scantron_fixup_scanline {
 6302:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6303:     if ($field eq 'ID') {
 6304: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6305: 	    return ($line,1,'New value too large');
 6306: 	}
 6307: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6308: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6309: 				     $args->{'newid'});
 6310: 	}
 6311: 	substr($line,$$scantron_config{'IDstart'}-1,
 6312: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6313: 	if ($args->{'newid'}=~/^\s*$/) {
 6314: 	    &scan_data($scan_data,"$whichline.user",
 6315: 		       $args->{'username'}.':'.$args->{'domain'});
 6316: 	}
 6317:     } elsif ($field eq 'CODE') {
 6318: 	if ($args->{'CODE_ignore_dup'}) {
 6319: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6320: 	}
 6321: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6322: 	if ($args->{'CODE'} ne 'use_unfound') {
 6323: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6324: 		return ($line,1,'New CODE value too large');
 6325: 	    }
 6326: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6327: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6328: 	    }
 6329: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6330: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6331: 	}
 6332:     } elsif ($field eq 'answer') {
 6333: 	my $length=$scantron_config->{'Qlength'};
 6334: 	my $off=$scantron_config->{'Qoff'};
 6335: 	my $on=$scantron_config->{'Qon'};
 6336: 	my $answer=${off}x$length;
 6337: 	if ($args->{'response'} eq 'none') {
 6338: 	    &scan_data($scan_data,
 6339: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6340: 	} else {
 6341: 	    if ($on eq 'letter') {
 6342: 		my @alphabet=('A'..'Z');
 6343: 		$answer=$alphabet[$args->{'response'}];
 6344: 	    } elsif ($on eq 'number') {
 6345: 		$answer=$args->{'response'}+1;
 6346: 		if ($answer == 10) { $answer = '0'; }
 6347: 	    } else {
 6348: 		substr($answer,$args->{'response'},1)=$on;
 6349: 	    }
 6350: 	    &scan_data($scan_data,
 6351: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6352: 	}
 6353: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6354: 	substr($line,$where-1,$length)=$answer;
 6355:     }
 6356:     return $line;
 6357: }
 6358: 
 6359: =pod
 6360: 
 6361: =item scan_data
 6362: 
 6363:     Edit or look up  an item in the scan_data hash.
 6364: 
 6365:   Arguments:
 6366:     $scan_data  - The hash (see scantron_getfile)
 6367:     $key        - shorthand of the key to edit (actual key is
 6368:                   scantronfilename_key).
 6369:     $data        - New value of the hash entry.
 6370:     $delete      - If true, the entry is removed from the hash.
 6371: 
 6372:   Returns:
 6373:     The new value of the hash table field (undefined if deleted).
 6374: 
 6375: =cut
 6376: 
 6377: 
 6378: sub scan_data {
 6379:     my ($scan_data,$key,$value,$delete)=@_;
 6380:     my $filename=$env{'form.scantron_selectfile'};
 6381:     if (defined($value)) {
 6382: 	$scan_data->{$filename.'_'.$key} = $value;
 6383:     }
 6384:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6385:     return $scan_data->{$filename.'_'.$key};
 6386: }
 6387: 
 6388: # ----- These first few routines are general use routines.----
 6389: 
 6390: # Return the number of occurences of a pattern in a string.
 6391: 
 6392: sub occurence_count {
 6393:     my ($string, $pattern) = @_;
 6394: 
 6395:     my @matches = ($string =~ /$pattern/g);
 6396: 
 6397:     return scalar(@matches);
 6398: }
 6399: 
 6400: 
 6401: # Take a string known to have digits and convert all the
 6402: # digits into letters in the range J,A..I.
 6403: 
 6404: sub digits_to_letters {
 6405:     my ($input) = @_;
 6406: 
 6407:     my @alphabet = ('J', 'A'..'I');
 6408: 
 6409:     my @input    = split(//, $input);
 6410:     my $output ='';
 6411:     for (my $i = 0; $i < scalar(@input); $i++) {
 6412: 	if ($input[$i] =~ /\d/) {
 6413: 	    $output .= $alphabet[$input[$i]];
 6414: 	} else {
 6415: 	    $output .= $input[$i];
 6416: 	}
 6417:     }
 6418:     return $output;
 6419: }
 6420: 
 6421: =pod 
 6422: 
 6423: =item scantron_parse_scanline
 6424: 
 6425:   Decodes a scanline from the selected scantron file
 6426: 
 6427:  Arguments:
 6428:     line             - The text of the scantron file line to process
 6429:     whichline        - Line number
 6430:     scantron_config  - Hash describing the format of the scantron lines.
 6431:     scan_data        - Hash of extra information about the scanline
 6432:                        (see scantron_getfile for more information)
 6433:     just_header      - True if should not process question answers but only
 6434:                        the stuff to the left of the answers.
 6435:     randomorder      - True if randomorder in use
 6436:     randompick       - True if randompick in use
 6437:     sequence         - Exam folder URL
 6438:     master_seq       - Ref to array containing symbs in exam folder
 6439:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6440:                        (corresponding values are resource objects)
 6441:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6442:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6443:                        are refs to an array of resource objects, ordered
 6444:                        according to order used for CODE, when randomorder
 6445:                        and or randompick are in use.
 6446:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6447:                        for current line to question number used for same question
 6448:                         in "Master Sequence" (as seen by Course Coordinator).
 6449:     startline        - Ref to hash where key is question number (0 is first)
 6450:                        and value is number of first bubble line for current 
 6451:                        student or code-based randompick and/or randomorder.
 6452:     totalref         - Ref of scalar used to score total number of bubble
 6453:                        lines needed for responses in a scan line (used when
 6454:                        randompick in use. 
 6455: 
 6456:  Returns:
 6457:    Hash containing the result of parsing the scanline
 6458: 
 6459:    Keys are all proceeded by the string 'scantron.'
 6460: 
 6461:        CODE    - the CODE in use for this scanline
 6462:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6463:                  by the operator
 6464:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6465:                             CODEs were selected, but the usage has been
 6466:                             forced by the operator
 6467:        ID  - student/employee ID
 6468:        PaperID - if used, the ID number printed on the sheet when the 
 6469:                  paper was scanned
 6470:        FirstName - first name from the sheet
 6471:        LastName  - last name from the sheet
 6472: 
 6473:      if just_header was not true these key may also exist
 6474: 
 6475:        missingerror - a list of bubble ranges that are considered to be answers
 6476:                       to a single question that don't have any bubbles filled in.
 6477:                       Of the form questionnumber:firstbubblenumber:count.
 6478:        doubleerror  - a list of bubble ranges that are considered to be answers
 6479:                       to a single question that have more than one bubble filled in.
 6480:                       Of the form questionnumber::firstbubblenumber:count
 6481:    
 6482:                 In the above, count is the number of bubble responses in the
 6483:                 input line needed to represent the possible answers to the question.
 6484:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6485:                 per line would have count = 2.
 6486: 
 6487:        maxquest     - the number of the last bubble line that was parsed
 6488: 
 6489:        (<number> starts at 1)
 6490:        <number>.answer - zero or more letters representing the selected
 6491:                          letters from the scanline for the bubble line 
 6492:                          <number>.
 6493:                          if blank there was either no bubble or there where
 6494:                          multiple bubbles, (consult the keys missingerror and
 6495:                          doubleerror if this is an error condition)
 6496: 
 6497: =cut
 6498: 
 6499: sub scantron_parse_scanline {
 6500:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6501:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6502:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6503: 
 6504:     my %record;
 6505:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6506:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6507: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6508: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6509: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6510: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6511: 	    $record{'scantron.CODE'}=substr($data,
 6512: 					    $$scantron_config{'CODEstart'}-1,
 6513: 					    $$scantron_config{'CODElength'});
 6514: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6515: 		$record{'scantron.useCODE'}=1;
 6516: 	    }
 6517: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6518: 		$record{'scantron.CODE_ignore_dup'}=1;
 6519: 	    }
 6520: 	} else {
 6521: 	    #FIXME interpret first N questions
 6522: 	}
 6523:     }
 6524:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6525: 				  $$scantron_config{'IDlength'});
 6526:     $record{'scantron.PaperID'}=
 6527: 	substr($data,$$scantron_config{'PaperID'}-1,
 6528: 	       $$scantron_config{'PaperIDlength'});
 6529:     $record{'scantron.FirstName'}=
 6530: 	substr($data,$$scantron_config{'FirstName'}-1,
 6531: 	       $$scantron_config{'FirstNamelength'});
 6532:     $record{'scantron.LastName'}=
 6533: 	substr($data,$$scantron_config{'LastName'}-1,
 6534: 	       $$scantron_config{'LastNamelength'});
 6535:     if ($just_header) { return \%record; }
 6536: 
 6537:     my @alphabet=('A'..'Z');
 6538:     my $questnum=0;
 6539:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6540: 
 6541:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6542:     if ($randompick || $randomorder) {
 6543:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6544:                                          $master_seq,$symb_to_resource,
 6545:                                          $partids_by_symb,$orderedforcode,
 6546:                                          $respnumlookup,$startline);
 6547:         if ($total) {
 6548:             $lastpos = $total*$$scantron_config{'Qlength'};
 6549:         }
 6550:         if (ref($totalref)) {
 6551:             $$totalref = $total;
 6552:         }
 6553:     }
 6554:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6555:     chomp($questions);		# Get rid of any trailing \n.
 6556:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6557:     while (length($questions)) {
 6558:         my $answers_needed;
 6559:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6560:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6561:         } else {
 6562:             $answers_needed = $bubble_lines_per_response{$questnum};
 6563:         }
 6564:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6565:                              || 1;
 6566:         $questnum++;
 6567:         my $quest_id = $questnum;
 6568:         my $currentquest = substr($questions,0,$answer_length);
 6569:         $questions       = substr($questions,$answer_length);
 6570:         if (length($currentquest) < $answer_length) { next; }
 6571: 
 6572:         my $subdivided;
 6573:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6574:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6575:         } else {
 6576:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6577:         }
 6578:         if ($subdivided =~ /,/) {
 6579:             my $subquestnum = 1;
 6580:             my $subquestions = $currentquest;
 6581:             my @subanswers_needed = split(/,/,$subdivided);
 6582:             foreach my $subans (@subanswers_needed) {
 6583:                 my $subans_length =
 6584:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6585:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6586:                 $subquestions   = substr($subquestions,$subans_length);
 6587:                 $quest_id = "$questnum.$subquestnum";
 6588:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6589:                     ($$scantron_config{'Qon'} eq 'number')) {
 6590:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6591:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6592:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6593:                         $randomorder,$randompick,$respnumlookup);
 6594:                 } else {
 6595:                     $ansnum = &scantron_validator_positional($ansnum,
 6596:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6597:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6598:                         $randomorder,$randompick,$respnumlookup);
 6599:                 }
 6600:                 $subquestnum ++;
 6601:             }
 6602:         } else {
 6603:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6604:                 ($$scantron_config{'Qon'} eq 'number')) {
 6605:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6606:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6607:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6608:                     $randomorder,$randompick,$respnumlookup);
 6609:             } else {
 6610:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6611:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6612:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6613:                     $randomorder,$randompick,$respnumlookup);
 6614:             }
 6615:         }
 6616:     }
 6617:     $record{'scantron.maxquest'}=$questnum;
 6618:     return \%record;
 6619: }
 6620: 
 6621: sub get_master_seq {
 6622:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6623:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6624:                    (ref($symb_to_resource) eq 'HASH'));
 6625:     my $resource_error;
 6626:     foreach my $resource (@{$resources}) {
 6627:         my $ressymb;
 6628:         if (ref($resource)) {
 6629:             $ressymb = $resource->symb();
 6630:             push(@{$master_seq},$ressymb);
 6631:             $symb_to_resource->{$ressymb} = $resource;
 6632:         } else {
 6633:             $resource_error = 1;
 6634:             last;
 6635:         }
 6636:     }
 6637:     return $resource_error;
 6638: }
 6639: 
 6640: sub get_respnum_lookups {
 6641:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6642:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6643:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6644:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6645:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6646:                    (ref($startline) eq 'HASH'));
 6647:     my ($user,$scancode);
 6648:     if ((exists($record->{'scantron.CODE'})) &&
 6649:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6650:         $scancode = $record->{'scantron.CODE'};
 6651:     } else {
 6652:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6653:     }
 6654:     my @mapresources =
 6655:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6656:                      $orderedforcode);
 6657:     my $total = 0;
 6658:     my $count = 0;
 6659:     foreach my $resource (@mapresources) {
 6660:         my $id = $resource->id();
 6661:         my $symb = $resource->symb();
 6662:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6663:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6664:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6665:                 if ($respnum ne '') {
 6666:                     $respnumlookup->{$count} = $respnum;
 6667:                     $startline->{$count} = $total;
 6668:                     $total += $bubble_lines_per_response{$respnum};
 6669:                     $count ++;
 6670:                 }
 6671:             }
 6672:         }
 6673:     }
 6674:     return $total;
 6675: }
 6676: 
 6677: sub scantron_validator_lettnum {
 6678:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6679:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6680:         $randompick,$respnumlookup) = @_;
 6681: 
 6682:     # Qon 'letter' implies for each slot in currquest we have:
 6683:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6684:     #    about anything else (esp. a value of Qoff) for missing
 6685:     #    bubbles.
 6686:     #
 6687:     # Qon 'number' implies each slot gives a digit that indexes the
 6688:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6689:     #    and * or ? for double bubbles on a single line.
 6690:     #
 6691: 
 6692:     my $matchon;
 6693:     if ($$scantron_config{'Qon'} eq 'letter') {
 6694:         $matchon = '[A-Z]';
 6695:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6696:         $matchon = '\d';
 6697:     }
 6698:     my $occurrences = 0;
 6699:     my $responsenum = $questnum-1;
 6700:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6701:        $responsenum = $respnumlookup->{$questnum-1}
 6702:     }
 6703:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6704:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6705:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6706:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6707:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6708:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6709:         my @singlelines = split('',$currquest);
 6710:         foreach my $entry (@singlelines) {
 6711:             $occurrences = &occurence_count($entry,$matchon);
 6712:             if ($occurrences > 1) {
 6713:                 last;
 6714:             }
 6715:         }
 6716:     } else {
 6717:         $occurrences = &occurence_count($currquest,$matchon); 
 6718:     }
 6719:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6720:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6721:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6722:             my $bubble = substr($currquest,$ans,1);
 6723:             if ($bubble =~ /$matchon/ ) {
 6724:                 if ($$scantron_config{'Qon'} eq 'number') {
 6725:                     if ($bubble == 0) {
 6726:                         $bubble = 10; 
 6727:                     }
 6728:                     $record->{"scantron.$ansnum.answer"} = 
 6729:                         $alphabet->[$bubble-1];
 6730:                 } else {
 6731:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6732:                 }
 6733:             } else {
 6734:                 $record->{"scantron.$ansnum.answer"}='';
 6735:             }
 6736:             $ansnum++;
 6737:         }
 6738:     } elsif (!defined($currquest)
 6739:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6740:             || (&occurence_count($currquest,$matchon) == 0)) {
 6741:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6742:             $record->{"scantron.$ansnum.answer"}='';
 6743:             $ansnum++;
 6744:         }
 6745:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6746:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6747:         }
 6748:     } else {
 6749:         if ($$scantron_config{'Qon'} eq 'number') {
 6750:             $currquest = &digits_to_letters($currquest);            
 6751:         }
 6752:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6753:             my $bubble = substr($currquest,$ans,1);
 6754:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6755:             $ansnum++;
 6756:         }
 6757:     }
 6758:     return $ansnum;
 6759: }
 6760: 
 6761: sub scantron_validator_positional {
 6762:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6763:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6764:         $randomorder,$randompick,$respnumlookup) = @_;
 6765: 
 6766:     # Otherwise there's a positional notation;
 6767:     # each bubble line requires Qlength items, and there are filled in
 6768:     # bubbles for each case where there 'Qon' characters.
 6769:     #
 6770: 
 6771:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6772: 
 6773:     # If the split only gives us one element.. the full length of the
 6774:     # answer string, no bubbles are filled in:
 6775: 
 6776:     if ($answers_needed eq '') {
 6777:         return;
 6778:     }
 6779: 
 6780:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6781:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6782:             $record->{"scantron.$ansnum.answer"}='';
 6783:             $ansnum++;
 6784:         }
 6785:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6786:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6787:         }
 6788:     } elsif (scalar(@array) == 2) {
 6789:         my $location = length($array[0]);
 6790:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6791:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6792:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6793:             if ($ans eq $line_num) {
 6794:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6795:             } else {
 6796:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6797:             }
 6798:             $ansnum++;
 6799:          }
 6800:     } else {
 6801:         #  If there's more than one instance of a bubble character
 6802:         #  That's a double bubble; with positional notation we can
 6803:         #  record all the bubbles filled in as well as the
 6804:         #  fact this response consists of multiple bubbles.
 6805:         #
 6806:         my $responsenum = $questnum-1;
 6807:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6808:             $responsenum = $respnumlookup->{$questnum-1}
 6809:         }
 6810:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6811:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6812:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6813:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6814:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6815:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6816:             my $doubleerror = 0;
 6817:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6818:                    (!$doubleerror)) {
 6819:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6820:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6821:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6822:                if (length(@currarray) > 2) {
 6823:                    $doubleerror = 1;
 6824:                } 
 6825:             }
 6826:             if ($doubleerror) {
 6827:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6828:             }
 6829:         } else {
 6830:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6831:         }
 6832:         my $item = $ansnum;
 6833:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6834:             $record->{"scantron.$item.answer"} = '';
 6835:             $item ++;
 6836:         }
 6837: 
 6838:         my @ans=@array;
 6839:         my $i=0;
 6840:         my $increment = 0;
 6841:         while ($#ans) {
 6842:             $i+=length($ans[0]) + $increment;
 6843:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6844:             my $bubble = $i%$$scantron_config{'Qlength'};
 6845:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6846:             shift(@ans);
 6847:             $increment = 1;
 6848:         }
 6849:         $ansnum += $answers_needed;
 6850:     }
 6851:     return $ansnum;
 6852: }
 6853: 
 6854: =pod
 6855: 
 6856: =item scantron_add_delay
 6857: 
 6858:    Adds an error message that occurred during the grading phase to a
 6859:    queue of messages to be shown after grading pass is complete
 6860: 
 6861:  Arguments:
 6862:    $delayqueue  - arrary ref of hash ref of error messages
 6863:    $scanline    - the scanline that caused the error
 6864:    $errormesage - the error message
 6865:    $errorcode   - a numeric code for the error
 6866: 
 6867:  Side Effects:
 6868:    updates the $delayqueue to have a new hash ref of the error
 6869: 
 6870: =cut
 6871: 
 6872: sub scantron_add_delay {
 6873:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6874:     push(@$delayqueue,
 6875: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6876: 	  'ecode' => $errorcode }
 6877: 	 );
 6878: }
 6879: 
 6880: =pod
 6881: 
 6882: =item scantron_find_student
 6883: 
 6884:    Finds the username for the current scanline
 6885: 
 6886:   Arguments:
 6887:    $scantron_record - hash result from scantron_parse_scanline
 6888:    $scan_data       - hash of correction information 
 6889:                       (see &scantron_getfile() form more information)
 6890:    $idmap           - hash from &username_to_idmap()
 6891:    $line            - number of current scanline
 6892:  
 6893:   Returns:
 6894:    Either 'username:domain' or undef if unknown
 6895: 
 6896: =cut
 6897: 
 6898: sub scantron_find_student {
 6899:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6900:     my $scanID=$$scantron_record{'scantron.ID'};
 6901:     if ($scanID =~ /^\s*$/) {
 6902:  	return &scan_data($scan_data,"$line.user");
 6903:     }
 6904:     foreach my $id (keys(%$idmap)) {
 6905:  	if (lc($id) eq lc($scanID)) {
 6906:  	    return $$idmap{$id};
 6907:  	}
 6908:     }
 6909:     return undef;
 6910: }
 6911: 
 6912: =pod
 6913: 
 6914: =item scantron_filter
 6915: 
 6916:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6917:    hidden resources was selected
 6918: 
 6919: =cut
 6920: 
 6921: sub scantron_filter {
 6922:     my ($curres)=@_;
 6923: 
 6924:     if (ref($curres) && $curres->is_problem()) {
 6925: 	# if the user has asked to not have either hidden
 6926: 	# or 'randomout' controlled resources to be graded
 6927: 	# don't include them
 6928: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6929: 	    && $curres->randomout) {
 6930: 	    return 0;
 6931: 	}
 6932: 	return 1;
 6933:     }
 6934:     return 0;
 6935: }
 6936: 
 6937: =pod
 6938: 
 6939: =item scantron_process_corrections
 6940: 
 6941:    Gets correction information out of submitted form data and corrects
 6942:    the scanline
 6943: 
 6944: =cut
 6945: 
 6946: sub scantron_process_corrections {
 6947:     my ($r) = @_;
 6948:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6949:     my ($scanlines,$scan_data)=&scantron_getfile();
 6950:     my $classlist=&Apache::loncoursedata::get_classlist();
 6951:     my $which=$env{'form.scantron_line'};
 6952:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6953:     my ($skip,$err,$errmsg);
 6954:     if ($env{'form.scantron_skip_record'}) {
 6955: 	$skip=1;
 6956:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6957: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6958: 	    $env{'form.scantron_domain'};
 6959: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6960: 	($line,$err,$errmsg)=
 6961: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6962: 				     'ID',{'newid'=>$newid,
 6963: 				    'username'=>$env{'form.scantron_username'},
 6964: 				    'domain'=>$env{'form.scantron_domain'}});
 6965:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6966: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6967: 	my $newCODE;
 6968: 	my %args;
 6969: 	if      ($resolution eq 'use_unfound') {
 6970: 	    $newCODE='use_unfound';
 6971: 	} elsif ($resolution eq 'use_found') {
 6972: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6973: 	} elsif ($resolution eq 'use_typed') {
 6974: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6975: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6976: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6977: 	}
 6978: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6979: 	    $args{'CODE_ignore_dup'}=1;
 6980: 	}
 6981: 	$args{'CODE'}=$newCODE;
 6982: 	($line,$err,$errmsg)=
 6983: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6984: 				     'CODE',\%args);
 6985:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6986: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6987: 	    ($line,$err,$errmsg)=
 6988: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6989: 					 $which,'answer',
 6990: 					 { 'question'=>$question,
 6991: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6992:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6993: 	    if ($err) { last; }
 6994: 	}
 6995:     }
 6996:     if ($err) {
 6997: 	$r->print(
 6998:             '<p class="LC_error">'
 6999:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7000:                 $errmsg)
 7001:            .'</p>');
 7002:     } else {
 7003: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7004: 	&scantron_putfile($scanlines,$scan_data);
 7005:     }
 7006: }
 7007: 
 7008: =pod
 7009: 
 7010: =item reset_skipping_status
 7011: 
 7012:    Forgets the current set of remember skipped scanlines (and thus
 7013:    reverts back to considering all lines in the
 7014:    scantron_skipped_<filename> file)
 7015: 
 7016: =cut
 7017: 
 7018: sub reset_skipping_status {
 7019:     my ($scanlines,$scan_data)=&scantron_getfile();
 7020:     &scan_data($scan_data,'remember_skipping',undef,1);
 7021:     &scantron_putfile(undef,$scan_data);
 7022: }
 7023: 
 7024: =pod
 7025: 
 7026: =item start_skipping
 7027: 
 7028:    Marks a scanline to be skipped. 
 7029: 
 7030: =cut
 7031: 
 7032: sub start_skipping {
 7033:     my ($scan_data,$i)=@_;
 7034:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7035:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7036: 	$remembered{$i}=2;
 7037:     } else {
 7038: 	$remembered{$i}=1;
 7039:     }
 7040:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7041: }
 7042: 
 7043: =pod
 7044: 
 7045: =item should_be_skipped
 7046: 
 7047:    Checks whether a scanline should be skipped.
 7048: 
 7049: =cut
 7050: 
 7051: sub should_be_skipped {
 7052:     my ($scanlines,$scan_data,$i)=@_;
 7053:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7054: 	# not redoing old skips
 7055: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7056: 	return 0;
 7057:     }
 7058:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7059: 
 7060:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7061: 	return 0;
 7062:     }
 7063:     return 1;
 7064: }
 7065: 
 7066: =pod
 7067: 
 7068: =item remember_current_skipped
 7069: 
 7070:    Discovers what scanlines are in the scantron_skipped_<filename>
 7071:    file and remembers them into scan_data for later use.
 7072: 
 7073: =cut
 7074: 
 7075: sub remember_current_skipped {
 7076:     my ($scanlines,$scan_data)=&scantron_getfile();
 7077:     my %to_remember;
 7078:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7079: 	if ($scanlines->{'skipped'}[$i]) {
 7080: 	    $to_remember{$i}=1;
 7081: 	}
 7082:     }
 7083: 
 7084:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7085:     &scantron_putfile(undef,$scan_data);
 7086: }
 7087: 
 7088: =pod
 7089: 
 7090: =item check_for_error
 7091: 
 7092:     Checks if there was an error when attempting to remove a specific
 7093:     scantron_.. bubblesheet data file. Prints out an error if
 7094:     something went wrong.
 7095: 
 7096: =cut
 7097: 
 7098: sub check_for_error {
 7099:     my ($r,$result)=@_;
 7100:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7101: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7102:     }
 7103: }
 7104: 
 7105: =pod
 7106: 
 7107: =item scantron_warning_screen
 7108: 
 7109:    Interstitial screen to make sure the operator has selected the
 7110:    correct options before we start the validation phase.
 7111: 
 7112: =cut
 7113: 
 7114: sub scantron_warning_screen {
 7115:     my ($button_text,$symb)=@_;
 7116:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7117:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7118:     my $CODElist;
 7119:     if ($scantron_config{'CODElocation'} &&
 7120: 	$scantron_config{'CODEstart'} &&
 7121: 	$scantron_config{'CODElength'}) {
 7122: 	$CODElist=$env{'form.scantron_CODElist'};
 7123: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7124: 	$CODElist=
 7125: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7126: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7127:     }
 7128:     my $lastbubblepoints;
 7129:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7130:         $lastbubblepoints =
 7131:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7132:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7133:     }
 7134:     return ('
 7135: <p>
 7136: <span class="LC_warning">
 7137: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7138: </p>
 7139: <table>
 7140: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7141: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7142: '.$CODElist.$lastbubblepoints.'
 7143: </table>
 7144: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7145: '.&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>
 7146: 
 7147: <br />
 7148: ');
 7149: }
 7150: 
 7151: =pod
 7152: 
 7153: =item scantron_do_warning
 7154: 
 7155:    Check if the operator has picked something for all required
 7156:    fields. Error out if something is missing.
 7157: 
 7158: =cut
 7159: 
 7160: sub scantron_do_warning {
 7161:     my ($r,$symb)=@_;
 7162:     if (!$symb) {return '';}
 7163:     my $default_form_data=&defaultFormData($symb);
 7164:     $r->print(&scantron_form_start().$default_form_data);
 7165:     if ( $env{'form.selectpage'} eq '' ||
 7166: 	 $env{'form.scantron_selectfile'} eq '' ||
 7167: 	 $env{'form.scantron_format'} eq '' ) {
 7168: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7169: 	if ( $env{'form.selectpage'} eq '') {
 7170: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7171: 	} 
 7172: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7173: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7174: 	} 
 7175: 	if ( $env{'form.scantron_format'} eq '') {
 7176: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7177: 	} 
 7178:     } else {
 7179: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7180:         my $bubbledbyhand=&hand_bubble_option();
 7181: 	$r->print('
 7182: '.$warning.$bubbledbyhand.'
 7183: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7184: <input type="hidden" name="command" value="scantron_validate" />
 7185: ');
 7186:     }
 7187:     $r->print("</form><br />");
 7188:     return '';
 7189: }
 7190: 
 7191: =pod
 7192: 
 7193: =item scantron_form_start
 7194: 
 7195:     html hidden input for remembering all selected grading options
 7196: 
 7197: =cut
 7198: 
 7199: sub scantron_form_start {
 7200:     my ($max_bubble)=@_;
 7201:     my $result= <<SCANTRONFORM;
 7202: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7203:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7204:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7205:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7206:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7207:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7208:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7209:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7210:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7211:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7212: SCANTRONFORM
 7213: 
 7214:   my $line = 0;
 7215:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7216:        my $chunk =
 7217: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7218:        $chunk .=
 7219: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7220:        $chunk .= 
 7221:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7222:        $chunk .=
 7223:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7224:        $chunk .=
 7225:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7226:        $result .= $chunk;
 7227:        $line++;
 7228:     }
 7229:     return $result;
 7230: }
 7231: 
 7232: =pod
 7233: 
 7234: =item scantron_validate_file
 7235: 
 7236:     Dispatch routine for doing validation of a bubblesheet data file.
 7237: 
 7238:     Also processes any necessary information resets that need to
 7239:     occur before validation begins (ignore previous corrections,
 7240:     restarting the skipped records processing)
 7241: 
 7242: =cut
 7243: 
 7244: sub scantron_validate_file {
 7245:     my ($r,$symb) = @_;
 7246:     if (!$symb) {return '';}
 7247:     my $default_form_data=&defaultFormData($symb);
 7248:     
 7249:     # do the detection of only doing skipped records first before we delete
 7250:     # them when doing the corrections reset
 7251:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7252: 	&reset_skipping_status();
 7253:     }
 7254:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7255: 	&remember_current_skipped();
 7256: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7257:     }
 7258: 
 7259:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7260: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7261: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7262: 	&check_for_error($r,&scantron_remove_scan_data());
 7263: 	$env{'form.scantron_options_ignore'}='done';
 7264:     }
 7265: 
 7266:     if ($env{'form.scantron_corrections'}) {
 7267: 	&scantron_process_corrections($r);
 7268:     }
 7269:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7270:     #get the student pick code ready
 7271:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7272:     my $nav_error;
 7273:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7274:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7275:     if ($nav_error) {
 7276:         $r->print(&navmap_errormsg());
 7277:         return '';
 7278:     }
 7279:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7280:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7281:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7282:     }
 7283:     $r->print($result);
 7284:     
 7285:     my @validate_phases=( 'sequence',
 7286: 			  'ID',
 7287: 			  'CODE',
 7288: 			  'doublebubble',
 7289: 			  'missingbubbles');
 7290:     if (!$env{'form.validatepass'}) {
 7291: 	$env{'form.validatepass'} = 0;
 7292:     }
 7293:     my $currentphase=$env{'form.validatepass'};
 7294: 
 7295: 
 7296:     my $stop=0;
 7297:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7298: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7299: 	$r->rflush();
 7300: 
 7301: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7302: 	{
 7303: 	    no strict 'refs';
 7304: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7305: 	}
 7306:     }
 7307:     if (!$stop) {
 7308: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7309: 	$r->print(&mt('Validation process complete.').'<br />'.
 7310:                   $warning.
 7311:                   &mt('Perform verification for each student after storage of submissions?').
 7312:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7313:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7314:                   ('&nbsp;'x3).'<label>'.
 7315:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7316:                   '</label></span><br />'.
 7317:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7318:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7319:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7320:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7321:     } else {
 7322: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7323: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7324:     }
 7325:     if ($stop) {
 7326: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7327: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7328: 	    $r->print(' '.&mt('this error').' <br />');
 7329: 
 7330:             $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>');
 7331: 	} else {
 7332:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7333: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7334:             } else {
 7335:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7336:             }
 7337: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7338: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7339: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7340: 	}
 7341:     }
 7342:     $r->print(" </form><br />");
 7343:     return '';
 7344: }
 7345: 
 7346: 
 7347: =pod
 7348: 
 7349: =item scantron_remove_file
 7350: 
 7351:    Removes the requested bubblesheet data file, makes sure that
 7352:    scantron_original_<filename> is never removed
 7353: 
 7354: 
 7355: =cut
 7356: 
 7357: sub scantron_remove_file {
 7358:     my ($which)=@_;
 7359:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7360:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7361:     my $file='scantron_';
 7362:     if ($which eq 'corrected' || $which eq 'skipped') {
 7363: 	$file.=$which.'_';
 7364:     } else {
 7365: 	return 'refused';
 7366:     }
 7367:     $file.=$env{'form.scantron_selectfile'};
 7368:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7369: }
 7370: 
 7371: 
 7372: =pod
 7373: 
 7374: =item scantron_remove_scan_data
 7375: 
 7376:    Removes all scan_data correction for the requested bubblesheet
 7377:    data file.  (In the case that both the are doing skipped records we need
 7378:    to remember the old skipped lines for the time being so that element
 7379:    persists for a while.)
 7380: 
 7381: =cut
 7382: 
 7383: sub scantron_remove_scan_data {
 7384:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7385:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7386:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7387:     my @todelete;
 7388:     my $filename=$env{'form.scantron_selectfile'};
 7389:     foreach my $key (@keys) {
 7390: 	if ($key=~/^\Q$filename\E_/) {
 7391: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7392: 		$key=~/remember_skipping/) {
 7393: 		next;
 7394: 	    }
 7395: 	    push(@todelete,$key);
 7396: 	}
 7397:     }
 7398:     my $result;
 7399:     if (@todelete) {
 7400: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7401: 				       \@todelete,$cdom,$cname);
 7402:     } else {
 7403: 	$result = 'ok';
 7404:     }
 7405:     return $result;
 7406: }
 7407: 
 7408: 
 7409: =pod
 7410: 
 7411: =item scantron_getfile
 7412: 
 7413:     Fetches the requested bubblesheet data file (all 3 versions), and
 7414:     the scan_data hash
 7415:   
 7416:   Arguments:
 7417:     None
 7418: 
 7419:   Returns:
 7420:     2 hash references
 7421: 
 7422:      - first one has 
 7423:          orig      -
 7424:          corrected -
 7425:          skipped   -  each of which points to an array ref of the specified
 7426:                       file broken up into individual lines
 7427:          count     - number of scanlines
 7428:  
 7429:      - second is the scan_data hash possible keys are
 7430:        ($number refers to scanline numbered $number and thus the key affects
 7431:         only that scanline
 7432:         $bubline refers to the specific bubble line element and the aspects
 7433:         refers to that specific bubble line element)
 7434: 
 7435:        $number.user - username:domain to use
 7436:        $number.CODE_ignore_dup 
 7437:                     - ignore the duplicate CODE error 
 7438:        $number.useCODE
 7439:                     - use the CODE in the scanline as is
 7440:        $number.no_bubble.$bubline
 7441:                     - it is valid that there is no bubbled in bubble
 7442:                       at $number $bubline
 7443:        remember_skipping
 7444:                     - a frozen hash containing keys of $number and values
 7445:                       of either 
 7446:                         1 - we are on a 'do skipped records pass' and plan
 7447:                             on processing this line
 7448:                         2 - we are on a 'do skipped records pass' and this
 7449:                             scanline has been marked to skip yet again
 7450: 
 7451: =cut
 7452: 
 7453: sub scantron_getfile {
 7454:     #FIXME really would prefer a scantron directory
 7455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7457:     my $lines;
 7458:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7459: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7460:     my %scanlines;
 7461:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7462:     my $temp=$scanlines{'orig'};
 7463:     $scanlines{'count'}=$#$temp;
 7464: 
 7465:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7466: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7467:     if ($lines eq '-1') {
 7468: 	$scanlines{'corrected'}=[];
 7469:     } else {
 7470: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7471:     }
 7472:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7473: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7474:     if ($lines eq '-1') {
 7475: 	$scanlines{'skipped'}=[];
 7476:     } else {
 7477: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7478:     }
 7479:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7480:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7481:     my %scan_data = @tmp;
 7482:     return (\%scanlines,\%scan_data);
 7483: }
 7484: 
 7485: =pod
 7486: 
 7487: =item lonnet_putfile
 7488: 
 7489:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7490: 
 7491:  Arguments:
 7492:    $contents - data to store
 7493:    $filename - filename to store $contents into
 7494: 
 7495:  Returns:
 7496:    result value from &Apache::lonnet::finishuserfileupload
 7497: 
 7498: =cut
 7499: 
 7500: sub lonnet_putfile {
 7501:     my ($contents,$filename)=@_;
 7502:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7503:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7504:     $env{'form.sillywaytopassafilearound'}=$contents;
 7505:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7506: 
 7507: }
 7508: 
 7509: =pod
 7510: 
 7511: =item scantron_putfile
 7512: 
 7513:     Stores the current version of the bubblesheet data files, and the
 7514:     scan_data hash. (Does not modify the original version only the
 7515:     corrected and skipped versions.
 7516: 
 7517:  Arguments:
 7518:     $scanlines - hash ref that looks like the first return value from
 7519:                  &scantron_getfile()
 7520:     $scan_data - hash ref that looks like the second return value from
 7521:                  &scantron_getfile()
 7522: 
 7523: =cut
 7524: 
 7525: sub scantron_putfile {
 7526:     my ($scanlines,$scan_data) = @_;
 7527:     #FIXME really would prefer a scantron directory
 7528:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7530:     if ($scanlines) {
 7531: 	my $prefix='scantron_';
 7532: # no need to update orig, shouldn't change
 7533: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7534: #		    $env{'form.scantron_selectfile'});
 7535: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7536: 			$prefix.'corrected_'.
 7537: 			$env{'form.scantron_selectfile'});
 7538: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7539: 			$prefix.'skipped_'.
 7540: 			$env{'form.scantron_selectfile'});
 7541:     }
 7542:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7543: }
 7544: 
 7545: =pod
 7546: 
 7547: =item scantron_get_line
 7548: 
 7549:    Returns the correct version of the scanline
 7550: 
 7551:  Arguments:
 7552:     $scanlines - hash ref that looks like the first return value from
 7553:                  &scantron_getfile()
 7554:     $scan_data - hash ref that looks like the second return value from
 7555:                  &scantron_getfile()
 7556:     $i         - number of the requested line (starts at 0)
 7557: 
 7558:  Returns:
 7559:    A scanline, (either the original or the corrected one if it
 7560:    exists), or undef if the requested scanline should be
 7561:    skipped. (Either because it's an skipped scanline, or it's an
 7562:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7563:    pass.
 7564: 
 7565: =cut
 7566: 
 7567: sub scantron_get_line {
 7568:     my ($scanlines,$scan_data,$i)=@_;
 7569:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7570:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7571:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7572:     return $scanlines->{'orig'}[$i]; 
 7573: }
 7574: 
 7575: =pod
 7576: 
 7577: =item scantron_todo_count
 7578: 
 7579:     Counts the number of scanlines that need processing.
 7580: 
 7581:  Arguments:
 7582:     $scanlines - hash ref that looks like the first return value from
 7583:                  &scantron_getfile()
 7584:     $scan_data - hash ref that looks like the second return value from
 7585:                  &scantron_getfile()
 7586: 
 7587:  Returns:
 7588:     $count - number of scanlines to process
 7589: 
 7590: =cut
 7591: 
 7592: sub get_todo_count {
 7593:     my ($scanlines,$scan_data)=@_;
 7594:     my $count=0;
 7595:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7596: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7597: 	if ($line=~/^[\s\cz]*$/) { next; }
 7598: 	$count++;
 7599:     }
 7600:     return $count;
 7601: }
 7602: 
 7603: =pod
 7604: 
 7605: =item scantron_put_line
 7606: 
 7607:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7608:     data file.
 7609: 
 7610:  Arguments:
 7611:     $scanlines - hash ref that looks like the first return value from
 7612:                  &scantron_getfile()
 7613:     $scan_data - hash ref that looks like the second return value from
 7614:                  &scantron_getfile()
 7615:     $i         - line number to update
 7616:     $newline   - contents of the updated scanline
 7617:     $skip      - if true make the line for skipping and update the
 7618:                  'skipped' file
 7619: 
 7620: =cut
 7621: 
 7622: sub scantron_put_line {
 7623:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7624:     if ($skip) {
 7625: 	$scanlines->{'skipped'}[$i]=$newline;
 7626: 	&start_skipping($scan_data,$i);
 7627: 	return;
 7628:     }
 7629:     $scanlines->{'corrected'}[$i]=$newline;
 7630: }
 7631: 
 7632: =pod
 7633: 
 7634: =item scantron_clear_skip
 7635: 
 7636:    Remove a line from the 'skipped' file
 7637: 
 7638:  Arguments:
 7639:     $scanlines - hash ref that looks like the first return value from
 7640:                  &scantron_getfile()
 7641:     $scan_data - hash ref that looks like the second return value from
 7642:                  &scantron_getfile()
 7643:     $i         - line number to update
 7644: 
 7645: =cut
 7646: 
 7647: sub scantron_clear_skip {
 7648:     my ($scanlines,$scan_data,$i)=@_;
 7649:     if (exists($scanlines->{'skipped'}[$i])) {
 7650: 	undef($scanlines->{'skipped'}[$i]);
 7651: 	return 1;
 7652:     }
 7653:     return 0;
 7654: }
 7655: 
 7656: =pod
 7657: 
 7658: =item scantron_filter_not_exam
 7659: 
 7660:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7661:    filter out resources that are not marked as 'exam' mode
 7662: 
 7663: =cut
 7664: 
 7665: sub scantron_filter_not_exam {
 7666:     my ($curres)=@_;
 7667:     
 7668:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7669: 	# if the user has asked to not have either hidden
 7670: 	# or 'randomout' controlled resources to be graded
 7671: 	# don't include them
 7672: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7673: 	    && $curres->randomout) {
 7674: 	    return 0;
 7675: 	}
 7676: 	return 1;
 7677:     }
 7678:     return 0;
 7679: }
 7680: 
 7681: =pod
 7682: 
 7683: =item scantron_validate_sequence
 7684: 
 7685:     Validates the selected sequence, checking for resource that are
 7686:     not set to exam mode.
 7687: 
 7688: =cut
 7689: 
 7690: sub scantron_validate_sequence {
 7691:     my ($r,$currentphase) = @_;
 7692: 
 7693:     my $navmap=Apache::lonnavmaps::navmap->new();
 7694:     unless (ref($navmap)) {
 7695:         $r->print(&navmap_errormsg());
 7696:         return (1,$currentphase);
 7697:     }
 7698:     my (undef,undef,$sequence)=
 7699: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7700: 
 7701:     my $map=$navmap->getResourceByUrl($sequence);
 7702: 
 7703:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7704:                                     value="ignore" />');
 7705:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7706: 	my @resources=
 7707: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7708: 	if (@resources) {
 7709: 	    $r->print('<p class="LC_warning">'
 7710:                .&mt('Some resources in the sequence currently are not set to'
 7711:                    .' exam mode. Grading these resources currently may not'
 7712:                    .' work correctly.')
 7713:                .'</p>'
 7714:             );
 7715: 	    return (1,$currentphase);
 7716: 	}
 7717:     }
 7718: 
 7719:     return (0,$currentphase+1);
 7720: }
 7721: 
 7722: 
 7723: 
 7724: sub scantron_validate_ID {
 7725:     my ($r,$currentphase) = @_;
 7726:     
 7727:     #get student info
 7728:     my $classlist=&Apache::loncoursedata::get_classlist();
 7729:     my %idmap=&username_to_idmap($classlist);
 7730: 
 7731:     #get scantron line setup
 7732:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7733:     my ($scanlines,$scan_data)=&scantron_getfile();
 7734: 
 7735:     my $nav_error;
 7736:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7737:     if ($nav_error) {
 7738:         $r->print(&navmap_errormsg());
 7739:         return(1,$currentphase);
 7740:     }
 7741: 
 7742:     my %found=('ids'=>{},'usernames'=>{});
 7743:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7744: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7745: 	if ($line=~/^[\s\cz]*$/) { next; }
 7746: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7747: 						 $scan_data);
 7748: 	my $id=$$scan_record{'scantron.ID'};
 7749: 	my $found;
 7750: 	foreach my $checkid (keys(%idmap)) {
 7751: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7752: 	}
 7753: 	if ($found) {
 7754: 	    my $username=$idmap{$found};
 7755: 	    if ($found{'ids'}{$found}) {
 7756: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7757: 					 $line,'duplicateID',$found);
 7758: 		return(1,$currentphase);
 7759: 	    } elsif ($found{'usernames'}{$username}) {
 7760: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7761: 					 $line,'duplicateID',$username);
 7762: 		return(1,$currentphase);
 7763: 	    }
 7764: 	    #FIXME store away line we previously saw the ID on to use above
 7765: 	    $found{'ids'}{$found}++;
 7766: 	    $found{'usernames'}{$username}++;
 7767: 	} else {
 7768: 	    if ($id =~ /^\s*$/) {
 7769: 		my $username=&scan_data($scan_data,"$i.user");
 7770: 		if (defined($username) && $found{'usernames'}{$username}) {
 7771: 		    &scantron_get_correction($r,$i,$scan_record,
 7772: 					     \%scantron_config,
 7773: 					     $line,'duplicateID',$username);
 7774: 		    return(1,$currentphase);
 7775: 		} elsif (!defined($username)) {
 7776: 		    &scantron_get_correction($r,$i,$scan_record,
 7777: 					     \%scantron_config,
 7778: 					     $line,'incorrectID');
 7779: 		    return(1,$currentphase);
 7780: 		}
 7781: 		$found{'usernames'}{$username}++;
 7782: 	    } else {
 7783: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7784: 					 $line,'incorrectID');
 7785: 		return(1,$currentphase);
 7786: 	    }
 7787: 	}
 7788:     }
 7789: 
 7790:     return (0,$currentphase+1);
 7791: }
 7792: 
 7793: 
 7794: sub scantron_get_correction {
 7795:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7796:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7797: #FIXME in the case of a duplicated ID the previous line, probably need
 7798: #to show both the current line and the previous one and allow skipping
 7799: #the previous one or the current one
 7800: 
 7801:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7802:         $r->print(
 7803:             '<p class="LC_warning">'
 7804:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7805:                 "<b>$error</b>",
 7806:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7807:            ."</p> \n");
 7808:     } else {
 7809:         $r->print(
 7810:             '<p class="LC_warning">'
 7811:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7812:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7813:            ."</p> \n");
 7814:     }
 7815:     my $message =
 7816:         '<p>'
 7817:        .&mt('The ID on the form is [_1]',
 7818:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7819:        .'<br />'
 7820:        .&mt('The name on the paper is [_1], [_2]',
 7821:             $$scan_record{'scantron.LastName'},
 7822:             $$scan_record{'scantron.FirstName'})
 7823:        .'</p>';
 7824: 
 7825:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7826:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7827:                            # Array populated for doublebubble or
 7828:     my @lines_to_correct;  # missingbubble errors to build javascript
 7829:                            # to validate radio button checking   
 7830: 
 7831:     if ($error =~ /ID$/) {
 7832: 	if ($error eq 'incorrectID') {
 7833: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7834: 		      "</p>\n");
 7835: 	} elsif ($error eq 'duplicateID') {
 7836: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7837: 	}
 7838: 	$r->print($message);
 7839: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7840: 	$r->print("\n<ul><li> ");
 7841: 	#FIXME it would be nice if this sent back the user ID and
 7842: 	#could do partial userID matches
 7843: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7844: 				       'scantron_username','scantron_domain'));
 7845: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7846: 	$r->print("\n:\n".
 7847: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7848: 
 7849: 	$r->print('</li>');
 7850:     } elsif ($error =~ /CODE$/) {
 7851: 	if ($error eq 'incorrectCODE') {
 7852: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7853: 	} elsif ($error eq 'duplicateCODE') {
 7854: 	    $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");
 7855: 	}
 7856:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7857:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7858:                  ."</p>\n");
 7859: 	$r->print($message);
 7860: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7861: 	$r->print("\n<br /> ");
 7862: 	my $i=0;
 7863: 	if ($error eq 'incorrectCODE' 
 7864: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7865: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7866: 	    if ($closest > 0) {
 7867: 		foreach my $testcode (@{$closest}) {
 7868: 		    my $checked='';
 7869: 		    if (!$i) { $checked=' checked="checked"'; }
 7870: 		    $r->print("
 7871:    <label>
 7872:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7873:        ".&mt("Use the similar CODE [_1] instead.",
 7874: 	    "<b><tt>".$testcode."</tt></b>")."
 7875:     </label>
 7876:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7877: 		    $r->print("\n<br />");
 7878: 		    $i++;
 7879: 		}
 7880: 	    }
 7881: 	}
 7882: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7883: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7884: 	    $r->print("
 7885:     <label>
 7886:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7887:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7888: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7889:     </label>");
 7890: 	    $r->print("\n<br />");
 7891: 	}
 7892: 
 7893: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7894: function change_radio(field) {
 7895:     var slct=document.scantronupload.scantron_CODE_resolution;
 7896:     var i;
 7897:     for (i=0;i<slct.length;i++) {
 7898:         if (slct[i].value==field) { slct[i].checked=true; }
 7899:     }
 7900: }
 7901: ENDSCRIPT
 7902: 	my $href="/adm/pickcode?".
 7903: 	   "form=".&escape("scantronupload").
 7904: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7905: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7906: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7907: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7908: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7909: 	    $r->print("
 7910:     <label>
 7911:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7912:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7913: 	     "<a target='_blank' href='$href'>","</a>")."
 7914:     </label> 
 7915:     ".&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\')" />'));
 7916: 	    $r->print("\n<br />");
 7917: 	}
 7918: 	$r->print("
 7919:     <label>
 7920:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7921:        ".&mt("Use [_1] as the CODE.",
 7922: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7923: 	$r->print("\n<br /><br />");
 7924:     } elsif ($error eq 'doublebubble') {
 7925: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7926: 
 7927: 	# The form field scantron_questions is acutally a list of line numbers.
 7928: 	# represented by this form so:
 7929: 
 7930: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7931:                                                 $respnumlookup,$startline);
 7932: 
 7933: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7934: 		  $line_list.'" />');
 7935: 	$r->print($message);
 7936: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7937: 	foreach my $question (@{$arg}) {
 7938: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7939:                                                    $scan_record, $error,
 7940:                                                    $randomorder,$randompick,
 7941:                                                    $respnumlookup,$startline);
 7942:             push(@lines_to_correct,@linenums);
 7943: 	}
 7944:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7945:     } elsif ($error eq 'missingbubble') {
 7946: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7947: 	$r->print($message);
 7948: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7949: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7950: 
 7951: 	# The form field scantron_questions is actually a list of line numbers not
 7952: 	# a list of question numbers. Therefore:
 7953: 	#
 7954: 	
 7955: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7956:                                                 $respnumlookup,$startline);
 7957: 
 7958: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7959: 		  $line_list.'" />');
 7960: 	foreach my $question (@{$arg}) {
 7961: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7962:                                                    $scan_record, $error,
 7963:                                                    $randomorder,$randompick,
 7964:                                                    $respnumlookup,$startline);
 7965:             push(@lines_to_correct,@linenums);
 7966: 	}
 7967:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7968:     } else {
 7969: 	$r->print("\n<ul>");
 7970:     }
 7971:     $r->print("\n</li></ul>");
 7972: }
 7973: 
 7974: sub verify_bubbles_checked {
 7975:     my (@ansnums) = @_;
 7976:     my $ansnumstr = join('","',@ansnums);
 7977:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7978:     &js_escape(\$warning);
 7979:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 7980: function verify_bubble_radio(form) {
 7981:     var ansnumArray = new Array ("$ansnumstr");
 7982:     var need_bubble_count = 0;
 7983:     for (var i=0; i<ansnumArray.length; i++) {
 7984:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7985:             var bubble_picked = 0; 
 7986:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7987:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7988:                     bubble_picked = 1;
 7989:                 }
 7990:             }
 7991:             if (bubble_picked == 0) {
 7992:                 need_bubble_count ++;
 7993:             }
 7994:         }
 7995:     }
 7996:     if (need_bubble_count) {
 7997:         alert("$warning");
 7998:         return;
 7999:     }
 8000:     form.submit(); 
 8001: }
 8002: ENDSCRIPT
 8003:     return $output;
 8004: }
 8005: 
 8006: =pod
 8007: 
 8008: =item  questions_to_line_list
 8009: 
 8010: Converts a list of questions into a string of comma separated
 8011: line numbers in the answer sheet used by the questions.  This is
 8012: used to fill in the scantron_questions form field.
 8013: 
 8014:   Arguments:
 8015:      questions    - Reference to an array of questions.
 8016:      randomorder  - True if randomorder in use.
 8017:      randompick   - True if randompick in use.
 8018:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8019:                      for current line to question number used for same question
 8020:                      in "Master Seqence" (as seen by Course Coordinator).
 8021:      startline    - Reference to hash where key is question number (0 is first)
 8022:                     and key is number of first bubble line for current student
 8023:                     or code-based randompick and/or randomorder.
 8024: 
 8025: =cut
 8026: 
 8027: 
 8028: sub questions_to_line_list {
 8029:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8030:     my @lines;
 8031: 
 8032:     foreach my $item (@{$questions}) {
 8033:         my $question = $item;
 8034:         my ($first,$count,$last);
 8035:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8036:             $question = $1;
 8037:             my $subquestion = $2;
 8038:             my $responsenum = $question-1;
 8039:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8040:                 $responsenum = $respnumlookup->{$question-1};
 8041:                 if (ref($startline) eq 'HASH') {
 8042:                     $first = $startline->{$question-1} + 1;
 8043:                 }
 8044:             } else {
 8045:                 $first = $first_bubble_line{$responsenum} + 1;
 8046:             }
 8047:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8048:             my $subcount = 1;
 8049:             while ($subcount<$subquestion) {
 8050:                 $first += $subans[$subcount-1];
 8051:                 $subcount ++;
 8052:             }
 8053:             $count = $subans[$subquestion-1];
 8054:         } else {
 8055:             my $responsenum = $question-1;
 8056:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8057:                 $responsenum = $respnumlookup->{$question-1};
 8058:                 if (ref($startline) eq 'HASH') {
 8059:                     $first = $startline->{$question-1} + 1;
 8060:                 }
 8061:             } else {
 8062:                 $first = $first_bubble_line{$responsenum} + 1;
 8063:             }
 8064:             $count   = $bubble_lines_per_response{$responsenum};
 8065:         }
 8066:         $last = $first+$count-1;
 8067:         push(@lines, ($first..$last));
 8068:     }
 8069:     return join(',', @lines);
 8070: }
 8071: 
 8072: =pod 
 8073: 
 8074: =item prompt_for_corrections
 8075: 
 8076: Prompts for a potentially multiline correction to the
 8077: user's bubbling (factors out common code from scantron_get_correction
 8078: for multi and missing bubble cases).
 8079: 
 8080:  Arguments:
 8081:    $r           - Apache request object.
 8082:    $question    - The question number to prompt for.
 8083:    $scan_config - The scantron file configuration hash.
 8084:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8085:    $error       - Type of error
 8086:    $randomorder - True if randomorder in use.
 8087:    $randompick  - True if randompick in use.
 8088:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8089:                     for current line to question number used for same question
 8090:                     in "Master Seqence" (as seen by Course Coordinator).
 8091:    $startline   - Reference to hash where key is question number (0 is first)
 8092:                   and value is number of first bubble line for current student
 8093:                   or code-based randompick and/or randomorder.
 8094: 
 8095:  Implicit inputs:
 8096:    %bubble_lines_per_response   - Starting line numbers for each question.
 8097:                                   Numbered from 0 (but question numbers are from
 8098:                                   1.
 8099:    %first_bubble_line           - Starting bubble line for each question.
 8100:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8101:                                   type problems render as separate sub-questions, 
 8102:                                   in exam mode. This hash contains a 
 8103:                                   comma-separated list of the lines per 
 8104:                                   sub-question.
 8105:    %responsetype_per_response   - essayresponse, formularesponse,
 8106:                                   stringresponse, imageresponse, reactionresponse,
 8107:                                   and organicresponse type problem parts can have
 8108:                                   multiple lines per response if the weight
 8109:                                   assigned exceeds 10.  In this case, only
 8110:                                   one bubble per line is permitted, but more 
 8111:                                   than one line might contain bubbles, e.g.
 8112:                                   bubbling of: line 1 - J, line 2 - J, 
 8113:                                   line 3 - B would assign 22 points.  
 8114: 
 8115: =cut
 8116: 
 8117: sub prompt_for_corrections {
 8118:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8119:         $randompick, $respnumlookup, $startline) = @_;
 8120:     my ($current_line,$lines);
 8121:     my @linenums;
 8122:     my $questionnum = $question;
 8123:     my ($first,$responsenum);
 8124:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8125:         $question = $1;
 8126:         my $subquestion = $2;
 8127:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8128:             $responsenum = $respnumlookup->{$question-1};
 8129:             if (ref($startline) eq 'HASH') {
 8130:                 $first = $startline->{$question-1};
 8131:             }
 8132:         } else {
 8133:             $responsenum = $question-1;
 8134:             $first = $first_bubble_line{$responsenum};
 8135:         }
 8136:         $current_line = $first + 1 ;
 8137:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8138:         my $subcount = 1;
 8139:         while ($subcount<$subquestion) {
 8140:             $current_line += $subans[$subcount-1];
 8141:             $subcount ++;
 8142:         }
 8143:         $lines = $subans[$subquestion-1];
 8144:     } else {
 8145:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8146:             $responsenum = $respnumlookup->{$question-1};
 8147:             if (ref($startline) eq 'HASH') {
 8148:                 $first = $startline->{$question-1};
 8149:             }
 8150:         } else {
 8151:             $responsenum = $question-1;
 8152:             $first = $first_bubble_line{$responsenum};
 8153:         }
 8154:         $current_line = $first + 1;
 8155:         $lines        = $bubble_lines_per_response{$responsenum};
 8156:     }
 8157:     if ($lines > 1) {
 8158:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8159:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8160:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8161:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8162:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8163:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8164:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8165:             $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 />');
 8166:         } else {
 8167:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8168:         }
 8169:     }
 8170:     for (my $i =0; $i < $lines; $i++) {
 8171:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8172: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8173: 	        		  $questionnum,$error,split('', $selected));
 8174:         push(@linenums,$current_line);
 8175: 	$current_line++;
 8176:     }
 8177:     if ($lines > 1) {
 8178: 	$r->print("<hr /><br />");
 8179:     }
 8180:     return @linenums;
 8181: }
 8182: 
 8183: =pod
 8184: 
 8185: =item scantron_bubble_selector
 8186:   
 8187:    Generates the html radiobuttons to correct a single bubble line
 8188:    possibly showing the existing the selected bubbles if known
 8189: 
 8190:  Arguments:
 8191:     $r           - Apache request object
 8192:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8193:     $line        - Number of the line being displayed.
 8194:     $questionnum - Question number (may include subquestion)
 8195:     $error       - Type of error.
 8196:     @selected    - Array of bubbles picked on this line.
 8197: 
 8198: =cut
 8199: 
 8200: sub scantron_bubble_selector {
 8201:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8202:     my $max=$$scan_config{'Qlength'};
 8203: 
 8204:     my $scmode=$$scan_config{'Qon'};
 8205:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8206:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8207:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8208:             $max=$$scan_config{'BubblesPerRow'};
 8209:             if (($scmode eq 'number') && ($max > 10)) {
 8210:                 $max = 10;
 8211:             } elsif (($scmode eq 'letter') && $max > 26) {
 8212:                 $max = 26;
 8213:             }
 8214:         } else {
 8215:             $max = 10;
 8216:         }
 8217:     }
 8218: 
 8219:     my @alphabet=('A'..'Z');
 8220:     $r->print(&Apache::loncommon::start_data_table().
 8221:               &Apache::loncommon::start_data_table_row());
 8222:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8223:     for (my $i=0;$i<$max+1;$i++) {
 8224: 	$r->print("\n".'<td align="center">');
 8225: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8226: 	else { $r->print('&nbsp;'); }
 8227: 	$r->print('</td>');
 8228:     }
 8229:     $r->print(&Apache::loncommon::end_data_table_row().
 8230:               &Apache::loncommon::start_data_table_row());
 8231:     for (my $i=0;$i<$max;$i++) {
 8232: 	$r->print("\n".
 8233: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8234: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8235:     }
 8236:     my $nobub_checked = ' ';
 8237:     if ($error eq 'missingbubble') {
 8238:         $nobub_checked = ' checked = "checked" ';
 8239:     }
 8240:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8241: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8242:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8243:               $line.'" value="'.$questionnum.'" /></td>');
 8244:     $r->print(&Apache::loncommon::end_data_table_row().
 8245:               &Apache::loncommon::end_data_table());
 8246: }
 8247: 
 8248: =pod
 8249: 
 8250: =item num_matches
 8251: 
 8252:    Counts the number of characters that are the same between the two arguments.
 8253: 
 8254:  Arguments:
 8255:    $orig - CODE from the scanline
 8256:    $code - CODE to match against
 8257: 
 8258:  Returns:
 8259:    $count - integer count of the number of same characters between the
 8260:             two arguments
 8261: 
 8262: =cut
 8263: 
 8264: sub num_matches {
 8265:     my ($orig,$code) = @_;
 8266:     my @code=split(//,$code);
 8267:     my @orig=split(//,$orig);
 8268:     my $same=0;
 8269:     for (my $i=0;$i<scalar(@code);$i++) {
 8270: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8271:     }
 8272:     return $same;
 8273: }
 8274: 
 8275: =pod
 8276: 
 8277: =item scantron_get_closely_matching_CODEs
 8278: 
 8279:    Cycles through all CODEs and finds the set that has the greatest
 8280:    number of same characters as the provided CODE
 8281: 
 8282:  Arguments:
 8283:    $allcodes - hash ref returned by &get_codes()
 8284:    $CODE     - CODE from the current scanline
 8285: 
 8286:  Returns:
 8287:    2 element list
 8288:     - first elements is number of how closely matching the best fit is 
 8289:       (5 means best set has 5 matching characters)
 8290:     - second element is an arrary ref containing the set of valid CODEs
 8291:       that best fit the passed in CODE
 8292: 
 8293: =cut
 8294: 
 8295: sub scantron_get_closely_matching_CODEs {
 8296:     my ($allcodes,$CODE)=@_;
 8297:     my @CODEs;
 8298:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8299: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8300:     }
 8301: 
 8302:     return ($#CODEs,$CODEs[-1]);
 8303: }
 8304: 
 8305: =pod
 8306: 
 8307: =item get_codes
 8308: 
 8309:    Builds a hash which has keys of all of the valid CODEs from the selected
 8310:    set of remembered CODEs.
 8311: 
 8312:  Arguments:
 8313:   $old_name - name of the set of remembered CODEs
 8314:   $cdom     - domain of the course
 8315:   $cnum     - internal course name
 8316: 
 8317:  Returns:
 8318:   %allcodes - keys are the valid CODEs, values are all 1
 8319: 
 8320: =cut
 8321: 
 8322: sub get_codes {
 8323:     my ($old_name, $cdom, $cnum) = @_;
 8324:     if (!$old_name) {
 8325: 	$old_name=$env{'form.scantron_CODElist'};
 8326:     }
 8327:     if (!$cdom) {
 8328: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8329:     }
 8330:     if (!$cnum) {
 8331: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8332:     }
 8333:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8334: 				    $cdom,$cnum);
 8335:     my %allcodes;
 8336:     if ($result{"type\0$old_name"} eq 'number') {
 8337: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8338:     } else {
 8339: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8340:     }
 8341:     return %allcodes;
 8342: }
 8343: 
 8344: =pod
 8345: 
 8346: =item scantron_validate_CODE
 8347: 
 8348:    Validates all scanlines in the selected file to not have any
 8349:    invalid or underspecified CODEs and that none of the codes are
 8350:    duplicated if this was requested.
 8351: 
 8352: =cut
 8353: 
 8354: sub scantron_validate_CODE {
 8355:     my ($r,$currentphase) = @_;
 8356:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8357:     if ($scantron_config{'CODElocation'} &&
 8358: 	$scantron_config{'CODEstart'} &&
 8359: 	$scantron_config{'CODElength'}) {
 8360: 	if (!defined($env{'form.scantron_CODElist'})) {
 8361: 	    &FIXME_blow_up()
 8362: 	}
 8363:     } else {
 8364: 	return (0,$currentphase+1);
 8365:     }
 8366:     
 8367:     my %usedCODEs;
 8368: 
 8369:     my %allcodes=&get_codes();
 8370: 
 8371:     my $nav_error;
 8372:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8373:     if ($nav_error) {
 8374:         $r->print(&navmap_errormsg());
 8375:         return(1,$currentphase);
 8376:     }
 8377: 
 8378:     my ($scanlines,$scan_data)=&scantron_getfile();
 8379:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8380: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8381: 	if ($line=~/^[\s\cz]*$/) { next; }
 8382: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8383: 						 $scan_data);
 8384: 	my $CODE=$$scan_record{'scantron.CODE'};
 8385: 	my $error=0;
 8386: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8387: 	    &scantron_get_correction($r,$i,$scan_record,
 8388: 				     \%scantron_config,
 8389: 				     $line,'incorrectCODE',\%allcodes);
 8390: 	    return(1,$currentphase);
 8391: 	}
 8392: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8393: 	    && !$$scan_record{'scantron.useCODE'}) {
 8394: 	    &scantron_get_correction($r,$i,$scan_record,
 8395: 				     \%scantron_config,
 8396: 				     $line,'incorrectCODE',\%allcodes);
 8397: 	    return(1,$currentphase);
 8398: 	}
 8399: 	if (exists($usedCODEs{$CODE}) 
 8400: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8401: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8402: 	    &scantron_get_correction($r,$i,$scan_record,
 8403: 				     \%scantron_config,
 8404: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8405: 	    return(1,$currentphase);
 8406: 	}
 8407: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8408:     }
 8409:     return (0,$currentphase+1);
 8410: }
 8411: 
 8412: =pod
 8413: 
 8414: =item scantron_validate_doublebubble
 8415: 
 8416:    Validates all scanlines in the selected file to not have any
 8417:    bubble lines with multiple bubbles marked.
 8418: 
 8419: =cut
 8420: 
 8421: sub scantron_validate_doublebubble {
 8422:     my ($r,$currentphase) = @_;
 8423:     #get student info
 8424:     my $classlist=&Apache::loncoursedata::get_classlist();
 8425:     my %idmap=&username_to_idmap($classlist);
 8426:     my (undef,undef,$sequence)=
 8427:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8428: 
 8429:     #get scantron line setup
 8430:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8431:     my ($scanlines,$scan_data)=&scantron_getfile();
 8432: 
 8433:     my $navmap = Apache::lonnavmaps::navmap->new();
 8434:     unless (ref($navmap)) {
 8435:         $r->print(&navmap_errormsg());
 8436:         return(1,$currentphase);
 8437:     }
 8438:     my $map=$navmap->getResourceByUrl($sequence);
 8439:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8440:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8441:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8442:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8443: 
 8444:     my $nav_error;
 8445:     if (ref($map)) {
 8446:         $randomorder = $map->randomorder();
 8447:         $randompick = $map->randompick();
 8448:         if ($randomorder || $randompick) {
 8449:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8450:             if ($nav_error) {
 8451:                 $r->print(&navmap_errormsg());
 8452:                 return(1,$currentphase);
 8453:             }
 8454:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8455:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8456:         }
 8457:     } else {
 8458:         $r->print(&navmap_errormsg());
 8459:         return(1,$currentphase);
 8460:     }
 8461: 
 8462:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8463:     if ($nav_error) {
 8464:         $r->print(&navmap_errormsg());
 8465:         return(1,$currentphase);
 8466:     }
 8467: 
 8468:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8469: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8470: 	if ($line=~/^[\s\cz]*$/) { next; }
 8471: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8472: 						 $scan_data,undef,\%idmap,$randomorder,
 8473:                                                  $randompick,$sequence,\@master_seq,
 8474:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8475:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8476: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8477: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8478: 				 'doublebubble',
 8479: 				 $$scan_record{'scantron.doubleerror'},
 8480:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8481:     	return (1,$currentphase);
 8482:     }
 8483:     return (0,$currentphase+1);
 8484: }
 8485: 
 8486: 
 8487: sub scantron_get_maxbubble {
 8488:     my ($nav_error,$scantron_config) = @_;
 8489:     if (defined($env{'form.scantron_maxbubble'}) &&
 8490: 	$env{'form.scantron_maxbubble'}) {
 8491: 	&restore_bubble_lines();
 8492: 	return $env{'form.scantron_maxbubble'};
 8493:     }
 8494: 
 8495:     my (undef, undef, $sequence) =
 8496: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8497: 
 8498:     my $navmap=Apache::lonnavmaps::navmap->new();
 8499:     unless (ref($navmap)) {
 8500:         if (ref($nav_error)) {
 8501:             $$nav_error = 1;
 8502:         }
 8503:         return;
 8504:     }
 8505:     my $map=$navmap->getResourceByUrl($sequence);
 8506:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8507:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8508: 
 8509:     &Apache::lonxml::clear_problem_counter();
 8510: 
 8511:     my $uname       = $env{'user.name'};
 8512:     my $udom        = $env{'user.domain'};
 8513:     my $cid         = $env{'request.course.id'};
 8514:     my $total_lines = 0;
 8515:     %bubble_lines_per_response = ();
 8516:     %first_bubble_line         = ();
 8517:     %subdivided_bubble_lines   = ();
 8518:     %responsetype_per_response = ();
 8519:     %masterseq_id_responsenum  = ();
 8520: 
 8521:     my $response_number = 0;
 8522:     my $bubble_line     = 0;
 8523:     foreach my $resource (@resources) {
 8524:         my $resid = $resource->id();
 8525:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8526:                                                           $udom,undef,$bubbles_per_row);
 8527:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8528: 	    foreach my $part_id (@{$parts}) {
 8529:                 my $lines;
 8530: 
 8531: 	        # TODO - make this a persistent hash not an array.
 8532: 
 8533:                 # optionresponse, matchresponse and rankresponse type items 
 8534:                 # render as separate sub-questions in exam mode.
 8535:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8536:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8537:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8538:                     my ($numbub,$numshown);
 8539:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8540:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8541:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8542:                         }
 8543:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8544:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8545:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8546:                         }
 8547:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8548:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8549:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8550:                         }
 8551:                     }
 8552:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8553:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8554:                     }
 8555:                     my $bubbles_per_row =
 8556:                         &bubblesheet_bubbles_per_row($scantron_config);
 8557:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8558:                     if (($numbub % $bubbles_per_row) != 0) {
 8559:                         $inner_bubble_lines++;
 8560:                     }
 8561:                     for (my $i=0; $i<$numshown; $i++) {
 8562:                         $subdivided_bubble_lines{$response_number} .= 
 8563:                             $inner_bubble_lines.',';
 8564:                     }
 8565:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8566:                     $lines = $numshown * $inner_bubble_lines;
 8567:                 } else {
 8568:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8569:                 }
 8570: 
 8571:                 $first_bubble_line{$response_number} = $bubble_line;
 8572: 	        $bubble_lines_per_response{$response_number} = $lines;
 8573:                 $responsetype_per_response{$response_number} = 
 8574:                     $analysis->{$part_id.'.type'};
 8575:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8576: 	        $response_number++;
 8577: 
 8578: 	        $bubble_line +=  $lines;
 8579: 	        $total_lines +=  $lines;
 8580: 	    }
 8581:         }
 8582:     }
 8583:     &Apache::lonnet::delenv('scantron.');
 8584: 
 8585:     &save_bubble_lines();
 8586:     $env{'form.scantron_maxbubble'} =
 8587: 	$total_lines;
 8588:     return $env{'form.scantron_maxbubble'};
 8589: }
 8590: 
 8591: sub bubblesheet_bubbles_per_row {
 8592:     my ($scantron_config) = @_;
 8593:     my $bubbles_per_row;
 8594:     if (ref($scantron_config) eq 'HASH') {
 8595:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8596:     }
 8597:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8598:         $bubbles_per_row = 10;
 8599:     }
 8600:     return $bubbles_per_row;
 8601: }
 8602: 
 8603: sub scantron_validate_missingbubbles {
 8604:     my ($r,$currentphase) = @_;
 8605:     #get student info
 8606:     my $classlist=&Apache::loncoursedata::get_classlist();
 8607:     my %idmap=&username_to_idmap($classlist);
 8608:     my (undef,undef,$sequence)=
 8609:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8610: 
 8611:     #get scantron line setup
 8612:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8613:     my ($scanlines,$scan_data)=&scantron_getfile();
 8614: 
 8615:     my $navmap = Apache::lonnavmaps::navmap->new();
 8616:     unless (ref($navmap)) {
 8617:         $r->print(&navmap_errormsg());
 8618:         return(1,$currentphase);
 8619:     }
 8620: 
 8621:     my $map=$navmap->getResourceByUrl($sequence);
 8622:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8623:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8624:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8625:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8626: 
 8627:     my $nav_error;
 8628:     if (ref($map)) {
 8629:         $randomorder = $map->randomorder();
 8630:         $randompick = $map->randompick();
 8631:         if ($randomorder || $randompick) {
 8632:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8633:             if ($nav_error) {
 8634:                 $r->print(&navmap_errormsg());
 8635:                 return(1,$currentphase);
 8636:             }
 8637:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8638:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8639:         }
 8640:     } else {
 8641:         $r->print(&navmap_errormsg());
 8642:         return(1,$currentphase);
 8643:     }
 8644: 
 8645: 
 8646:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8647:     if ($nav_error) {
 8648:         $r->print(&navmap_errormsg());
 8649:         return(1,$currentphase);
 8650:     }
 8651: 
 8652:     if (!$max_bubble) { $max_bubble=2**31; }
 8653:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8654: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8655: 	if ($line=~/^[\s\cz]*$/) { next; }
 8656:         my $scan_record =
 8657:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8658:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8659:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8660:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8661: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8662: 	my @to_correct;
 8663: 	
 8664: 	# Probably here's where the error is...
 8665: 
 8666: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8667:             my $lastbubble;
 8668:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8669:                 my $question = $1;
 8670:                 my $subquestion = $2;
 8671:                 my ($first,$responsenum);
 8672:                 if ($randomorder || $randompick) {
 8673:                     $responsenum = $respnumlookup{$question-1};
 8674:                     $first = $startline{$question-1};
 8675:                 } else {
 8676:                     $responsenum = $question-1;
 8677:                     $first = $first_bubble_line{$responsenum};
 8678:                 }
 8679:                 if (!defined($first)) { next; }
 8680:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8681:                 my $subcount = 1;
 8682:                 while ($subcount<$subquestion) {
 8683:                     $first += $subans[$subcount-1];
 8684:                     $subcount ++;
 8685:                 }
 8686:                 my $count = $subans[$subquestion-1];
 8687:                 $lastbubble = $first + $count;
 8688:             } else {
 8689:                 my ($first,$responsenum);
 8690:                 if ($randomorder || $randompick) {
 8691:                     $responsenum = $respnumlookup{$missing-1};
 8692:                     $first = $startline{$missing-1};
 8693:                 } else {
 8694:                     $responsenum = $missing-1;
 8695:                     $first = $first_bubble_line{$responsenum};
 8696:                 }
 8697:                 if (!defined($first)) { next; }
 8698:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8699:             }
 8700:             if ($lastbubble > $max_bubble) { next; }
 8701: 	    push(@to_correct,$missing);
 8702: 	}
 8703: 	if (@to_correct) {
 8704: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8705: 				     $line,'missingbubble',\@to_correct,
 8706:                                      $randomorder,$randompick,\%respnumlookup,
 8707:                                      \%startline);
 8708: 	    return (1,$currentphase);
 8709: 	}
 8710: 
 8711:     }
 8712:     return (0,$currentphase+1);
 8713: }
 8714: 
 8715: sub hand_bubble_option {
 8716:     my (undef, undef, $sequence) =
 8717:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8718:     return if ($sequence eq '');
 8719:     my $navmap = Apache::lonnavmaps::navmap->new();
 8720:     unless (ref($navmap)) {
 8721:         return;
 8722:     }
 8723:     my $needs_hand_bubbles;
 8724:     my $map=$navmap->getResourceByUrl($sequence);
 8725:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8726:     foreach my $res (@resources) {
 8727:         if (ref($res)) {
 8728:             if ($res->is_problem()) {
 8729:                 my $partlist = $res->parts();
 8730:                 foreach my $part (@{ $partlist }) {
 8731:                     my @types = $res->responseType($part);
 8732:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8733:                         $needs_hand_bubbles = 1;
 8734:                         last;
 8735:                     }
 8736:                 }
 8737:             }
 8738:         }
 8739:     }
 8740:     if ($needs_hand_bubbles) {
 8741:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8742:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8743:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8744:                &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 />').
 8745:                '<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;'.
 8746:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8747:     }
 8748:     return;
 8749: }
 8750: 
 8751: sub scantron_process_students {
 8752:     my ($r,$symb) = @_;
 8753: 
 8754:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8755:     if (!$symb) {
 8756: 	return '';
 8757:     }
 8758:     my $default_form_data=&defaultFormData($symb);
 8759: 
 8760:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8761:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8762:     my ($scanlines,$scan_data)=&scantron_getfile();
 8763:     my $classlist=&Apache::loncoursedata::get_classlist();
 8764:     my %idmap=&username_to_idmap($classlist);
 8765:     my $navmap=Apache::lonnavmaps::navmap->new();
 8766:     unless (ref($navmap)) {
 8767:         $r->print(&navmap_errormsg());
 8768:         return '';
 8769:     }
 8770:     my $map=$navmap->getResourceByUrl($sequence);
 8771:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8772:         %grader_randomlists_by_symb);
 8773:     if (ref($map)) {
 8774:         $randomorder = $map->randomorder();
 8775:         $randompick = $map->randompick();
 8776:     } else {
 8777:         $r->print(&navmap_errormsg());
 8778:         return '';
 8779:     }
 8780:     my $nav_error;
 8781:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8782:     if ($randomorder || $randompick) {
 8783:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8784:         if ($nav_error) {
 8785:             $r->print(&navmap_errormsg());
 8786:             return '';
 8787:         }
 8788:     }
 8789:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8790:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8791: 
 8792:     my ($uname,$udom);
 8793:     my $result= <<SCANTRONFORM;
 8794: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8795:   <input type="hidden" name="command" value="scantron_configphase" />
 8796:   $default_form_data
 8797: SCANTRONFORM
 8798:     $r->print($result);
 8799: 
 8800:     my @delayqueue;
 8801:     my (%completedstudents,%scandata);
 8802:     
 8803:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8804:     my $count=&get_todo_count($scanlines,$scan_data);
 8805:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8806:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8807:     $r->print('<br />');
 8808:     my $start=&Time::HiRes::time();
 8809:     my $i=-1;
 8810:     my $started;
 8811: 
 8812:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8813:     if ($nav_error) {
 8814:         $r->print(&navmap_errormsg());
 8815:         return '';
 8816:     }
 8817: 
 8818:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8819:     # the user and return.
 8820: 
 8821:     if ($ssi_error) {
 8822: 	$r->print("</form>");
 8823: 	&ssi_print_error($r);
 8824:         &Apache::lonnet::remove_lock($lock);
 8825: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8826:     }
 8827: 
 8828:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8829:     my $numletts = scalar(keys(%lettdig));
 8830:     my %orderedforcode;
 8831: 
 8832:     while ($i<$scanlines->{'count'}) {
 8833:  	($uname,$udom)=('','');
 8834:  	$i++;
 8835:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8836:  	if ($line=~/^[\s\cz]*$/) { next; }
 8837: 	if ($started) {
 8838: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8839: 	}
 8840: 	$started=1;
 8841:         my %respnumlookup = ();
 8842:         my %startline = ();
 8843:         my $total;
 8844:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8845:  						 $scan_data,undef,\%idmap,$randomorder,
 8846:                                                  $randompick,$sequence,\@master_seq,
 8847:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8848:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8849:                                                  \$total);
 8850:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8851:  					      \%idmap,$i)) {
 8852:   	    &scantron_add_delay(\@delayqueue,$line,
 8853:  				'Unable to find a student that matches',1);
 8854:  	    next;
 8855:   	}
 8856:  	if (exists $completedstudents{$uname}) {
 8857:  	    &scantron_add_delay(\@delayqueue,$line,
 8858:  				'Student '.$uname.' has multiple sheets',2);
 8859:  	    next;
 8860:  	}
 8861:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8862:         my $user = $uname.':'.$usec;
 8863:   	($uname,$udom)=split(/:/,$uname);
 8864: 
 8865:         my $scancode;
 8866:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8867:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8868:             $scancode = $scan_record->{'scantron.CODE'};
 8869:         } else {
 8870:             $scancode = '';
 8871:         }
 8872: 
 8873:         my @mapresources = @resources;
 8874:         if ($randomorder || $randompick) {
 8875:             @mapresources =
 8876:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8877:                              \%orderedforcode);
 8878:         }
 8879:         my (%partids_by_symb,$res_error);
 8880:         foreach my $resource (@mapresources) {
 8881:             my $ressymb;
 8882:             if (ref($resource)) {
 8883:                 $ressymb = $resource->symb();
 8884:             } else {
 8885:                 $res_error = 1;
 8886:                 last;
 8887:             }
 8888:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8889:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8890:                 my $currcode;
 8891:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8892:                     $currcode = $scancode;
 8893:                 }
 8894:                 my ($analysis,$parts) =
 8895:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8896:                                               $uname,$udom,undef,$bubbles_per_row,
 8897:                                               $currcode);
 8898:                 $partids_by_symb{$ressymb} = $parts;
 8899:             } else {
 8900:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8901:             }
 8902:         }
 8903: 
 8904:         if ($res_error) {
 8905:             &scantron_add_delay(\@delayqueue,$line,
 8906:                                 'An error occurred while grading student '.$uname,2);
 8907:             next;
 8908:         }
 8909: 
 8910: 	&Apache::lonxml::clear_problem_counter();
 8911:   	&Apache::lonnet::appenv($scan_record);
 8912: 
 8913: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8914: 	    &scantron_putfile($scanlines,$scan_data);
 8915: 	}
 8916: 	
 8917:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8918:                                    \@mapresources,\%partids_by_symb,
 8919:                                    $bubbles_per_row,$randomorder,$randompick,
 8920:                                    \%respnumlookup,\%startline) 
 8921:             eq 'ssi_error') {
 8922:             $ssi_error = 0; # So end of handler error message does not trigger.
 8923:             $r->print("</form>");
 8924:             &ssi_print_error($r);
 8925:             &Apache::lonnet::remove_lock($lock);
 8926:             return '';      # Why return ''?  Beats me.
 8927:         }
 8928: 
 8929:         if (($scancode) && ($randomorder || $randompick)) {
 8930:             my $parmresult =
 8931:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8932:                                                        '0_examcode',2,$scancode,
 8933:                                                        'string_examcode',$uname,
 8934:                                                        $udom);
 8935:         }
 8936: 	$completedstudents{$uname}={'line'=>$line};
 8937:         if ($env{'form.verifyrecord'}) {
 8938:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8939:             if ($randompick) {
 8940:                 if ($total) {
 8941:                     $lastpos = $total*$scantron_config{'Qlength'};
 8942:                 }
 8943:             }
 8944: 
 8945:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8946:             chomp($studentdata);
 8947:             $studentdata =~ s/\r$//;
 8948:             my $studentrecord = '';
 8949:             my $counter = -1;
 8950:             foreach my $resource (@mapresources) {
 8951:                 my $ressymb = $resource->symb();
 8952:                 ($counter,my $recording) =
 8953:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8954:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8955:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8956:                                              $randompick,\%respnumlookup,\%startline);
 8957:                 $studentrecord .= $recording;
 8958:             }
 8959:             if ($studentrecord ne $studentdata) {
 8960:                 &Apache::lonxml::clear_problem_counter();
 8961:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8962:                                            \@mapresources,\%partids_by_symb,
 8963:                                            $bubbles_per_row,$randomorder,$randompick,
 8964:                                            \%respnumlookup,\%startline)
 8965:                     eq 'ssi_error') {
 8966:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8967:                     $r->print("</form>");
 8968:                     &ssi_print_error($r);
 8969:                     &Apache::lonnet::remove_lock($lock);
 8970:                     delete($completedstudents{$uname});
 8971:                     return '';
 8972:                 }
 8973:                 $counter = -1;
 8974:                 $studentrecord = '';
 8975:                 foreach my $resource (@mapresources) {
 8976:                     my $ressymb = $resource->symb();
 8977:                     ($counter,my $recording) =
 8978:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8979:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8980:                                                  \%scantron_config,\%lettdig,$numletts,
 8981:                                                  $randomorder,$randompick,\%respnumlookup,
 8982:                                                  \%startline);
 8983:                     $studentrecord .= $recording;
 8984:                 }
 8985:                 if ($studentrecord ne $studentdata) {
 8986:                     $r->print('<p><span class="LC_warning">');
 8987:                     if ($scancode eq '') {
 8988:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8989:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8990:                     } else {
 8991:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8992:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8993:                     }
 8994:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8995:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8996:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8997:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8998:                               &Apache::loncommon::start_data_table_row().
 8999:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9000:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9001:                               &Apache::loncommon::end_data_table_row().
 9002:                               &Apache::loncommon::start_data_table_row().
 9003:                               '<td>'.&mt('Stored submissions').'</td>'.
 9004:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9005:                               &Apache::loncommon::end_data_table_row().
 9006:                               &Apache::loncommon::end_data_table().'</p>');
 9007:                 } else {
 9008:                     $r->print('<br /><span class="LC_warning">'.
 9009:                              &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 />'.
 9010:                              &mt("As a consequence, this user's submission history records two tries.").
 9011:                                  '</span><br />');
 9012:                 }
 9013:             }
 9014:         }
 9015:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9016:     } continue {
 9017: 	&Apache::lonxml::clear_problem_counter();
 9018: 	&Apache::lonnet::delenv('scantron.');
 9019:     }
 9020:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9021:     &Apache::lonnet::remove_lock($lock);
 9022: #    my $lasttime = &Time::HiRes::time()-$start;
 9023: #    $r->print("<p>took $lasttime</p>");
 9024: 
 9025:     $r->print("</form>");
 9026:     return '';
 9027: }
 9028: 
 9029: sub graders_resources_pass {
 9030:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9031:         $bubbles_per_row) = @_;
 9032:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9033:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9034:         foreach my $resource (@{$resources}) {
 9035:             my $ressymb = $resource->symb();
 9036:             my ($analysis,$parts) =
 9037:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9038:                                           $env{'user.name'},$env{'user.domain'},
 9039:                                           1,$bubbles_per_row);
 9040:             $grader_partids_by_symb->{$ressymb} = $parts;
 9041:             if (ref($analysis) eq 'HASH') {
 9042:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9043:                     $grader_randomlists_by_symb->{$ressymb} =
 9044:                         $analysis->{'parts_withrandomlist'};
 9045:                 }
 9046:             }
 9047:         }
 9048:     }
 9049:     return;
 9050: }
 9051: 
 9052: =pod
 9053: 
 9054: =item users_order
 9055: 
 9056:   Returns array of resources in current map, ordered based on either CODE,
 9057:   if this is a CODEd exam, or based on student's identity if this is a
 9058:   "NAMEd" exam.
 9059: 
 9060:   Should be used when randomorder and/or randompick applied when the 
 9061:   corresponding exam was printed, prior to students completing bubblesheets 
 9062:   for the version of the exam the student received.
 9063: 
 9064: =cut
 9065: 
 9066: sub users_order  {
 9067:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9068:     my @mapresources;
 9069:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9070:         return @mapresources;
 9071:     }
 9072:     if ($scancode) {
 9073:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9074:             @mapresources = @{$orderedforcode->{$scancode}};
 9075:         } else {
 9076:             $env{'form.CODE'} = $scancode;
 9077:             my $actual_seq =
 9078:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9079:                                                                $master_seq,
 9080:                                                                $user,$scancode,1);
 9081:             if (ref($actual_seq) eq 'ARRAY') {
 9082:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9083:                 if (ref($orderedforcode) eq 'HASH') {
 9084:                     if (@mapresources > 0) {
 9085:                         $orderedforcode->{$scancode} = \@mapresources;
 9086:                     }
 9087:                 }
 9088:             }
 9089:             delete($env{'form.CODE'});
 9090:         }
 9091:     } else {
 9092:         my $actual_seq =
 9093:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9094:                                                            $master_seq,
 9095:                                                            $user,undef,1);
 9096:         if (ref($actual_seq) eq 'ARRAY') {
 9097:             @mapresources =
 9098:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9099:         }
 9100:     }
 9101:     return @mapresources;
 9102: }
 9103: 
 9104: sub grade_student_bubbles {
 9105:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9106:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9107:     my $uselookup = 0;
 9108:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9109:         (ref($startline) eq 'HASH')) {
 9110:         $uselookup = 1;
 9111:     }
 9112: 
 9113:     if (ref($resources) eq 'ARRAY') {
 9114:         my $count = 0;
 9115:         foreach my $resource (@{$resources}) {
 9116:             my $ressymb = $resource->symb();
 9117:             my %form = ('submitted'      => 'scantron',
 9118:                         'grade_target'   => 'grade',
 9119:                         'grade_username' => $uname,
 9120:                         'grade_domain'   => $udom,
 9121:                         'grade_courseid' => $env{'request.course.id'},
 9122:                         'grade_symb'     => $ressymb,
 9123:                         'CODE'           => $scancode
 9124:                        );
 9125:             if ($bubbles_per_row ne '') {
 9126:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9127:             }
 9128:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9129:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9130:             }
 9131:             if (ref($parts) eq 'HASH') {
 9132:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9133:                     foreach my $part (@{$parts->{$ressymb}}) {
 9134:                         if ($uselookup) {
 9135:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9136:                         } else {
 9137:                             $form{'scantron_questnum_start.'.$part} =
 9138:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9139:                         }
 9140:                         $count++;
 9141:                     }
 9142:                 }
 9143:             }
 9144:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9145:             return 'ssi_error' if ($ssi_error);
 9146:             last if (&Apache::loncommon::connection_aborted($r));
 9147:         }
 9148:     }
 9149:     return;
 9150: }
 9151: 
 9152: sub scantron_upload_scantron_data {
 9153:     my ($r,$symb) = @_;
 9154:     my $dom = $env{'request.role.domain'};
 9155:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9156:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9157:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9158:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9159: 							  'domainid',
 9160: 							  'coursename',$dom);
 9161:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9162:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9163:     my $default_form_data=&defaultFormData($symb);
 9164:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9165:     &js_escape(\$nofile_alert);
 9166:     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.");
 9167:     &js_escape(\$nocourseid_alert);
 9168:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9169:     function checkUpload(formname) {
 9170: 	if (formname.upfile.value == "") {
 9171: 	    alert("'.$nofile_alert.'");
 9172: 	    return false;
 9173: 	}
 9174:         if (formname.courseid.value == "") {
 9175:             alert("'.$nocourseid_alert.'");
 9176:             return false;
 9177:         }
 9178: 	formname.submit();
 9179:     }
 9180: 
 9181:     function ToSyllabus() {
 9182:         var cdom = '."'$dom'".';
 9183:         var cnum = document.rules.courseid.value;
 9184:         if (cdom == "" || cdom == null) {
 9185:             return;
 9186:         }
 9187:         if (cnum == "" || cnum == null) {
 9188:            return;
 9189:         }
 9190:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9191:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9192:         return;
 9193:     }
 9194: 
 9195:     '.$formatjs.'
 9196: '));
 9197:     $r->print('
 9198: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9199: 
 9200: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9201: '.$default_form_data.
 9202:   &Apache::lonhtmlcommon::start_pick_box().
 9203:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9204:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9205:   &Apache::lonhtmlcommon::row_closure().
 9206:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9207:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9208:   &Apache::lonhtmlcommon::row_closure().
 9209:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9210:   '<input name="domainid" type="hidden" />'.$domdesc.
 9211:   &Apache::lonhtmlcommon::row_closure());
 9212:     if ($formatoptions) {
 9213:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9214:                   &Apache::lonhtmlcommon::row_closure());
 9215:     }
 9216:     $r->print(
 9217:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9218:   '<input type="file" name="upfile" size="50" />'.
 9219:   &Apache::lonhtmlcommon::row_closure(1).
 9220:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9221: 
 9222: <input name="command" value="scantronupload_save" type="hidden" />
 9223: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9224: </form>
 9225: ');
 9226:     return '';
 9227: }
 9228: 
 9229: sub scantron_upload_dataformat {
 9230:     my ($dom) = @_;
 9231:     my ($formatoptions,$formattitle,$formatjs);
 9232:     $formatjs = <<'END';
 9233: function toggleScantab(form) {
 9234:    return;
 9235: }
 9236: END
 9237:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9238:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9239:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9240:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9241:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9242:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9243:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9244:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9245:                             my ($onclick,$formatextra,$singleline);
 9246:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9247:                             my $count = 0;
 9248:                             foreach my $line (@lines) {
 9249:                                 next if ($line =~ /^#/);
 9250:                                 $singleline = $line;
 9251:                                 $count ++;
 9252:                             }
 9253:                             if ($count > 1) {
 9254:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9255:                                                '<span class="LC_nobreak">'.
 9256:                                                &mt('Bubblesheet type').':&nbsp;'.
 9257:                                                &scantron_scantab().'</span></div>';
 9258:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9259:                                 $formatjs = <<"END";
 9260: function toggleScantab(form) {
 9261:     var divid = 'bubbletype';
 9262:     if (document.getElementById(divid)) {
 9263:         var radioname = 'fileformat';
 9264:         var num = form.elements[radioname].length;
 9265:         if (num) {
 9266:             for (var i=0; i<num; i++) {
 9267:                 if (form.elements[radioname][i].checked) {
 9268:                     var chosen = form.elements[radioname][i].value;
 9269:                     if (chosen == 'dat') {
 9270:                         document.getElementById(divid).style.display = 'none';
 9271:                     } else if (chosen == 'csv') {
 9272:                         document.getElementById(divid).style.display = 'block';
 9273:                     }
 9274:                 }
 9275:             }
 9276:         }
 9277:     }
 9278:     return;
 9279: }
 9280: 
 9281: END
 9282:                             } elsif ($count == 1) {
 9283:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9284:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9285:                             }
 9286:                             $formattitle = &mt('File format');
 9287:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9288:                                              &mt('Plain Text (no delimiters)').
 9289:                                              '</label>'.('&nbsp;'x2).
 9290:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9291:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9292:                         }
 9293:                     }
 9294:                 }
 9295:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9296:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9297:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9298:                         $formattitle = &mt('Bubblesheet type');
 9299:                         $formatoptions = &scantron_scantab();
 9300:                     }
 9301:                 }
 9302:             }
 9303:         }
 9304:     }
 9305:     return ($formatoptions,$formattitle,$formatjs);
 9306: }
 9307: 
 9308: sub scantron_upload_scantron_data_save {
 9309:     my ($r,$symb) = @_;
 9310:     my $doanotherupload=
 9311: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9312: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9313: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9314: 	'</form>'."\n";
 9315:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9316: 	!&Apache::lonnet::allowed('usc',
 9317: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9318: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9319:         unless ($symb) {
 9320: 	    $r->print($doanotherupload);
 9321: 	}
 9322: 	return '';
 9323:     }
 9324:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9325:     my $uploadedfile;
 9326:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9327:     if (length($env{'form.upfile'}) < 2) {
 9328:         $r->print(
 9329:             &Apache::lonhtmlcommon::confirm_success(
 9330:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9331:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9332:     } else {
 9333:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9334:         my $parser;
 9335:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9336:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9337:                 my $is_csv;
 9338:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9339:                 if (@possibles > 1) {
 9340:                     if ($env{'form.fileformat'} eq 'csv') {
 9341:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9342:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9343:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9344:                                     $is_csv = 1;
 9345:                                 }
 9346:                             }
 9347:                         }
 9348:                     }
 9349:                 } elsif (@possibles == 1) {
 9350:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9351:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9352:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9353:                                 $is_csv = 1;
 9354:                             }
 9355:                         }
 9356:                     }
 9357:                 }
 9358:                 if ($is_csv) {
 9359:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9360:                 }
 9361:             }
 9362:         }
 9363:         my $result =
 9364:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9365:                                             $env{'form.courseid'},$env{'form.domainid'});
 9366: 	if ($result =~ m{^/uploaded/}) {
 9367:             $r->print(
 9368:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9369:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9370:                         (length($env{'form.upfile'})-1),
 9371:                         '<span class="LC_filename">'.$result.'</span>'));
 9372:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9373:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9374:                                                        $env{'form.courseid'},$uploadedfile));
 9375: 	} else {
 9376:             $r->print(
 9377:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9378:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9379:                           $result,
 9380: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9381: 	}
 9382:     }
 9383:     if ($symb) {
 9384: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9385:     } else {
 9386: 	$r->print($doanotherupload);
 9387:     }
 9388:     return '';
 9389: }
 9390: 
 9391: sub validate_uploaded_scantron_file {
 9392:     my ($cdom,$cname,$fname) = @_;
 9393:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9394:     my @lines;
 9395:     if ($scanlines ne '-1') {
 9396:         @lines=split("\n",$scanlines,-1);
 9397:     }
 9398:     my $output;
 9399:     if (@lines) {
 9400:         my (%counts,$max_match_format);
 9401:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9402:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9403:         my %idmap = &username_to_idmap($classlist);
 9404:         foreach my $key (keys(%idmap)) {
 9405:             my $lckey = lc($key);
 9406:             $idmap{$lckey} = $idmap{$key};
 9407:         }
 9408:         my %unique_formats;
 9409:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9410:         foreach my $line (@formatlines) {
 9411:             chomp($line);
 9412:             my @config = split(/:/,$line);
 9413:             my $idstart = $config[5];
 9414:             my $idlength = $config[6];
 9415:             if (($idstart ne '') && ($idlength > 0)) {
 9416:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9417:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9418:                 } else {
 9419:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9420:                 }
 9421:             }
 9422:         }
 9423:         foreach my $key (keys(%unique_formats)) {
 9424:             my ($idstart,$idlength) = split(':',$key);
 9425:             %{$counts{$key}} = (
 9426:                                'found'   => 0,
 9427:                                'total'   => 0,
 9428:                               );
 9429:             foreach my $line (@lines) {
 9430:                 next if ($line =~ /^#/);
 9431:                 next if ($line =~ /^[\s\cz]*$/);
 9432:                 my $id = substr($line,$idstart-1,$idlength);
 9433:                 $id = lc($id);
 9434:                 if (exists($idmap{$id})) {
 9435:                     $counts{$key}{'found'} ++;
 9436:                 }
 9437:                 $counts{$key}{'total'} ++;
 9438:             }
 9439:             if ($counts{$key}{'total'}) {
 9440:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9441:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9442:                     $max_match_pct = $percent_match;
 9443:                     $max_match_format = $key;
 9444:                     $found_match_count = $counts{$key}{'found'};
 9445:                     $max_match_count = $counts{$key}{'total'};
 9446:                 }
 9447:             }
 9448:         }
 9449:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9450:             my $format_descs;
 9451:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9452:             for (my $i=0; $i<$numwithformat; $i++) {
 9453:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9454:                 if ($i<$numwithformat-2) {
 9455:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9456:                 } elsif ($i==$numwithformat-2) {
 9457:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9458:                 } elsif ($i==$numwithformat-1) {
 9459:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9460:                 }
 9461:             }
 9462:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9463:             $output .= '<br />';
 9464:             if ($found_match_count == $max_match_count) {
 9465:                 # 100% matching entries
 9466:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9467:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9468:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9469:                 &mt('Comparison of student IDs in the uploaded file with'.
 9470:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9471:                     ' in the file (for the format defined for [_3]).',
 9472:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9473:             } else {
 9474:                 # Not all entries matching? -> Show warning and additional info
 9475:                 $output .=
 9476:                     &Apache::lonhtmlcommon::confirm_success(
 9477:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9478:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9479:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9480:                     &mt('Comparison of student IDs in the uploaded file with'.
 9481:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9482:                         ' in the file (for the format defined for [_3]).',
 9483:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9484:                     '<p class="LC_info">'.
 9485:                     &mt('A low percentage of matches results from one of the following:').
 9486:                     '</p><ul>'.
 9487:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9488:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9489:                                '<i>'.$cdom.'</i>').'</li>'.
 9490:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9491:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9492:                     '</ul>';
 9493:             }
 9494:         }
 9495:     } else {
 9496:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9497:     }
 9498:     return $output;
 9499: }
 9500: 
 9501: sub valid_file {
 9502:     my ($requested_file)=@_;
 9503:     foreach my $filename (sort(&scantron_filenames())) {
 9504: 	if ($requested_file eq $filename) { return 1; }
 9505:     }
 9506:     return 0;
 9507: }
 9508: 
 9509: sub scantron_download_scantron_data {
 9510:     my ($r,$symb) = @_;
 9511:     my $default_form_data=&defaultFormData($symb);
 9512:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9513:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9514:     my $file=$env{'form.scantron_selectfile'};
 9515:     if (! &valid_file($file)) {
 9516: 	$r->print('
 9517: 	<p>
 9518: 	    '.&mt('The requested filename was invalid.').'
 9519:         </p>
 9520: ');
 9521: 	return;
 9522:     }
 9523:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9524:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9525:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9526:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9527:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9528:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9529:     $r->print('
 9530:     <p>
 9531: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9532: 	      '<a href="'.$orig.'">','</a>').'
 9533:     </p>
 9534:     <p>
 9535: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9536: 	      '<a href="'.$corrected.'">','</a>').'
 9537:     </p>
 9538:     <p>
 9539: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9540: 	      '<a href="'.$skipped.'">','</a>').'
 9541:     </p>
 9542: ');
 9543:     return '';
 9544: }
 9545: 
 9546: sub checkscantron_results {
 9547:     my ($r,$symb) = @_;
 9548:     if (!$symb) {return '';}
 9549:     my $cid = $env{'request.course.id'};
 9550:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9551:     my $numletts = scalar(keys(%lettdig));
 9552:     my $cnum = $env{'course.'.$cid.'.num'};
 9553:     my $cdom = $env{'course.'.$cid.'.domain'};
 9554:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9555:     my %record;
 9556:     my %scantron_config =
 9557:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9558:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9559:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9560:     my $classlist=&Apache::loncoursedata::get_classlist();
 9561:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9562:     my $navmap=Apache::lonnavmaps::navmap->new();
 9563:     unless (ref($navmap)) {
 9564:         $r->print(&navmap_errormsg());
 9565:         return '';
 9566:     }
 9567:     my $map=$navmap->getResourceByUrl($sequence);
 9568:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9569:         %grader_randomlists_by_symb,%orderedforcode);
 9570:     if (ref($map)) {
 9571:         $randomorder=$map->randomorder();
 9572:         $randompick=$map->randompick();
 9573:     }
 9574:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9575:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9576:     if ($nav_error) {
 9577:         $r->print(&navmap_errormsg());
 9578:         return '';
 9579:     }
 9580:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9581:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9582:     my ($uname,$udom);
 9583:     my (%scandata,%lastname,%bylast);
 9584:     $r->print('
 9585: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9586: 
 9587:     my @delayqueue;
 9588:     my %completedstudents;
 9589: 
 9590:     my $count=&get_todo_count($scanlines,$scan_data);
 9591:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9592:     my ($username,$domain,$started);
 9593:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9594:     if ($nav_error) {
 9595:         $r->print(&navmap_errormsg());
 9596:         return '';
 9597:     }
 9598: 
 9599:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9600:                                           'Processing first student');
 9601:     my $start=&Time::HiRes::time();
 9602:     my $i=-1;
 9603: 
 9604:     while ($i<$scanlines->{'count'}) {
 9605:         ($username,$domain,$uname)=('','','');
 9606:         $i++;
 9607:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9608:         if ($line=~/^[\s\cz]*$/) { next; }
 9609:         if ($started) {
 9610:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9611:                                                      'last student');
 9612:         }
 9613:         $started=1;
 9614:         my $scan_record=
 9615:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9616:                                                      $scan_data);
 9617:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9618:                                               \%idmap,$i)) {
 9619:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9620:                                 'Unable to find a student that matches',1);
 9621:             next;
 9622:         }
 9623:         if (exists $completedstudents{$uname}) {
 9624:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9625:                                 'Student '.$uname.' has multiple sheets',2);
 9626:             next;
 9627:         }
 9628:         my $pid = $scan_record->{'scantron.ID'};
 9629:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9630:         push(@{$bylast{$lastname{$pid}}},$pid);
 9631:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9632:         my $user = $uname.':'.$usec;
 9633:         ($username,$domain)=split(/:/,$uname);
 9634: 
 9635:         my $scancode;
 9636:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9637:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9638:             $scancode = $scan_record->{'scantron.CODE'};
 9639:         } else {
 9640:             $scancode = '';
 9641:         }
 9642: 
 9643:         my @mapresources = @resources;
 9644:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9645:         my %respnumlookup=();
 9646:         my %startline=();
 9647:         if ($randomorder || $randompick) {
 9648:             @mapresources =
 9649:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9650:                              \%orderedforcode);
 9651:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9652:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9653:                                              \%grader_partids_by_symb,\%orderedforcode,
 9654:                                              \%respnumlookup,\%startline);
 9655:             if ($randompick && $total) {
 9656:                 $lastpos = $total*$scantron_config{'Qlength'};
 9657:             }
 9658:         }
 9659:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9660:         chomp($scandata{$pid});
 9661:         $scandata{$pid} =~ s/\r$//;
 9662: 
 9663:         my $counter = -1;
 9664:         foreach my $resource (@mapresources) {
 9665:             my $parts;
 9666:             my $ressymb = $resource->symb();
 9667:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9668:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9669:                 my $currcode;
 9670:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9671:                     $currcode = $scancode;
 9672:                 }
 9673:                 (my $analysis,$parts) =
 9674:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9675:                                               $username,$domain,undef,
 9676:                                               $bubbles_per_row,$currcode);
 9677:             } else {
 9678:                 $parts = $grader_partids_by_symb{$ressymb};
 9679:             }
 9680:             ($counter,my $recording) =
 9681:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9682:                                          $scandata{$pid},$parts,
 9683:                                          \%scantron_config,\%lettdig,$numletts,
 9684:                                          $randomorder,$randompick,
 9685:                                          \%respnumlookup,\%startline);
 9686:             $record{$pid} .= $recording;
 9687:         }
 9688:     }
 9689:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9690:     $r->print('<br />');
 9691:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9692:     $passed = 0;
 9693:     $failed = 0;
 9694:     $numstudents = 0;
 9695:     foreach my $last (sort(keys(%bylast))) {
 9696:         if (ref($bylast{$last}) eq 'ARRAY') {
 9697:             foreach my $pid (sort(@{$bylast{$last}})) {
 9698:                 my $showscandata = $scandata{$pid};
 9699:                 my $showrecord = $record{$pid};
 9700:                 $showscandata =~ s/\s/&nbsp;/g;
 9701:                 $showrecord =~ s/\s/&nbsp;/g;
 9702:                 if ($scandata{$pid} eq $record{$pid}) {
 9703:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9704:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9705: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9706: '</tr>'."\n".
 9707: '<tr class="'.$css_class.'">'."\n".
 9708: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9709:                     $passed ++;
 9710:                 } else {
 9711:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9712:                     $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".
 9713: '</tr>'."\n".
 9714: '<tr class="'.$css_class.'">'."\n".
 9715: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9716: '</tr>'."\n";
 9717:                     $failed ++;
 9718:                 }
 9719:                 $numstudents ++;
 9720:             }
 9721:         }
 9722:     }
 9723:     $r->print('<p>'.
 9724:               &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).',
 9725:                   '<b>',
 9726:                   $numstudents,
 9727:                   '</b>',
 9728:                   $env{'form.scantron_maxbubble'}).
 9729:               '</p>'
 9730:     );
 9731:     $r->print('<p>'
 9732:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9733:              .'<br />'
 9734:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9735:              .'</p>');
 9736:     if ($passed) {
 9737:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9738:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9739:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9740:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9741:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9742:                  $okstudents."\n".
 9743:                  &Apache::loncommon::end_data_table().'<br />');
 9744:     }
 9745:     if ($failed) {
 9746:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9747:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9748:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9749:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9750:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9751:                  $badstudents."\n".
 9752:                  &Apache::loncommon::end_data_table()).'<br />'.
 9753:                  &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.');  
 9754:     }
 9755:     $r->print('</form><br />');
 9756:     return;
 9757: }
 9758: 
 9759: sub verify_scantron_grading {
 9760:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9761:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9762:         $respnumlookup,$startline) = @_;
 9763:     my ($record,%expected,%startpos);
 9764:     return ($counter,$record) if (!ref($resource));
 9765:     return ($counter,$record) if (!$resource->is_problem());
 9766:     my $symb = $resource->symb();
 9767:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9768:     foreach my $part_id (@{$partids}) {
 9769:         $counter ++;
 9770:         $expected{$part_id} = 0;
 9771:         my $respnum = $counter;
 9772:         if ($randomorder || $randompick) {
 9773:             $respnum = $respnumlookup->{$counter};
 9774:             $startpos{$part_id} = $startline->{$counter} + 1;
 9775:         } else {
 9776:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9777:         }
 9778:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9779:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9780:             foreach my $item (@sub_lines) {
 9781:                 $expected{$part_id} += $item;
 9782:             }
 9783:         } else {
 9784:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9785:         }
 9786:     }
 9787:     if ($symb) {
 9788:         my %recorded;
 9789:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9790:         if ($returnhash{'version'}) {
 9791:             my %lasthash=();
 9792:             my $version;
 9793:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9794:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9795:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9796:                 }
 9797:             }
 9798:             foreach my $key (keys(%lasthash)) {
 9799:                 if ($key =~ /\.scantron$/) {
 9800:                     my $value = &unescape($lasthash{$key});
 9801:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9802:                     if ($value eq '') {
 9803:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9804:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9805:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9806:                             }
 9807:                         }
 9808:                     } else {
 9809:                         my @tocheck;
 9810:                         my @items = split(//,$value);
 9811:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9812:                             ($scantron_config->{'Qon'} eq 'number')) {
 9813:                             if (@items < $expected{$part_id}) {
 9814:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9815:                                 my @singles = split(//,$fragment);
 9816:                                 foreach my $pos (@singles) {
 9817:                                     if ($pos eq ' ') {
 9818:                                         push(@tocheck,$pos);
 9819:                                     } else {
 9820:                                         my $next = shift(@items);
 9821:                                         push(@tocheck,$next);
 9822:                                     }
 9823:                                 }
 9824:                             } else {
 9825:                                 @tocheck = @items;
 9826:                             }
 9827:                             foreach my $letter (@tocheck) {
 9828:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9829:                                     if ($letter !~ /^[A-J]$/) {
 9830:                                         $letter = $scantron_config->{'Qoff'};
 9831:                                     }
 9832:                                     $recorded{$part_id} .= $letter;
 9833:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9834:                                     my $digit;
 9835:                                     if ($letter !~ /^[A-J]$/) {
 9836:                                         $digit = $scantron_config->{'Qoff'};
 9837:                                     } else {
 9838:                                         $digit = $lettdig->{$letter};
 9839:                                     }
 9840:                                     $recorded{$part_id} .= $digit;
 9841:                                 }
 9842:                             }
 9843:                         } else {
 9844:                             @tocheck = @items;
 9845:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9846:                                 my $curr_sub = shift(@tocheck);
 9847:                                 my $digit;
 9848:                                 if ($curr_sub =~ /^[A-J]$/) {
 9849:                                     $digit = $lettdig->{$curr_sub}-1;
 9850:                                 }
 9851:                                 if ($curr_sub eq 'J') {
 9852:                                     $digit += scalar($numletts);
 9853:                                 }
 9854:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9855:                                     if ($j == $digit) {
 9856:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9857:                                     } else {
 9858:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9859:                                     }
 9860:                                 }
 9861:                             }
 9862:                         }
 9863:                     }
 9864:                 }
 9865:             }
 9866:         }
 9867:         foreach my $part_id (@{$partids}) {
 9868:             if ($recorded{$part_id} eq '') {
 9869:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9870:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9871:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9872:                     }
 9873:                 }
 9874:             }
 9875:             $record .= $recorded{$part_id};
 9876:         }
 9877:     }
 9878:     return ($counter,$record);
 9879: }
 9880: 
 9881: #-------- end of section for handling grading scantron forms -------
 9882: #
 9883: #-------------------------------------------------------------------
 9884: 
 9885: #-------------------------- Menu interface -------------------------
 9886: #
 9887: #--- Href with symb and command ---
 9888: 
 9889: sub href_symb_cmd {
 9890:     my ($symb,$cmd)=@_;
 9891:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9892: }
 9893: 
 9894: sub grading_menu {
 9895:     my ($request,$symb) = @_;
 9896:     if (!$symb) {return '';}
 9897: 
 9898:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9899:                   'command'=>'individual');
 9900: 
 9901:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9902: 
 9903:     $fields{'command'}='ungraded';
 9904:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9905: 
 9906:     $fields{'command'}='table';
 9907:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9908: 
 9909:     $fields{'command'}='all_for_one';
 9910:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9911: 
 9912:     $fields{'command'}='downloadfilesselect';
 9913:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9914:     
 9915:     $fields{'command'} = 'csvform';
 9916:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9917:     
 9918:     $fields{'command'} = 'processclicker';
 9919:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9920:     
 9921:     $fields{'command'} = 'scantron_selectphase';
 9922:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9923: 
 9924:     $fields{'command'} = 'initialverifyreceipt';
 9925:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9926: 
 9927:     my %permissions;
 9928:     if ($perm{'mgr'}) {
 9929:         $permissions{'either'} = 'F';
 9930:         $permissions{'mgr'} = 'F';
 9931:     }
 9932:     if ($perm{'vgr'}) {
 9933:         $permissions{'either'} = 'F';
 9934:         $permissions{'vgr'} = 'F';
 9935:     }
 9936: 
 9937:     my @menu = ({	categorytitle=>'Hand Grading',
 9938:             items =>[
 9939:                         {       linktext => 'Select individual students to grade',
 9940:                                 url => $url1a,
 9941:                                 permission => $permissions{'either'},
 9942:                                 icon => 'grade_students.png',
 9943:                                 linktitle => 'Grade current resource for a selection of students.'
 9944:                         },
 9945:                         {       linktext => 'Grade ungraded submissions',
 9946:                                 url => $url1b,
 9947:                                 permission => $permissions{'either'},
 9948:                                 icon => 'ungrade_sub.png',
 9949:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9950:                         },
 9951: 
 9952:                         {       linktext => 'Grading table',
 9953:                                 url => $url1c,
 9954:                                 permission => $permissions{'either'},
 9955:                                 icon => 'grading_table.png',
 9956:                                 linktitle => 'Grade current resource for all students.'
 9957:                         },
 9958:                         {       linktext => 'Grade page/folder for one student',
 9959:                                 url => $url1d,
 9960:                                 permission => $permissions{'either'},
 9961:                                 icon => 'grade_PageFolder.png',
 9962:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9963:                         },
 9964:                         {       linktext => 'Download submitted files',
 9965:                                 url => $url1e,
 9966:                                 permission => $permissions{'either'},
 9967:                                 icon => 'download_sub.png',
 9968:                                 linktitle => 'Download all files submitted by students.'
 9969:                         }]},
 9970:                          { categorytitle=>'Automated Grading',
 9971:                items =>[
 9972: 
 9973:                 	    {	linktext => 'Upload Scores',
 9974:                     		url => $url2,
 9975:                     		permission => $permissions{'mgr'},
 9976:                     		icon => 'uploadscores.png',
 9977:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9978:                 	    },
 9979:                 	    {	linktext => 'Process Clicker',
 9980:                     		url => $url3,
 9981:                     		permission => $permissions{'mgr'},
 9982:                     		icon => 'addClickerInfoFile.png',
 9983:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9984:                 	    },
 9985:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9986:                     		url => $url4,
 9987:                     		permission => $permissions{'mgr'},
 9988:                     		icon => 'bubblesheet.png',
 9989:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9990:                 	    },
 9991:                             {   linktext => 'Verify Receipt Number',
 9992:                                 url => $url5,
 9993:                                 permission => $permissions{'either'},
 9994:                                 icon => 'receipt_number.png',
 9995:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9996:                             }
 9997: 
 9998:                     ]
 9999:             });
10000: 
10001:     # Create the menu
10002:     my $Str;
10003:     $Str .= '<form method="post" action="" name="gradingMenu">';
10004:     $Str .= '<input type="hidden" name="command" value="" />'.
10005:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10006: 
10007:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10008:     return $Str;    
10009: }
10010: 
10011: sub ungraded {
10012:     my ($request)=@_;
10013:     &submit_options($request);
10014: }
10015: 
10016: sub submit_options_sequence {
10017:     my ($request,$symb) = @_;
10018:     if (!$symb) {return '';}
10019:     &commonJSfunctions($request);
10020:     my $result;
10021: 
10022:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10023:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10024:     $result.=&selectfield(0).
10025:             '<input type="hidden" name="command" value="pickStudentPage" />
10026:             <div>
10027:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10028:             </div>
10029:         </div>
10030:   </form>';
10031:     return $result;
10032: }
10033: 
10034: sub submit_options_table {
10035:     my ($request,$symb) = @_;
10036:     if (!$symb) {return '';}
10037:     &commonJSfunctions($request);
10038:     my $result;
10039: 
10040:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10041:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10042: 
10043:     $result.=&selectfield(1).
10044:             '<input type="hidden" name="command" value="viewgrades" />
10045:             <div>
10046:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10047:             </div>
10048:         </div>
10049:   </form>';
10050:     return $result;
10051: }
10052: 
10053: sub submit_options_download {
10054:     my ($request,$symb) = @_;
10055:     if (!$symb) {return '';}
10056: 
10057:     my $res_error;
10058:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10059:         &response_type($symb,\$res_error);
10060:     if ($res_error) {
10061:         $request->print(&mt('An error occurred retrieving response types'));
10062:         return;
10063:     }
10064:     unless ($numessay) {
10065:         $request->print(&mt('No essayresponse items found'));
10066:         return;
10067:     }
10068:     my $table;
10069:     if (ref($partlist) eq 'ARRAY') {
10070:         if (scalar(@$partlist) > 1 ) {
10071:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10072:         }
10073:     }
10074: 
10075:     &commonJSfunctions($request);
10076: 
10077:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10078:         $table."\n".
10079:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10080:     $result.='
10081: <h2>
10082:   '.&mt('Select Students for whom to Download Submitted Files').'
10083: </h2>'.&selectfield(1).'
10084:                 <input type="hidden" name="command" value="downloadfileslink" />
10085:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10086:             </div>
10087:           </div>
10088: 
10089: 
10090:   </form>';
10091:     return $result;
10092: }
10093: 
10094: #--- Displays the submissions first page -------
10095: sub submit_options {
10096:     my ($request,$symb) = @_;
10097:     if (!$symb) {return '';}
10098: 
10099:     &commonJSfunctions($request);
10100:     my $result;
10101: 
10102:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10103: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10104:     $result.=&selectfield(1).'
10105:                 <input type="hidden" name="command" value="submission" />
10106:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10107:             </div>
10108:           </div>
10109:   </form>';
10110:     return $result;
10111: }
10112: 
10113: sub selectfield {
10114:    my ($full)=@_;
10115:    my %options =
10116:        (&substatus_options,
10117:         'select_form_order' => ['yes','queued','graded','incorrect','all']);
10118: 
10119:   #
10120:   # PrepareClasslist() needs to be called to avoid getting a sections list
10121:   # for a different course from the @Sections global in lonstatistics.pm,
10122:   # populated by an earlier request.
10123:   #
10124:    &Apache::lonstatistics::PrepareClasslist();
10125: 
10126:    my $result='<div class="LC_columnSection">
10127: 
10128:     <fieldset>
10129:       <legend>
10130:        '.&mt('Sections').'
10131:       </legend>
10132:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10133:     </fieldset>
10134: 
10135:     <fieldset>
10136:       <legend>
10137:         '.&mt('Groups').'
10138:       </legend>
10139:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10140:     </fieldset>
10141:  
10142:     <fieldset>
10143:       <legend>
10144:         '.&mt('Access Status').'
10145:       </legend>
10146:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10147:     </fieldset>';
10148:     if ($full) {
10149:         $result.='
10150:     <fieldset>
10151:       <legend>
10152:         '.&mt('Submission Status').'
10153:       </legend>'.
10154:        &Apache::loncommon::select_form('all','submitonly',\%options).
10155:    '</fieldset>';
10156:     }
10157:     $result.='</div><br />';
10158:     return $result;
10159: }
10160: 
10161: sub substatus_options {
10162:     return &Apache::lonlocal::texthash(
10163:                                       'yes'       => 'with submissions',
10164:                                       'queued'    => 'in grading queue',
10165:                                       'graded'    => 'with ungraded submissions',
10166:                                       'incorrect' => 'with incorrect submissions',
10167:                                       'all'       => 'with any status',
10168:                                       );
10169: }
10170: 
10171: sub transtatus_options {
10172:     return &Apache::lonlocal::texthash(
10173:                                        'yes'       => 'with score transactions',
10174:                                        'incorrect' => 'with less than full credit',
10175:                                        'all'       => 'with any status',
10176:                                       );
10177: }
10178: 
10179: sub reset_perm {
10180:     undef(%perm);
10181: }
10182: 
10183: sub init_perm {
10184:     &reset_perm();
10185:     foreach my $test_perm ('vgr','mgr','opa') {
10186: 
10187: 	my $scope = $env{'request.course.id'};
10188: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10189: 
10190: 	    $scope .= '/'.$env{'request.course.sec'};
10191: 	    if ( $perm{$test_perm}=
10192: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10193: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10194: 	    } else {
10195: 		delete($perm{$test_perm});
10196: 	    }
10197: 	}
10198:     }
10199: }
10200: 
10201: sub init_old_essays {
10202:     my ($symb,$apath,$adom,$aname) = @_;
10203:     if ($symb ne '') {
10204:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10205:         if (keys(%essays) > 0) {
10206:             $old_essays{$symb} = \%essays;
10207:         }
10208:     }
10209:     return;
10210: }
10211: 
10212: sub reset_old_essays {
10213:     undef(%old_essays);
10214: }
10215: 
10216: sub gather_clicker_ids {
10217:     my %clicker_ids;
10218: 
10219:     my $classlist = &Apache::loncoursedata::get_classlist();
10220: 
10221:     # Set up a couple variables.
10222:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10223:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10224:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10225: 
10226:     foreach my $student (keys(%$classlist)) {
10227:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10228:         my $username = $classlist->{$student}->[$username_idx];
10229:         my $domain   = $classlist->{$student}->[$domain_idx];
10230:         my $clickers =
10231: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10232:         foreach my $id (split(/\,/,$clickers)) {
10233:             $id=~s/^[\#0]+//;
10234:             $id=~s/[\-\:]//g;
10235:             if (exists($clicker_ids{$id})) {
10236: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10237:             } else {
10238: 		$clicker_ids{$id}=$username.':'.$domain;
10239:             }
10240:         }
10241:     }
10242:     return %clicker_ids;
10243: }
10244: 
10245: sub gather_adv_clicker_ids {
10246:     my %clicker_ids;
10247:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10248:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10249:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10250:     foreach my $element (sort(keys(%coursepersonnel))) {
10251:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10252:             my ($puname,$pudom)=split(/\:/,$person);
10253:             my $clickers =
10254: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10255:             foreach my $id (split(/\,/,$clickers)) {
10256: 		$id=~s/^[\#0]+//;
10257:                 $id=~s/[\-\:]//g;
10258: 		if (exists($clicker_ids{$id})) {
10259: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10260: 		} else {
10261: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10262: 		}
10263:             }
10264:         }
10265:     }
10266:     return %clicker_ids;
10267: }
10268: 
10269: sub clicker_grading_parameters {
10270:     return ('gradingmechanism' => 'scalar',
10271:             'upfiletype' => 'scalar',
10272:             'specificid' => 'scalar',
10273:             'pcorrect' => 'scalar',
10274:             'pincorrect' => 'scalar');
10275: }
10276: 
10277: sub process_clicker {
10278:     my ($r,$symb)=@_;
10279:     if (!$symb) {return '';}
10280:     my $result=&checkforfile_js();
10281:     $result.=&Apache::loncommon::start_data_table().
10282:              &Apache::loncommon::start_data_table_header_row().
10283:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10284:              &Apache::loncommon::end_data_table_header_row().
10285:              &Apache::loncommon::start_data_table_row()."<td>\n";
10286: # Attempt to restore parameters from last session, set defaults if not present
10287:     my %Saveable_Parameters=&clicker_grading_parameters();
10288:     &Apache::loncommon::restore_course_settings('grades_clicker',
10289:                                                  \%Saveable_Parameters);
10290:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10291:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10292:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10293:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10294: 
10295:     my %checked;
10296:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10297:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10298:           $checked{$gradingmechanism}=' checked="checked"';
10299:        }
10300:     }
10301: 
10302:     my $upload=&mt("Evaluate File");
10303:     my $type=&mt("Type");
10304:     my $attendance=&mt("Award points just for participation");
10305:     my $personnel=&mt("Correctness determined from response by course personnel");
10306:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10307:     my $given=&mt("Correctness determined from given list of answers").' '.
10308:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10309:     my $pcorrect=&mt("Percentage points for correct solution");
10310:     my $pincorrect=&mt("Percentage points for incorrect solution");
10311:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10312:                                                    {'iclicker' => 'i>clicker',
10313:                                                     'interwrite' => 'interwrite PRS',
10314:                                                     'turning' => 'Turning Technologies'});
10315:     $symb = &Apache::lonenc::check_encrypt($symb);
10316:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10317: function sanitycheck() {
10318: // Accept only integer percentages
10319:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10320:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10321: // Find out grading choice
10322:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10323:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10324:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10325:       }
10326:    }
10327: // By default, new choice equals user selection
10328:    newgradingchoice=gradingchoice;
10329: // Not good to give more points for false answers than correct ones
10330:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10331:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10332:    }
10333: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10334:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10335:       document.forms.gradesupload.pcorrect.value=100;
10336:       document.forms.gradesupload.pincorrect.value=100;
10337:    }
10338: // If the values are different, cannot be attendance only
10339:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10340:        (gradingchoice=='attendance')) {
10341:        newgradingchoice='personnel';
10342:    }
10343: // Change grading choice to new one
10344:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10345:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10346:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10347:       } else {
10348:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10349:       }
10350:    }
10351: // Remember the old state
10352:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10353: }
10354: ENDUPFORM
10355:     $result.= <<ENDUPFORM;
10356: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10357: <input type="hidden" name="symb" value="$symb" />
10358: <input type="hidden" name="command" value="processclickerfile" />
10359: <input type="file" name="upfile" size="50" />
10360: <br /><label>$type: $selectform</label>
10361: ENDUPFORM
10362:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10363:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10364:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10365: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10366: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10367: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10368: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10369: <br />&nbsp;&nbsp;&nbsp;
10370: <input type="text" name="givenanswer" size="50" />
10371: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10372: ENDGRADINGFORM
10373:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10374:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10375:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10376: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10377: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10378: </form>
10379: ENDPERCFORM
10380:     $result.='</td>'.
10381:              &Apache::loncommon::end_data_table_row().
10382:              &Apache::loncommon::end_data_table();
10383:     return $result;
10384: }
10385: 
10386: sub process_clicker_file {
10387:     my ($r,$symb) = @_;
10388:     if (!$symb) {return '';}
10389: 
10390:     my %Saveable_Parameters=&clicker_grading_parameters();
10391:     &Apache::loncommon::store_course_settings('grades_clicker',
10392:                                               \%Saveable_Parameters);
10393:     my $result='';
10394:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10395: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10396: 	return $result;
10397:     }
10398:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10399:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10400:         return $result;
10401:     }
10402:     my $foundgiven=0;
10403:     if ($env{'form.gradingmechanism'} eq 'given') {
10404:         $env{'form.givenanswer'}=~s/^\s*//gs;
10405:         $env{'form.givenanswer'}=~s/\s*$//gs;
10406:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10407:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10408:         my @answers=split(/\,/,$env{'form.givenanswer'});
10409:         $foundgiven=$#answers+1;
10410:     }
10411:     my %clicker_ids=&gather_clicker_ids();
10412:     my %correct_ids;
10413:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10414: 	%correct_ids=&gather_adv_clicker_ids();
10415:     }
10416:     if ($env{'form.gradingmechanism'} eq 'specific') {
10417: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10418: 	   $correct_id=~tr/a-z/A-Z/;
10419: 	   $correct_id=~s/\s//gs;
10420: 	   $correct_id=~s/^[\#0]+//;
10421:            $correct_id=~s/[\-\:]//g;
10422:            if ($correct_id) {
10423: 	      $correct_ids{$correct_id}='specified';
10424:            }
10425:         }
10426:     }
10427:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10428: 	$result.=&mt('Score based on attendance only');
10429:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10430:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10431:     } else {
10432: 	my $number=0;
10433: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10434: 	foreach my $id (sort(keys(%correct_ids))) {
10435: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10436: 	    if ($correct_ids{$id} eq 'specified') {
10437: 		$result.=&mt('specified');
10438: 	    } else {
10439: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10440: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10441: 	    }
10442: 	    $number++;
10443: 	}
10444:         $result.="</p>\n";
10445:         if ($number==0) {
10446:             $result .=
10447:                  &Apache::lonhtmlcommon::confirm_success(
10448:                      &mt('No IDs found to determine correct answer'),1);
10449:             return $result;
10450:         }
10451:     }
10452:     if (length($env{'form.upfile'}) < 2) {
10453:         $result .=
10454:             &Apache::lonhtmlcommon::confirm_success(
10455:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10456:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10457:         return $result;
10458:     }
10459:     my $mimetype;
10460:     if ($env{'form.upfiletype'} eq 'iclicker') {
10461:         my $mm = new File::MMagic;
10462:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10463:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10464:             $result.= '<p>'.
10465:                 &Apache::lonhtmlcommon::confirm_success(
10466:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10467:             return $result;
10468:         }
10469:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10470:         $result .= '<p>'.
10471:             &Apache::lonhtmlcommon::confirm_success(
10472:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10473:         return $result;
10474:     }
10475: 
10476: # Were able to get all the info needed, now analyze the file
10477: 
10478:     $result.=&Apache::loncommon::studentbrowser_javascript();
10479:     $symb = &Apache::lonenc::check_encrypt($symb);
10480:     $result.=&Apache::loncommon::start_data_table().
10481:              &Apache::loncommon::start_data_table_header_row().
10482:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10483:              &Apache::loncommon::end_data_table_header_row().
10484:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10485: <td>
10486: <form method="post" action="/adm/grades" name="clickeranalysis">
10487: <input type="hidden" name="symb" value="$symb" />
10488: <input type="hidden" name="command" value="assignclickergrades" />
10489: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10490: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10491: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10492: ENDHEADER
10493:     if ($env{'form.gradingmechanism'} eq 'given') {
10494:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10495:     } 
10496:     my %responses;
10497:     my @questiontitles;
10498:     my $errormsg='';
10499:     my $number=0;
10500:     if ($env{'form.upfiletype'} eq 'iclicker') {
10501:         if ($mimetype eq 'text/plain') {
10502:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10503:         } elsif ($mimetype eq 'text/html') {
10504:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10505:         }
10506:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10507:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10508:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10509:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10510:     }
10511:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10512:              '<input type="hidden" name="number" value="'.$number.'" />'.
10513:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10514:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10515:              '<br />';
10516:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10517:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10518:        return $result;
10519:     } 
10520: # Remember Question Titles
10521: # FIXME: Possibly need delimiter other than ":"
10522:     for (my $i=0;$i<$number;$i++) {
10523:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10524:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10525:     }
10526:     my $correct_count=0;
10527:     my $student_count=0;
10528:     my $unknown_count=0;
10529: # Match answers with usernames
10530: # FIXME: Possibly need delimiter other than ":"
10531:     foreach my $id (keys(%responses)) {
10532:        if ($correct_ids{$id}) {
10533:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10534:           $correct_count++;
10535:        } elsif ($clicker_ids{$id}) {
10536:           if ($clicker_ids{$id}=~/\,/) {
10537: # More than one user with the same clicker!
10538:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10539:                            &Apache::loncommon::start_data_table_row()."<td>".
10540:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10541:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10542:                            "<select name='multi".$id."'>";
10543:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10544:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10545:              }
10546:              $result.='</select>';
10547:              $unknown_count++;
10548:           } else {
10549: # Good: found one and only one user with the right clicker
10550:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10551:              $student_count++;
10552:           }
10553:        } else {
10554:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10555:                            &Apache::loncommon::start_data_table_row()."<td>".
10556:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10557:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10558:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10559:                    "\n".&mt("Domain").": ".
10560:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10561:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10562:           $unknown_count++;
10563:        }
10564:     }
10565:     $result.='<hr />'.
10566:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10567:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10568:        if ($correct_count==0) {
10569:           $errormsg.="Found no correct answers for grading!";
10570:        } elsif ($correct_count>1) {
10571:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10572:        }
10573:     }
10574:     if ($number<1) {
10575:        $errormsg.="Found no questions.";
10576:     }
10577:     if ($errormsg) {
10578:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10579:     } else {
10580:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10581:     }
10582:     $result.='</form></td>'.
10583:              &Apache::loncommon::end_data_table_row().
10584:              &Apache::loncommon::end_data_table();
10585:     return $result;
10586: }
10587: 
10588: sub iclicker_eval {
10589:     my ($questiontitles,$responses)=@_;
10590:     my $number=0;
10591:     my $errormsg='';
10592:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10593:         my %components=&Apache::loncommon::record_sep($line);
10594:         my @entries=map {$components{$_}} (sort(keys(%components)));
10595: 	if ($entries[0] eq 'Question') {
10596: 	    for (my $i=3;$i<$#entries;$i+=6) {
10597: 		$$questiontitles[$number]=$entries[$i];
10598: 		$number++;
10599: 	    }
10600: 	}
10601: 	if ($entries[0]=~/^\#/) {
10602: 	    my $id=$entries[0];
10603: 	    my @idresponses;
10604: 	    $id=~s/^[\#0]+//;
10605: 	    for (my $i=0;$i<$number;$i++) {
10606: 		my $idx=3+$i*6;
10607:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10608: 		push(@idresponses,$entries[$idx]);
10609: 	    }
10610: 	    $$responses{$id}=join(',',@idresponses);
10611: 	}
10612:     }
10613:     return ($errormsg,$number);
10614: }
10615: 
10616: sub iclickerxml_eval {
10617:     my ($questiontitles,$responses)=@_;
10618:     my $number=0;
10619:     my $errormsg='';
10620:     my @state;
10621:     my %respbyid;
10622:     my $p = HTML::Parser->new
10623:     (
10624:         xml_mode => 1,
10625:         start_h =>
10626:             [sub {
10627:                  my ($tagname,$attr) = @_;
10628:                  push(@state,$tagname);
10629:                  if ("@state" eq "ssn p") {
10630:                      my $title = $attr->{qn};
10631:                      $title =~ s/(^\s+|\s+$)//g;
10632:                      $questiontitles->[$number]=$title;
10633:                  } elsif ("@state" eq "ssn p v") {
10634:                      my $id = $attr->{id};
10635:                      my $entry = $attr->{ans};
10636:                      $id=~s/^[\#0]+//;
10637:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10638:                      $respbyid{$id}[$number] = $entry;
10639:                  }
10640:             }, "tagname, attr"],
10641:          end_h =>
10642:                [sub {
10643:                    my ($tagname) = @_;
10644:                    if ("@state" eq "ssn p") {
10645:                        $number++;
10646:                    }
10647:                    pop(@state);
10648:                 }, "tagname"],
10649:     );
10650: 
10651:     $p->parse($env{'form.upfile'});
10652:     $p->eof;
10653:     foreach my $id (keys(%respbyid)) {
10654:         $responses->{$id}=join(',',@{$respbyid{$id}});
10655:     }
10656:     return ($errormsg,$number);
10657: }
10658: 
10659: sub interwrite_eval {
10660:     my ($questiontitles,$responses)=@_;
10661:     my $number=0;
10662:     my $errormsg='';
10663:     my $skipline=1;
10664:     my $questionnumber=0;
10665:     my %idresponses=();
10666:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10667:         my %components=&Apache::loncommon::record_sep($line);
10668:         my @entries=map {$components{$_}} (sort(keys(%components)));
10669:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10670:         if ($entries[1] eq 'Response') { $skipline=1; }
10671:         next if $skipline;
10672:         if ($entries[0]!=$questionnumber) {
10673:            $questionnumber=$entries[0];
10674:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10675:            $number++;
10676:         }
10677:         my $id=$entries[4];
10678:         $id=~s/^[\#0]+//;
10679:         $id=~s/^v\d*\://i;
10680:         $id=~s/[\-\:]//g;
10681:         $idresponses{$id}[$number]=$entries[6];
10682:     }
10683:     foreach my $id (keys(%idresponses)) {
10684:        $$responses{$id}=join(',',@{$idresponses{$id}});
10685:        $$responses{$id}=~s/^\s*\,//;
10686:     }
10687:     return ($errormsg,$number);
10688: }
10689: 
10690: sub turning_eval {
10691:     my ($questiontitles,$responses)=@_;
10692:     my $number=0;
10693:     my $errormsg='';
10694:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10695:         my %components=&Apache::loncommon::record_sep($line);
10696:         my @entries=map {$components{$_}} (sort(keys(%components)));
10697:         if ($#entries>$number) { $number=$#entries; }
10698:         my $id=$entries[0];
10699:         my @idresponses;
10700:         $id=~s/^[\#0]+//;
10701:         unless ($id) { next; }
10702:         for (my $idx=1;$idx<=$#entries;$idx++) {
10703:             $entries[$idx]=~s/\,/\;/g;
10704:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10705:             push(@idresponses,$entries[$idx]);
10706:         }
10707:         $$responses{$id}=join(',',@idresponses);
10708:     }
10709:     for (my $i=1; $i<=$number; $i++) {
10710:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10711:     }
10712:     return ($errormsg,$number);
10713: }
10714: 
10715: sub assign_clicker_grades {
10716:     my ($r,$symb) = @_;
10717:     if (!$symb) {return '';}
10718: # See which part we are saving to
10719:     my $res_error;
10720:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10721:     if ($res_error) {
10722:         return &navmap_errormsg();
10723:     }
10724: # FIXME: This should probably look for the first handgradeable part
10725:     my $part=$$partlist[0];
10726: # Start screen output
10727:     my $result = &Apache::loncommon::start_data_table(). 
10728:                  &Apache::loncommon::start_data_table_header_row().
10729:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10730:                  &Apache::loncommon::end_data_table_header_row().
10731:                  &Apache::loncommon::start_data_table_row().'<td>';
10732: # Get correct result
10733: # FIXME: Possibly need delimiter other than ":"
10734:     my @correct=();
10735:     my $gradingmechanism=$env{'form.gradingmechanism'};
10736:     my $number=$env{'form.number'};
10737:     if ($gradingmechanism ne 'attendance') {
10738:        foreach my $key (keys(%env)) {
10739:           if ($key=~/^form\.correct\:/) {
10740:              my @input=split(/\,/,$env{$key});
10741:              for (my $i=0;$i<=$#input;$i++) {
10742:                  if (($correct[$i]) && ($input[$i]) &&
10743:                      ($correct[$i] ne $input[$i])) {
10744:                     $result.='<br /><span class="LC_warning">'.
10745:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10746:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10747:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10748:                     $correct[$i]=$input[$i];
10749:                  }
10750:              }
10751:           }
10752:        }
10753:        for (my $i=0;$i<$number;$i++) {
10754:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10755:              $result.='<br /><span class="LC_error">'.
10756:                       &mt('No correct result given for question "[_1]"!',
10757:                           $env{'form.question:'.$i}).'</span>';
10758:           }
10759:        }
10760:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10761:     }
10762: # Start grading
10763:     my $pcorrect=$env{'form.pcorrect'};
10764:     my $pincorrect=$env{'form.pincorrect'};
10765:     my $storecount=0;
10766:     my %users=();
10767:     foreach my $key (keys(%env)) {
10768:        my $user='';
10769:        if ($key=~/^form\.student\:(.*)$/) {
10770:           $user=$1;
10771:        }
10772:        if ($key=~/^form\.unknown\:(.*)$/) {
10773:           my $id=$1;
10774:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10775:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10776:           } elsif ($env{'form.multi'.$id}) {
10777:              $user=$env{'form.multi'.$id};
10778:           }
10779:        }
10780:        if ($user) {
10781:           if ($users{$user}) {
10782:              $result.='<br /><span class="LC_warning">'.
10783:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10784:                       '</span><br />';
10785:           }
10786:           $users{$user}=1;
10787:           my @answer=split(/\,/,$env{$key});
10788:           my $sum=0;
10789:           my $realnumber=$number;
10790:           for (my $i=0;$i<$number;$i++) {
10791:              if  ($correct[$i] eq '-') {
10792:                 $realnumber--;
10793:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10794:                 if ($gradingmechanism eq 'attendance') {
10795:                    $sum+=$pcorrect;
10796:                 } elsif ($correct[$i] eq '*') {
10797:                    $sum+=$pcorrect;
10798:                 } else {
10799: # We actually grade if correct or not
10800:                    my $increment=$pincorrect;
10801: # Special case: numerical answer "0"
10802:                    if ($correct[$i] eq '0') {
10803:                       if ($answer[$i]=~/^[0\.]+$/) {
10804:                          $increment=$pcorrect;
10805:                       }
10806: # General numerical answer, both evaluate to something non-zero
10807:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10808:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10809:                          $increment=$pcorrect;
10810:                       }
10811: # Must be just alphanumeric
10812:                    } elsif ($answer[$i] eq $correct[$i]) {
10813:                       $increment=$pcorrect;
10814:                    }
10815:                    $sum+=$increment;
10816:                 }
10817:              }
10818:           }
10819:           my $ave=$sum/(100*$realnumber);
10820: # Store
10821:           my ($username,$domain)=split(/\:/,$user);
10822:           my %grades=();
10823:           $grades{"resource.$part.solved"}='correct_by_override';
10824:           $grades{"resource.$part.awarded"}=$ave;
10825:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10826:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10827:                                                  $env{'request.course.id'},
10828:                                                  $domain,$username);
10829:           if ($returncode ne 'ok') {
10830:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10831:           } else {
10832:              $storecount++;
10833:           }
10834:        }
10835:     }
10836: # We are done
10837:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10838:              '</td>'.
10839:              &Apache::loncommon::end_data_table_row().
10840:              &Apache::loncommon::end_data_table();
10841:     return $result;
10842: }
10843: 
10844: sub navmap_errormsg {
10845:     return '<div class="LC_error">'.
10846:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10847:            &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>').
10848:            '</div>';
10849: }
10850: 
10851: sub startpage {
10852:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
10853:     my %args;
10854:     if ($onload) {
10855:          my %loaditems = (
10856:                         'onload' => $onload,
10857:                       );
10858:          $args{'add_entries'} = \%loaditems;
10859:     }
10860:     if ($nomenu) {
10861:         $args{'only_body'} = 1;
10862:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
10863:     } else {
10864:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10865:         $args{'bread_crumbs'} = $crumbs;
10866:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
10867:     }
10868:     unless ($nodisplayflag) {
10869:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
10870:     }
10871: }
10872: 
10873: sub select_problem {
10874:     my ($r)=@_;
10875:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10876:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
10877:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10878:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10879: }
10880: 
10881: sub handler {
10882:     my $request=$_[0];
10883:     &reset_caches();
10884:     if ($request->header_only) {
10885:         &Apache::loncommon::content_type($request,'text/html');
10886:         $request->send_http_header;
10887:         return OK;
10888:     }
10889:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10890: 
10891: # see what command we need to execute
10892:  
10893:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10894:     my $command=$commands[0];
10895: 
10896:     &init_perm();
10897:     if (!$env{'request.course.id'}) {
10898:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10899:                 ($command =~ /^scantronupload/)) {
10900:             # Not in a course.
10901:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10902:             return HTTP_NOT_ACCEPTABLE;
10903:         }
10904:     } elsif (!%perm) {
10905:         $request->internal_redirect('/adm/quickgrades');
10906:         return OK;
10907:     }
10908:     &Apache::loncommon::content_type($request,'text/html');
10909:     $request->send_http_header;
10910: 
10911:     if ($#commands > 0) {
10912: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10913:     }
10914: 
10915: # see what the symb is
10916: 
10917:     my $symb=$env{'form.symb'};
10918:     unless ($symb) {
10919:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10920:        $symb=&Apache::lonnet::symbread($url);
10921:     }
10922:     &Apache::lonenc::check_decrypt(\$symb);
10923: 
10924:     $ssi_error = 0;
10925:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10926: #
10927: # Not called from a resource, but inside a course
10928: #
10929:         &startpage($request,undef,[],1,1);
10930:         &select_problem($request);
10931:     } else {
10932:         if ($command eq 'submission' && $perm{'vgr'}) {
10933:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
10934:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10935:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10936:                     &choose_task_version_form($symb,$env{'form.student'},
10937:                                               $env{'form.userdom'});
10938:             }
10939:             my $divforres;
10940:             if ($env{'form.student'} eq '') {
10941:                 $js .= &part_selector_js();
10942:                 $onload = "toggleParts('gradesub');";
10943:             } else {
10944:                 $divforres = 1;
10945:             }
10946:             my $head_extra = $js;
10947:             unless ($env{'form.vProb'} eq 'no') {
10948:                 my $csslinks = &Apache::loncommon::css_links($symb);
10949:                 if ($csslinks) {
10950:                     $head_extra .= "\n$csslinks";
10951:                 }
10952:             }
10953:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
10954:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
10955:             if ($versionform) {
10956:                 if ($divforres) {
10957:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
10958:                 }
10959:                 $request->print($versionform);
10960:             }
10961:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
10962:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10963:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10964:                 &choose_task_version_form($symb,$env{'form.student'},
10965:                                           $env{'form.userdom'},
10966:                                           $env{'form.inhibitmenu'});
10967:             my $head_extra = $js;
10968:             unless ($env{'form.vProb'} eq 'no') {
10969:                 my $csslinks = &Apache::loncommon::css_links($symb);
10970:                 if ($csslinks) {
10971:                     $head_extra .= "\n$csslinks";
10972:                 }
10973:             }
10974:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
10975:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
10976:             if ($versionform) {
10977:                 $request->print($versionform);
10978:             }
10979:             $request->print('<br clear="all" />');
10980:             $request->print(&show_previous_task_version($request,$symb));
10981:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10982:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10983:                                        {href=>'',text=>'Select student'}],1,1);
10984:             &pickStudentPage($request,$symb);
10985:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10986:             my $csslinks;
10987:             unless ($env{'form.vProb'} eq 'no') {
10988:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
10989:             }
10990:             &startpage($request,$symb,
10991:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10992:                                        {href=>'',text=>'Select student'},
10993:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
10994:             &displayPage($request,$symb);
10995:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10996:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10997:                                        {href=>'',text=>'Select student'},
10998:                                        {href=>'',text=>'Grade student'},
10999:                                        {href=>'',text=>'Store grades'}],1,1);
11000:             &updateGradeByPage($request,$symb);
11001:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11002:             my $csslinks;
11003:             unless ($env{'form.vProb'} eq 'no') {
11004:                 $csslinks = &Apache::loncommon::css_links($symb);
11005:             }
11006:             &startpage($request,$symb,[{href=>'',text=>'...'},
11007:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11008:             &processGroup($request,$symb);
11009:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11010:             &startpage($request,$symb);
11011:             $request->print(&grading_menu($request,$symb));
11012:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
11013:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11014:             $request->print(&submit_options($request,$symb));
11015:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11016:             my $js = &part_selector_js();
11017:             my $onload = "toggleParts('gradesub');";
11018:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11019:                        undef,undef,undef,undef,undef,$js,$onload);
11020:             $request->print(&listStudents($request,$symb,'graded'));
11021:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11022:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11023:             $request->print(&submit_options_table($request,$symb));
11024:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11025:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11026:             $request->print(&submit_options_sequence($request,$symb));
11027:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11028:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11029:             $request->print(&viewgrades($request,$symb));
11030:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11031:             &startpage($request,$symb,[{href=>'',text=>'...'},
11032:                                        {href=>'',text=>'Store grades'}]);
11033:             $request->print(&processHandGrade($request,$symb));
11034:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11035:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11036:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11037:                                                                              text=>"Modify grades"},
11038:                                        {href=>'', text=>"Store grades"}]);
11039:             $request->print(&editgrades($request,$symb));
11040:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11041:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11042:             $request->print(&initialverifyreceipt($request,$symb));
11043:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
11044:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11045:                                        {href=>'',text=>'Verification Result'}]);
11046:             $request->print(&verifyreceipt($request,$symb));
11047:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11048:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11049:             $request->print(&process_clicker($request,$symb));
11050:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11051:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11052:                                        {href=>'', text=>'Process clicker file'}]);
11053:             $request->print(&process_clicker_file($request,$symb));
11054:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11055:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11056:                                        {href=>'', text=>'Process clicker file'},
11057:                                        {href=>'', text=>'Store grades'}]);
11058:             $request->print(&assign_clicker_grades($request,$symb));
11059:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
11060:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11061:             $request->print(&upcsvScores_form($request,$symb));
11062:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11063:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11064:             $request->print(&csvupload($request,$symb));
11065:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11066:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11067:             $request->print(&csvuploadmap($request,$symb));
11068:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11069:             if ($env{'form.associate'} ne 'Reverse Association') {
11070:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11071:                 $request->print(&csvuploadoptions($request,$symb));
11072:             } else {
11073:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11074:                     $env{'form.upfile_associate'} = 'reverse';
11075:                 } else {
11076:                     $env{'form.upfile_associate'} = 'forward';
11077:                 }
11078:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11079:                 $request->print(&csvuploadmap($request,$symb));
11080:             }
11081:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11082:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11083:             $request->print(&csvuploadassign($request,$symb));
11084:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11085:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11086:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11087:             $request->print(&scantron_selectphase($request,undef,$symb));
11088:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11089:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11090:             $request->print(&scantron_do_warning($request,$symb));
11091:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11092:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11093:             $request->print(&scantron_validate_file($request,$symb));
11094:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11095:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11096:             $request->print(&scantron_process_students($request,$symb));
11097:         } elsif ($command eq 'scantronupload' &&
11098:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11099:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11100:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11101:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11102:             $request->print(&scantron_upload_scantron_data($request,$symb));
11103:         } elsif ($command eq 'scantronupload_save' &&
11104:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11105:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11106:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11107:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11108:         } elsif ($command eq 'scantron_download' &&
11109:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11110:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11111:             $request->print(&scantron_download_scantron_data($request,$symb));
11112:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11113:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11114:             $request->print(&checkscantron_results($request,$symb));
11115:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11116:             my $js = &part_selector_js();
11117:             my $onload = "toggleParts('gradingMenu');";
11118:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11119:                        undef,undef,undef,undef,undef,$js,$onload);
11120:             $request->print(&submit_options_download($request,$symb));
11121:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11122:             &startpage($request,$symb,
11123:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11124:     {href=>'', text=>'Download submitted files'}],
11125:                undef,undef,undef,undef,undef,undef,undef,1);
11126:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11127:             &submit_download_link($request,$symb);
11128:         } elsif ($command) {
11129:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11130:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11131:         }
11132:     }
11133:     if ($ssi_error) {
11134: 	&ssi_print_error($request);
11135:     }
11136:     $request->print(&Apache::loncommon::end_page());
11137:     &reset_caches();
11138:     return OK;
11139: }
11140: 
11141: 1;
11142: 
11143: __END__;
11144: 
11145: 
11146: =head1 NAME
11147: 
11148: Apache::grades
11149: 
11150: =head1 SYNOPSIS
11151: 
11152: Handles the viewing of grades.
11153: 
11154: This is part of the LearningOnline Network with CAPA project
11155: described at http://www.lon-capa.org.
11156: 
11157: =head1 OVERVIEW
11158: 
11159: Do an ssi with retries:
11160: While I'd love to factor out this with the vesrion in lonprintout,
11161: 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
11162: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11163: 
11164: At least the logic that drives this has been pulled out into loncommon.
11165: 
11166: 
11167: 
11168: ssi_with_retries - Does the server side include of a resource.
11169:                      if the ssi call returns an error we'll retry it up to
11170:                      the number of times requested by the caller.
11171:                      If we still have a problem, no text is appended to the
11172:                      output and we set some global variables.
11173:                      to indicate to the caller an SSI error occurred.  
11174:                      All of this is supposed to deal with the issues described
11175:                      in LON-CAPA BZ 5631 see:
11176:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11177:                      by informing the user that this happened.
11178: 
11179: Parameters:
11180:   resource   - The resource to include.  This is passed directly, without
11181:                interpretation to lonnet::ssi.
11182:   form       - The form hash parameters that guide the interpretation of the resource
11183:                
11184:   retries    - Number of retries allowed before giving up completely.
11185: Returns:
11186:   On success, returns the rendered resource identified by the resource parameter.
11187: Side Effects:
11188:   The following global variables can be set:
11189:    ssi_error                - If an unrecoverable error occurred this becomes true.
11190:                               It is up to the caller to initialize this to false
11191:                               if desired.
11192:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11193:                               of the resource that could not be rendered by the ssi
11194:                               call.
11195:    ssi_error_message   - The error string fetched from the ssi response
11196:                               in the event of an error.
11197: 
11198: 
11199: =head1 HANDLER SUBROUTINE
11200: 
11201: ssi_with_retries()
11202: 
11203: =head1 SUBROUTINES
11204: 
11205: =over
11206: 
11207: =item scantron_get_correction() : 
11208: 
11209:    Builds the interface screen to interact with the operator to fix a
11210:    specific error condition in a specific scanline
11211: 
11212:  Arguments:
11213:     $r           - Apache request object
11214:     $i           - number of the current scanline
11215:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11216:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11217:     $line        - full contents of the current scanline
11218:     $error       - error condition, valid values are
11219:                    'incorrectCODE', 'duplicateCODE',
11220:                    'doublebubble', 'missingbubble',
11221:                    'duplicateID', 'incorrectID'
11222:     $arg         - extra information needed
11223:        For errors:
11224:          - duplicateID   - paper number that this studentID was seen before on
11225:          - duplicateCODE - array ref of the paper numbers this CODE was
11226:                            seen on before
11227:          - incorrectCODE - current incorrect CODE 
11228:          - doublebubble  - array ref of the bubble lines that have double
11229:                            bubble errors
11230:          - missingbubble - array ref of the bubble lines that have missing
11231:                            bubble errors
11232: 
11233:    $randomorder - True if exam folder has randomorder set
11234:    $randompick  - True if exam folder has randompick set
11235:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11236:                      for current line to question number used for same question
11237:                      in "Master Seqence" (as seen by Course Coordinator).
11238:    $startline   - Reference to hash where key is question number (0 is first)
11239:                   and value is number of first bubble line for current student
11240:                   or code-based randompick and/or randomorder.
11241: 
11242: 
11243: =item  scantron_get_maxbubble() : 
11244: 
11245:    Arguments:
11246:        $nav_error  - Reference to scalar which is a flag to indicate a
11247:                       failure to retrieve a navmap object.
11248:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11249:        calling routine should trap the error condition and display the warning
11250:        found in &navmap_errormsg().
11251: 
11252:        $scantron_config - Reference to bubblesheet format configuration hash.
11253: 
11254:    Returns the maximum number of bubble lines that are expected to
11255:    occur. Does this by walking the selected sequence rendering the
11256:    resource and then checking &Apache::lonxml::get_problem_counter()
11257:    for what the current value of the problem counter is.
11258: 
11259:    Caches the results to $env{'form.scantron_maxbubble'},
11260:    $env{'form.scantron.bubble_lines.n'}, 
11261:    $env{'form.scantron.first_bubble_line.n'} and
11262:    $env{"form.scantron.sub_bubblelines.n"}
11263:    which are the total number of bubble lines, the number of bubble
11264:    lines for response n and number of the first bubble line for response n,
11265:    and a comma separated list of numbers of bubble lines for sub-questions
11266:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11267: 
11268: 
11269: =item  scantron_validate_missingbubbles() : 
11270: 
11271:    Validates all scanlines in the selected file to not have any
11272:     answers that don't have bubbles that have not been verified
11273:     to be bubble free.
11274: 
11275: =item  scantron_process_students() : 
11276: 
11277:    Routine that does the actual grading of the bubblesheet information.
11278: 
11279:    The parsed scanline hash is added to %env 
11280: 
11281:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11282:    foreach resource , with the form data of
11283: 
11284: 	'submitted'     =>'scantron' 
11285: 	'grade_target'  =>'grade',
11286: 	'grade_username'=> username of student
11287: 	'grade_domain'  => domain of student
11288: 	'grade_courseid'=> of course
11289: 	'grade_symb'    => symb of resource to grade
11290: 
11291:     This triggers a grading pass. The problem grading code takes care
11292:     of converting the bubbled letter information (now in %env) into a
11293:     valid submission.
11294: 
11295: =item  scantron_upload_scantron_data() :
11296: 
11297:     Creates the screen for adding a new bubblesheet data file to a course.
11298: 
11299: =item  scantron_upload_scantron_data_save() : 
11300: 
11301:    Adds a provided bubble information data file to the course if user
11302:    has the correct privileges to do so. 
11303: 
11304: =item  valid_file() :
11305: 
11306:    Validates that the requested bubble data file exists in the course.
11307: 
11308: =item  scantron_download_scantron_data() : 
11309: 
11310:    Shows a list of the three internal files (original, corrected,
11311:    skipped) for a specific bubblesheet data file that exists in the
11312:    course.
11313: 
11314: =item  scantron_validate_ID() : 
11315: 
11316:    Validates all scanlines in the selected file to not have any
11317:    invalid or underspecified student/employee IDs
11318: 
11319: =item navmap_errormsg() :
11320: 
11321:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11322:    Should be called whenever the request to instantiate a navmap object fails.  
11323: 
11324: =back
11325: 
11326: =cut

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