File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.54: download - view: text, annotated - select for diffs
Thu Sep 10 00:39:46 2020 UTC (3 years, 7 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  Backport 1.776

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.54 2020/09/10 00:39:46 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:                   .&Apache::lonhtmlcommon::row_closure()
 1148:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1149:                   .'<span class="LC_nobreak">'
 1150:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1151:                   .&mt('No').('&nbsp;'x2).'</label>'
 1152:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1153:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1154:                   .&Apache::lonhtmlcommon::row_closure();
 1155: 
 1156:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1157:                   .'<select name="increment">'
 1158:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1159:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1160:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1161:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1162:                   .'</select>';
 1163:     $gradeTable .= 
 1164:         &build_section_inputs().
 1165: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1166: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1167: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1168:     if (exists($env{'form.Status'})) {
 1169: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1170:     } else {
 1171:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1172:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1173:                       .&Apache::lonhtmlcommon::StatusOptions(
 1174:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1175:     }
 1176:     if ($numessay) {
 1177:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1178:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1179:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1180:     }
 1181:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1182:                   .&Apache::lonhtmlcommon::end_pick_box();
 1183: 
 1184:     $gradeTable .= '<p>'
 1185:                   .&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"
 1186:                   .'<input type="hidden" name="command" value="processGroup" />'
 1187:                   .'</p>';
 1188: 
 1189: # checkall buttons
 1190:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1191:     $gradeTable.='<input type="button" '."\n".
 1192:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1193:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1194:     $gradeTable.=&check_buttons();
 1195:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1196:     $gradeTable.= &Apache::loncommon::start_data_table().
 1197: 	&Apache::loncommon::start_data_table_header_row();
 1198:     my $loop = 0;
 1199:     while ($loop < 2) {
 1200: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1201: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1202: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1203: 	    foreach my $part (sort(@$partlist)) {
 1204: 		my $display_part=
 1205: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1206: 		$gradeTable.=
 1207: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1208: 	    }
 1209: 	} elsif ($submitonly eq 'queued') {
 1210: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1211: 	}
 1212: 	$loop++;
 1213: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1214:     }
 1215:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1216: 
 1217:     my $ctr = 0;
 1218:     foreach my $student (sort 
 1219: 			 {
 1220: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1221: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1222: 			     }
 1223: 			     return $a cmp $b;
 1224: 			 }
 1225: 			 (keys(%$fullname))) {
 1226: 	my ($uname,$udom) = split(/:/,$student);
 1227: 
 1228: 	my %status = ();
 1229: 
 1230: 	if ($submitonly eq 'queued') {
 1231: 	    my %queue_status = 
 1232: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1233: 							$udom,$uname);
 1234: 	    next if (!defined($queue_status{'gradingqueue'}));
 1235: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1236: 	}
 1237: 
 1238: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1239: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1240: 	    my $submitted = 0;
 1241: 	    my $graded = 0;
 1242: 	    my $incorrect = 0;
 1243: 	    foreach (keys(%status)) {
 1244: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1245: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1246: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1247: 		
 1248: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1249: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1250: 		    $submitted = 0;
 1251: 		    my ($part)=split(/\./,$partid);
 1252: 		    $gradeTable.='<input type="hidden" name="'.
 1253: 			$student.':'.$part.':submitted_by" value="'.
 1254: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1255: 		}
 1256: 	    }
 1257: 	    
 1258: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1259: 				     $submitonly eq 'incorrect' ||
 1260: 				     $submitonly eq 'graded'));
 1261: 	    next if (!$graded && ($submitonly eq 'graded'));
 1262: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1263: 	}
 1264: 
 1265: 	$ctr++;
 1266: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1267:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1268: 	if ( $perm{'vgr'} eq 'F' ) {
 1269: 	    if ($ctr%2 ==1) {
 1270: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1271: 	    }
 1272: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1273:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1274:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1275: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1276: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1277: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1278: 
 1279: 	    if ($submitonly ne 'all') {
 1280: 		foreach (sort(keys(%status))) {
 1281: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1282: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1283: 		}
 1284: 	    }
 1285: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1286: 	    if ($ctr%2 ==0) {
 1287: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1288: 	    }
 1289: 	}
 1290:     }
 1291:     if ($ctr%2 ==1) {
 1292: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1293: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1294: 		foreach (@$partlist) {
 1295: 		    $gradeTable.='<td>&nbsp;</td>';
 1296: 		}
 1297: 	    } elsif ($submitonly eq 'queued') {
 1298: 		$gradeTable.='<td>&nbsp;</td>';
 1299: 	    }
 1300: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1301:     }
 1302: 
 1303:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1304:         '<input type="button" '.
 1305:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1306:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1307:     if ($ctr == 0) {
 1308: 	my $num_students=(scalar(keys(%$fullname)));
 1309: 	if ($num_students eq 0) {
 1310: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1311: 	} else {
 1312: 	    my $submissions='submissions';
 1313: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1314: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1315: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1316: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1317: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1318: 		    $num_students).
 1319: 		'</span><br />';
 1320: 	}
 1321:     } elsif ($ctr == 1) {
 1322: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1323:     }
 1324:     $request->print($gradeTable);
 1325:     return '';
 1326: }
 1327: 
 1328: #---- Called from the listStudents routine
 1329: 
 1330: sub check_script {
 1331:     my ($form,$type) = @_;
 1332:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1333:     function checkall() {
 1334:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1335:             ele = document.forms.'.$form.'.elements[i];
 1336:             if (ele.name == "'.$type.'") {
 1337:             document.forms.'.$form.'.elements[i].checked=true;
 1338:                                        }
 1339:         }
 1340:     }
 1341: 
 1342:     function checksec() {
 1343:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1344:             ele = document.forms.'.$form.'.elements[i];
 1345:            string = document.forms.'.$form.'.chksec.value;
 1346:            if
 1347:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1348:               document.forms.'.$form.'.elements[i].checked=true;
 1349:             }
 1350:         }
 1351:     }
 1352: 
 1353: 
 1354:     function uncheckall() {
 1355:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1356:             ele = document.forms.'.$form.'.elements[i];
 1357:             if (ele.name == "'.$type.'") {
 1358:             document.forms.'.$form.'.elements[i].checked=false;
 1359:                                        }
 1360:         }
 1361:     }
 1362: 
 1363: '."\n");
 1364:     return $chkallscript;
 1365: }
 1366: 
 1367: sub check_buttons {
 1368:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1369:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1370:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1371:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1372:     return $buttons;
 1373: }
 1374: 
 1375: #     Displays the submissions for one student or a group of students
 1376: sub processGroup {
 1377:     my ($request,$symb) = @_;
 1378:     my $ctr        = 0;
 1379:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1380:     my $total      = scalar(@stuchecked)-1;
 1381: 
 1382:     foreach my $student (@stuchecked) {
 1383: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1384: 	$env{'form.student'}        = $uname;
 1385: 	$env{'form.userdom'}        = $udom;
 1386: 	$env{'form.fullname'}       = $fullname;
 1387: 	&submission($request,$ctr,$total,$symb);
 1388: 	$ctr++;
 1389:     }
 1390:     return '';
 1391: }
 1392: 
 1393: #------------------------------------------------------------------------------------
 1394: #
 1395: #-------------------------- Next few routines handles grading by student, essentially
 1396: #                           handles essay response type problem/part
 1397: #
 1398: #--- Javascript to handle the submission page functionality ---
 1399: sub sub_page_js {
 1400:     my $request = shift;
 1401:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1402:     &js_escape(\$alertmsg);
 1403:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1404:     function updateRadio(formname,id,weight) {
 1405: 	var gradeBox = formname["GD_BOX"+id];
 1406: 	var radioButton = formname["RADVAL"+id];
 1407: 	var oldpts = formname["oldpts"+id].value;
 1408: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1409: 	gradeBox.value = pts;
 1410: 	var resetbox = false;
 1411: 	if (isNaN(pts) || pts < 0) {
 1412: 	    alert("$alertmsg"+pts);
 1413: 	    for (var i=0; i<radioButton.length; i++) {
 1414: 		if (radioButton[i].checked) {
 1415: 		    gradeBox.value = i;
 1416: 		    resetbox = true;
 1417: 		}
 1418: 	    }
 1419: 	    if (!resetbox) {
 1420: 		formtextbox.value = "";
 1421: 	    }
 1422: 	    return;
 1423: 	}
 1424: 
 1425: 	if (pts > weight) {
 1426: 	    var resp = confirm("You entered a value ("+pts+
 1427: 			       ") greater than the weight for the part. Accept?");
 1428: 	    if (resp == false) {
 1429: 		gradeBox.value = oldpts;
 1430: 		return;
 1431: 	    }
 1432: 	}
 1433: 
 1434: 	for (var i=0; i<radioButton.length; i++) {
 1435: 	    radioButton[i].checked=false;
 1436: 	    if (pts == i && pts != "") {
 1437: 		radioButton[i].checked=true;
 1438: 	    }
 1439: 	}
 1440: 	updateSelect(formname,id);
 1441: 	formname["stores"+id].value = "0";
 1442:     }
 1443: 
 1444:     function writeBox(formname,id,pts) {
 1445: 	var gradeBox = formname["GD_BOX"+id];
 1446: 	if (checkSolved(formname,id) == 'update') {
 1447: 	    gradeBox.value = pts;
 1448: 	} else {
 1449: 	    var oldpts = formname["oldpts"+id].value;
 1450: 	    gradeBox.value = oldpts;
 1451: 	    var radioButton = formname["RADVAL"+id];
 1452: 	    for (var i=0; i<radioButton.length; i++) {
 1453: 		radioButton[i].checked=false;
 1454: 		if (i == oldpts) {
 1455: 		    radioButton[i].checked=true;
 1456: 		}
 1457: 	    }
 1458: 	}
 1459: 	formname["stores"+id].value = "0";
 1460: 	updateSelect(formname,id);
 1461: 	return;
 1462:     }
 1463: 
 1464:     function clearRadBox(formname,id) {
 1465: 	if (checkSolved(formname,id) == 'noupdate') {
 1466: 	    updateSelect(formname,id);
 1467: 	    return;
 1468: 	}
 1469: 	gradeSelect = formname["GD_SEL"+id];
 1470: 	for (var i=0; i<gradeSelect.length; i++) {
 1471: 	    if (gradeSelect[i].selected) {
 1472: 		var selectx=i;
 1473: 	    }
 1474: 	}
 1475: 	var stores = formname["stores"+id];
 1476: 	if (selectx == stores.value) { return };
 1477: 	var gradeBox = formname["GD_BOX"+id];
 1478: 	gradeBox.value = "";
 1479: 	var radioButton = formname["RADVAL"+id];
 1480: 	for (var i=0; i<radioButton.length; i++) {
 1481: 	    radioButton[i].checked=false;
 1482: 	}
 1483: 	stores.value = selectx;
 1484:     }
 1485: 
 1486:     function checkSolved(formname,id) {
 1487: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1488: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1489: 	    if (!reply) {return "noupdate";}
 1490: 	    formname.overRideScore.value = 'yes';
 1491: 	}
 1492: 	return "update";
 1493:     }
 1494: 
 1495:     function updateSelect(formname,id) {
 1496: 	formname["GD_SEL"+id][0].selected = true;
 1497: 	return;
 1498:     }
 1499: 
 1500: //=========== Check that a point is assigned for all the parts  ============
 1501:     function checksubmit(formname,val,total,parttot) {
 1502: 	formname.gradeOpt.value = val;
 1503: 	if (val == "Save & Next") {
 1504: 	    for (i=0;i<=total;i++) {
 1505: 		for (j=0;j<parttot;j++) {
 1506: 		    var partid = formname["partid"+i+"_"+j].value;
 1507: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1508: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1509: 			if (points == "") {
 1510: 			    var name = formname["name"+i].value;
 1511: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1512: 			    var resp = confirm("You did not assign a score for "+studentID+
 1513: 					       ", part "+partid+". Continue?");
 1514: 			    if (resp == false) {
 1515: 				formname["GD_BOX"+i+"_"+partid].focus();
 1516: 				return false;
 1517: 			    }
 1518: 			}
 1519: 		    }
 1520: 		}
 1521: 	    }
 1522: 	}
 1523: 	formname.submit();
 1524:     }
 1525: 
 1526: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1527:     function checkSubmitPage(formname,total) {
 1528: 	noscore = new Array(100);
 1529: 	var ptr = 0;
 1530: 	for (i=1;i<total;i++) {
 1531: 	    var partid = formname["q_"+i].value;
 1532: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1533: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1534: 		var status = formname["solved"+i+"_"+partid].value;
 1535: 		if (points == "" && status != "correct_by_student") {
 1536: 		    noscore[ptr] = i;
 1537: 		    ptr++;
 1538: 		}
 1539: 	    }
 1540: 	}
 1541: 	if (ptr != 0) {
 1542: 	    var sense = ptr == 1 ? ": " : "s: ";
 1543: 	    var prolist = "";
 1544: 	    if (ptr == 1) {
 1545: 		prolist = noscore[0];
 1546: 	    } else {
 1547: 		var i = 0;
 1548: 		while (i < ptr-1) {
 1549: 		    prolist += noscore[i]+", ";
 1550: 		    i++;
 1551: 		}
 1552: 		prolist += "and "+noscore[i];
 1553: 	    }
 1554: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1555: 	    if (resp == false) {
 1556: 		return false;
 1557: 	    }
 1558: 	}
 1559: 
 1560: 	formname.submit();
 1561:     }
 1562: SUBJAVASCRIPT
 1563: }
 1564: 
 1565: #--- javascript for grading message center
 1566: sub sub_grademessage_js {
 1567:     my $request = shift;
 1568:     my $iconpath = $request->dir_config('lonIconsURL');
 1569:     &commonJSfunctions($request);
 1570: 
 1571:     my $inner_js_msg_central= (<<INNERJS);
 1572: <script type="text/javascript">
 1573:     function checkInput() {
 1574:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1575:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1576:       var usrctr = document.msgcenter.usrctr.value;
 1577:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1578:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1579: 
 1580:       var msgchk = "";
 1581:       if (document.msgcenter.subchk.checked) {
 1582:          msgchk = "msgsub,";
 1583:       }
 1584:       var includemsg = 0;
 1585:       for (var i=1; i<=nmsg; i++) {
 1586:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1587:           var frmmsg = document.msgcenter["msg"+i];
 1588:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1589:           var showflg = opener.document.SCORE["shownOnce"+i];
 1590:           showflg.value = "1";
 1591:           var chkbox = document.msgcenter["msgn"+i];
 1592:           if (chkbox.checked) {
 1593:              msgchk += "savemsg"+i+",";
 1594:              includemsg = 1;
 1595:           }
 1596:       }
 1597:       if (document.msgcenter.newmsgchk.checked) {
 1598:          msgchk += "newmsg"+usrctr;
 1599:          includemsg = 1;
 1600:       }
 1601:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1602:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1603:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1604:       includemsg.value = msgchk;
 1605: 
 1606:       self.close()
 1607: 
 1608:     }
 1609: </script>
 1610: INNERJS
 1611: 
 1612:     my $start_page_msg_central =
 1613:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1614: 				       {'js_ready'  => 1,
 1615: 					'only_body' => 1,
 1616: 					'bgcolor'   =>'#FFFFFF',});
 1617:     my $end_page_msg_central =
 1618: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1619: 
 1620: 
 1621:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1622:     $docopen=~s/^document\.//;
 1623: 
 1624:     my %html_js_lt = &Apache::lonlocal::texthash(
 1625:                 comp => 'Compose Message for: ',
 1626:                 incl => 'Include',
 1627:                 type => 'Type',
 1628:                 subj => 'Subject',
 1629:                 mesa => 'Message',
 1630:                 new  => 'New',
 1631:                 save => 'Save',
 1632:                 canc => 'Cancel',
 1633:              );
 1634:     &html_escape(\%html_js_lt);
 1635:     &js_escape(\%html_js_lt);
 1636:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1637: 
 1638: //===================== Script to view submitted by ==================
 1639:   function viewSubmitter(submitter) {
 1640:     document.SCORE.refresh.value = "on";
 1641:     document.SCORE.NCT.value = "1";
 1642:     document.SCORE.unamedom0.value = submitter;
 1643:     document.SCORE.submit();
 1644:     return;
 1645:   }
 1646: 
 1647: //====================== Script for composing message ==============
 1648:    // preload images
 1649:    img1 = new Image();
 1650:    img1.src = "$iconpath/mailbkgrd.gif";
 1651:    img2 = new Image();
 1652:    img2.src = "$iconpath/mailto.gif";
 1653: 
 1654:   function msgCenter(msgform,usrctr,fullname) {
 1655:     var Nmsg  = msgform.savemsgN.value;
 1656:     savedMsgHeader(Nmsg,usrctr,fullname);
 1657:     var subject = msgform.msgsub.value;
 1658:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1659:     re = /msgsub/;
 1660:     var shwsel = "";
 1661:     if (re.test(msgchk)) { shwsel = "checked" }
 1662:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1663:     displaySubject(checkEntities(subject),shwsel);
 1664:     for (var i=1; i<=Nmsg; i++) {
 1665: 	var testmsg = "savemsg"+i+",";
 1666: 	re = new RegExp(testmsg,"g");
 1667: 	shwsel = "";
 1668: 	if (re.test(msgchk)) { shwsel = "checked" }
 1669: 	var message = document.SCORE["savemsg"+i].value;
 1670: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1671: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1672: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1673:     }
 1674:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1675:     shwsel = "";
 1676:     re = /newmsg/;
 1677:     if (re.test(msgchk)) { shwsel = "checked" }
 1678:     newMsg(newmsg,shwsel);
 1679:     msgTail(); 
 1680:     return;
 1681:   }
 1682: 
 1683:   function checkEntities(strx) {
 1684:     if (strx.length == 0) return strx;
 1685:     var orgStr = ["&", "<", ">", '"']; 
 1686:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1687:     var counter = 0;
 1688:     while (counter < 4) {
 1689: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1690: 	counter++;
 1691:     }
 1692:     return strx;
 1693:   }
 1694: 
 1695:   function strReplace(strx, orgStr, newStr) {
 1696:     return strx.split(orgStr).join(newStr);
 1697:   }
 1698: 
 1699:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1700:     var height = 70*Nmsg+250;
 1701:     if (height > 600) {
 1702: 	height = 600;
 1703:     }
 1704:     var xpos = (screen.width-600)/2;
 1705:     xpos = (xpos < 0) ? '0' : xpos;
 1706:     var ypos = (screen.height-height)/2-30;
 1707:     ypos = (ypos < 0) ? '0' : ypos;
 1708: 
 1709:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1710:     pWin.focus();
 1711:     pDoc = pWin.document;
 1712:     pDoc.$docopen;
 1713:     pDoc.write('$start_page_msg_central');
 1714: 
 1715:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1716:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1717:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1718: 
 1719:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1720:     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>");
 1721: }
 1722:     function displaySubject(msg,shwsel) {
 1723:     pDoc = pWin.document;
 1724:     pDoc.write("<tr>");
 1725:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1726:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1727:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1728: }
 1729: 
 1730:   function displaySavedMsg(ctr,msg,shwsel) {
 1731:     pDoc = pWin.document;
 1732:     pDoc.write("<tr>");
 1733:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1734:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1735:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1736: }
 1737: 
 1738:   function newMsg(newmsg,shwsel) {
 1739:     pDoc = pWin.document;
 1740:     pDoc.write("<tr>");
 1741:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1742:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1743:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1744: }
 1745: 
 1746:   function msgTail() {
 1747:     pDoc = pWin.document;
 1748:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1749:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1750:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1751:     pDoc.write("<\\/form>");
 1752:     pDoc.write('$end_page_msg_central');
 1753:     pDoc.close();
 1754: }
 1755: 
 1756: SUBJAVASCRIPT
 1757: }
 1758: 
 1759: #--- javascript for essay type problem --
 1760: sub sub_page_kw_js {
 1761:     my $request = shift;
 1762: 
 1763:     unless ($env{'form.compmsg'}) {
 1764:         &commonJSfunctions($request);
 1765:     }
 1766: 
 1767:     my $inner_js_highlight_central= (<<INNERJS);
 1768: <script type="text/javascript">
 1769:     function updateChoice(flag) {
 1770:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1771:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1772:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1773:       opener.document.SCORE.refresh.value = "on";
 1774:       if (opener.document.SCORE.keywords.value!=""){
 1775:          opener.document.SCORE.submit();
 1776:       }
 1777:       self.close()
 1778:     }
 1779: </script>
 1780: INNERJS
 1781: 
 1782:     my $start_page_highlight_central =
 1783:         &Apache::loncommon::start_page('Highlight Central',
 1784:                                        $inner_js_highlight_central,
 1785:                                        {'js_ready'  => 1,
 1786:                                         'only_body' => 1,
 1787:                                         'bgcolor'   =>'#FFFFFF',});
 1788:     my $end_page_highlight_central =
 1789:         &Apache::loncommon::end_page({'js_ready' => 1});
 1790: 
 1791:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1792:     $docopen=~s/^document\.//;
 1793: 
 1794:     my %js_lt = &Apache::lonlocal::texthash(
 1795:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1796:                 plse => 'Please select a word or group of words from document and then click this link.',
 1797:                 adds => 'Add selection to keyword list? Edit if desired.',
 1798:                 col1 => 'red',
 1799:                 col2 => 'green',
 1800:                 col3 => 'blue',
 1801:                 siz1 => 'normal',
 1802:                 siz2 => '+1',
 1803:                 siz3 => '+2',
 1804:                 sty1 => 'normal',
 1805:                 sty2 => 'italic',
 1806:                 sty3 => 'bold',
 1807:              );
 1808:     my %html_js_lt = &Apache::lonlocal::texthash(
 1809:                 save => 'Save',
 1810:                 canc => 'Cancel',
 1811:                 kehi => 'Keyword Highlight Options',
 1812:                 txtc => 'Text Color',
 1813:                 font => 'Font Size',
 1814:                 fnst => 'Font Style',
 1815:              );
 1816:     &js_escape(\%js_lt);
 1817:     &html_escape(\%html_js_lt);
 1818:     &js_escape(\%html_js_lt);
 1819:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1820: 
 1821: //===================== Show list of keywords ====================
 1822:   function keywords(formname) {
 1823:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1824:     if (nret==null) return;
 1825:     formname.keywords.value = nret;
 1826: 
 1827:     if (formname.keywords.value != "") {
 1828:         formname.refresh.value = "on";
 1829:         formname.submit();
 1830:     }
 1831:     return;
 1832:   }
 1833: 
 1834: //===================== Script to add keyword(s) ==================
 1835:   function getSel() {
 1836:     if (document.getSelection) txt = document.getSelection();
 1837:     else if (document.selection) txt = document.selection.createRange().text;
 1838:     else return;
 1839:     if (typeof(txt) != 'string') {
 1840:         txt = String(txt);
 1841:     }
 1842:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1843:     if (cleantxt=="") {
 1844:         alert("$js_lt{'plse'}");
 1845:         return;
 1846:     }
 1847:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1848:     if (nret==null) return;
 1849:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1850:     if (document.SCORE.keywords.value != "") {
 1851:         document.SCORE.refresh.value = "on";
 1852:         document.SCORE.submit();
 1853:     }
 1854:     return;
 1855:   }
 1856: 
 1857: //====================== Script for keyword highlight options ==============
 1858:   function kwhighlight() {
 1859:     var kwclr    = document.SCORE.kwclr.value;
 1860:     var kwsize   = document.SCORE.kwsize.value;
 1861:     var kwstyle  = document.SCORE.kwstyle.value;
 1862:     var redsel = "";
 1863:     var grnsel = "";
 1864:     var blusel = "";
 1865:     var txtcol1 = "$js_lt{'col1'}";
 1866:     var txtcol2 = "$js_lt{'col2'}";
 1867:     var txtcol3 = "$js_lt{'col3'}";
 1868:     var txtsiz1 = "$js_lt{'siz1'}";
 1869:     var txtsiz2 = "$js_lt{'siz2'}";
 1870:     var txtsiz3 = "$js_lt{'siz3'}";
 1871:     var txtsty1 = "$js_lt{'sty1'}";
 1872:     var txtsty2 = "$js_lt{'sty2'}";
 1873:     var txtsty3 = "$js_lt{'sty3'}";
 1874:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1875:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1876:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1877:     var sznsel = "";
 1878:     var sz1sel = "";
 1879:     var sz2sel = "";
 1880:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1881:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1882:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1883:     var synsel = "";
 1884:     var syisel = "";
 1885:     var sybsel = "";
 1886:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1887:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1888:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1889:     highlightCentral();
 1890:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1891:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1892:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1893:     highlightend();
 1894:     return;
 1895:   }
 1896: 
 1897:   function highlightCentral() {
 1898: //    if (window.hwdWin) window.hwdWin.close();
 1899:     var xpos = (screen.width-400)/2;
 1900:     xpos = (xpos < 0) ? '0' : xpos;
 1901:     var ypos = (screen.height-330)/2-30;
 1902:     ypos = (ypos < 0) ? '0' : ypos;
 1903: 
 1904:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1905:     hwdWin.focus();
 1906:     var hDoc = hwdWin.document;
 1907:     hDoc.$docopen;
 1908:     hDoc.write('$start_page_highlight_central');
 1909:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1910:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1911: 
 1912:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1913:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1914:   }
 1915: 
 1916:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1917:     var hDoc = hwdWin.document;
 1918:     hDoc.write("<tr>");
 1919:     hDoc.write("<td align=\\"left\\">");
 1920:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1921:     hDoc.write("<td align=\\"left\\">");
 1922:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1923:     hDoc.write("<td align=\\"left\\">");
 1924:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1925:     hDoc.write("<\\/tr>");
 1926:   }
 1927: 
 1928:   function highlightend() { 
 1929:     var hDoc = hwdWin.document;
 1930:     hDoc.write("<\\/table><br \\/>");
 1931:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1932:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1933:     hDoc.write("<\\/form>");
 1934:     hDoc.write('$end_page_highlight_central');
 1935:     hDoc.close();
 1936:   }
 1937: 
 1938: SUBJAVASCRIPT
 1939: }
 1940: 
 1941: sub get_increment {
 1942:     my $increment = $env{'form.increment'};
 1943:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1944:         $increment != .1) {
 1945:         $increment = 1;
 1946:     }
 1947:     return $increment;
 1948: }
 1949: 
 1950: sub gradeBox_start {
 1951:     return (
 1952:         &Apache::loncommon::start_data_table()
 1953:        .&Apache::loncommon::start_data_table_header_row()
 1954:        .'<th>'.&mt('Part').'</th>'
 1955:        .'<th>'.&mt('Points').'</th>'
 1956:        .'<th>&nbsp;</th>'
 1957:        .'<th>'.&mt('Assign Grade').'</th>'
 1958:        .'<th>'.&mt('Weight').'</th>'
 1959:        .'<th>'.&mt('Grade Status').'</th>'
 1960:        .&Apache::loncommon::end_data_table_header_row()
 1961:     );
 1962: }
 1963: 
 1964: sub gradeBox_end {
 1965:     return (
 1966:         &Apache::loncommon::end_data_table()
 1967:     );
 1968: }
 1969: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1970: sub gradeBox {
 1971:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1972:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1973: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1974:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1975:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1976:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1977:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1978:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1979: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1980:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1981:     my $display_part= &get_display_part($partid,$symb);
 1982:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1983: 				       [$partid]);
 1984:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1985:     if ($last_resets{$partid}) {
 1986:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1987:     }
 1988:     my $result=&Apache::loncommon::start_data_table_row();
 1989:     my $ctr = 0;
 1990:     my $thisweight = 0;
 1991:     my $increment = &get_increment();
 1992: 
 1993:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1994:     while ($thisweight<=$wgt) {
 1995: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1996:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1997: 	    $thisweight.')" value="'.$thisweight.'" '.
 1998: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1999: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2000:         $thisweight += $increment;
 2001: 	$ctr++;
 2002:     }
 2003:     $radio.='</tr></table>';
 2004: 
 2005:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2006: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2007: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2008: 	$wgt.')" /></td>'."\n";
 2009:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2010: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2011: 	' </td>'."\n";
 2012:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2013: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2014:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2015: 	$line.='<option></option>'.
 2016: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2017:     } else {
 2018: 	$line.='<option selected="selected"></option>'.
 2019: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2020:     }
 2021:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2022: 
 2023: 
 2024:     $result .= 
 2025: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2026:     $result.=&Apache::loncommon::end_data_table_row();
 2027:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2028:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2029: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2030: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2031: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2032:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2033:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2034:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2035:         $aggtries.'" />'."\n";
 2036:     my $res_error;
 2037:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2038:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2039:     if ($res_error) {
 2040:         return &navmap_errormsg();
 2041:     }
 2042:     return $result;
 2043: }
 2044: 
 2045: sub handback_box {
 2046:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2047:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2048:     return unless ($numessay);
 2049:     my (@respids);
 2050:     my @part_response_id = &flatten_responseType($responseType);
 2051:     foreach my $part_response_id (@part_response_id) {
 2052:     	my ($part,$resp) = @{ $part_response_id };
 2053:         if ($part eq $partid) {
 2054:             push(@respids,$resp);
 2055:         }
 2056:     }
 2057:     my $result;
 2058:     foreach my $respid (@respids) {
 2059: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2060: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2061: 	next if (!@$files);
 2062: 	my $file_counter = 0;
 2063: 	foreach my $file (@$files) {
 2064: 	    if ($file =~ /\/portfolio\//) {
 2065:                 $file_counter++;
 2066:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2067:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 2068:     	        $file_disp = "$name.$ext";
 2069:     	        $file = $file_path.$file_disp;
 2070:     	        $result.=&mt('Return commented version of [_1] to student.',
 2071:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2072:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2073:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2074: 	    }
 2075: 	}
 2076:         if ($file_counter) {
 2077:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2078:                        '<span class="LC_info">'.
 2079:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2080:         }
 2081:     }
 2082:     return $result;    
 2083: }
 2084: 
 2085: sub show_problem {
 2086:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2087:     my $rendered;
 2088:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2089:     &Apache::lonxml::remember_problem_counter();
 2090:     if ($mode eq 'both' or $mode eq 'text') {
 2091: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2092: 						       $env{'request.course.id'},
 2093: 						       undef,\%form);
 2094:     }
 2095:     if ($removeform) {
 2096: 	$rendered=~s|<form(.*?)>||g;
 2097: 	$rendered=~s|</form>||g;
 2098: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2099:     }
 2100:     my $companswer;
 2101:     if ($mode eq 'both' or $mode eq 'answer') {
 2102: 	&Apache::lonxml::restore_problem_counter();
 2103: 	$companswer=
 2104: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2105: 						    $env{'request.course.id'},
 2106: 						    %form);
 2107:     }
 2108:     if ($removeform) {
 2109: 	$companswer=~s|<form(.*?)>||g;
 2110: 	$companswer=~s|</form>||g;
 2111: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2112:     }
 2113:     my $renderheading = &mt('View of the problem');
 2114:     my $answerheading = &mt('Correct answer');
 2115:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2116:         my $stu_fullname = $env{'form.fullname'};
 2117:         if ($stu_fullname eq '') {
 2118:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2119:         }
 2120:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2121:         if ($forwhom ne '') {
 2122:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2123:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2124:         }
 2125:     }
 2126:     $rendered=
 2127:         '<div class="LC_Box">'
 2128:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2129:        .$rendered
 2130:        .'</div>';
 2131:     $companswer=
 2132:         '<div class="LC_Box">'
 2133:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2134:        .$companswer
 2135:        .'</div>';
 2136:     my $result;
 2137:     if ($mode eq 'both') {
 2138:         $result=$rendered.$companswer;
 2139:     } elsif ($mode eq 'text') {
 2140:         $result=$rendered;
 2141:     } elsif ($mode eq 'answer') {
 2142:         $result=$companswer;
 2143:     }
 2144:     return $result;
 2145: }
 2146: 
 2147: sub files_exist {
 2148:     my ($r, $symb) = @_;
 2149:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2150:     foreach my $student (@students) {
 2151:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2152:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2153: 					      $udom,$uname);
 2154:         my ($string,$timestamp)= &get_last_submission(\%record);
 2155:         foreach my $submission (@$string) {
 2156:             my ($partid,$respid) =
 2157: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2158:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2159: 					   \%record);
 2160:             return 1 if (@$files);
 2161:         }
 2162:     }
 2163:     return 0;
 2164: }
 2165: 
 2166: sub download_all_link {
 2167:     my ($r,$symb) = @_;
 2168:     unless (&files_exist($r, $symb)) {
 2169:         $r->print(&mt('There are currently no submitted documents.'));
 2170:         return;
 2171:     }
 2172:     my $all_students = 
 2173: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2174: 
 2175:     my $parts =
 2176: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2177: 
 2178:     my $identifier = &Apache::loncommon::get_cgi_id();
 2179:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2180:                              'cgi.'.$identifier.'.symb' => $symb,
 2181:                              'cgi.'.$identifier.'.parts' => $parts,});
 2182:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2183: 	      &mt('Download All Submitted Documents').'</a>');
 2184:     return;
 2185: }
 2186: 
 2187: sub submit_download_link {
 2188:     my ($request,$symb) = @_;
 2189:     if (!$symb) { return ''; }
 2190:     my $res_error;
 2191:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2192:         &response_type($symb,\$res_error);
 2193:     if ($res_error) {
 2194:         $request->print(&mt('An error occurred retrieving response types'));
 2195:         return;
 2196:     }
 2197:     unless ($numessay) {
 2198:         $request->print(&mt('No essayresponse items found'));
 2199:         return;
 2200:     }
 2201:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2202:     if (@chosenparts) {
 2203:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2204:                                           undef,undef,1));
 2205:     }
 2206:     if ($numessay) {
 2207:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2208:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2209:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2210:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2211:         if (ref($fullname) eq 'HASH') {
 2212:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2213:             if (@students) {
 2214:                 @{$env{'form.stuinfo'}} = @students;
 2215:                 if ($numdropbox) {
 2216:                     &download_all_link($request,$symb);
 2217:                 } else {
 2218:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2219:                 }
 2220: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2221: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2222:             } else {
 2223:                 $request->print(&mt('No students match the criteria you selected'));
 2224:             }
 2225:         } else {
 2226:             $request->print(&mt('Could not retrieve student information'));
 2227:         }
 2228:     } else {
 2229:         $request->print(&mt('No essayresponse items found'));
 2230:     }
 2231:     return;
 2232: }
 2233: 
 2234: sub build_section_inputs {
 2235:     my $section_inputs;
 2236:     if ($env{'form.section'} eq '') {
 2237:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2238:     } else {
 2239:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2240:         foreach my $section (@sections) {
 2241:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2242:         }
 2243:     }
 2244:     return $section_inputs;
 2245: }
 2246: 
 2247: # --------------------------- show submissions of a student, option to grade 
 2248: sub submission {
 2249:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2250:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2251:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2252:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2253:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2254: 
 2255:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2256:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2257:     my ($essayurl,%coursedesc_by_cid);
 2258: 
 2259:     if (!&canview($usec)) {
 2260:         $request->print(
 2261:             '<span class="LC_warning">'.
 2262:             &mt('Unable to view requested student.').
 2263:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2264:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2265:             '</span>');
 2266: 	return;
 2267:     }
 2268: 
 2269:     my $res_error;
 2270:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2271:         &response_type($symb,\$res_error);
 2272:     if ($res_error) {
 2273:         $request->print(&navmap_errormsg());
 2274:         return;
 2275:     }
 2276: 
 2277:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2278:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2279:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2280:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2281:         $env{'form.compmsg'} = 1;
 2282:     }
 2283:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2284:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2285: 	'" src="'.$request->dir_config('lonIconsURL').
 2286: 	'/check.gif" height="16" border="0" />';
 2287: 
 2288:     # header info
 2289:     if ($counter == 0) {
 2290:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2291:         if (@chosenparts) {
 2292:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2293:         } elsif ($divforres) {
 2294:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2295:         } else {
 2296:             $request->print('<br clear="all" />');
 2297:         }
 2298: 	&sub_page_js($request);
 2299:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2300: 	&sub_page_kw_js($request) if ($numessay);
 2301: 
 2302: 	# option to display problem, only once else it cause problems 
 2303:         # with the form later since the problem has a form.
 2304: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2305: 	    my $mode;
 2306: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2307: 		$mode='both';
 2308: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2309: 		$mode='text';
 2310: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2311: 		$mode='answer';
 2312: 	    }
 2313: 	    &Apache::lonxml::clear_problem_counter();
 2314: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2315: 	}
 2316: 
 2317: 	my %keyhash = ();
 2318: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2319: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2320: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2321: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2322: 	}
 2323: 	# kwclr is the only variable that is guaranteed not to be blank
 2324: 	# if this subroutine has been called once.
 2325: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2326: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2327: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2328: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2329: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2330: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2331: 	}
 2332: 	if ($env{'form.compmsg'}) {
 2333: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2334: 		$keyhash{$symb.'_subject'} : $probtitle;
 2335: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2336: 	}
 2337: 
 2338: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2339: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2340: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2341: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2342: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2343: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2344: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2345: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2346: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2347: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2348: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2349: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2350: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2351: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2352: 			&build_section_inputs().
 2353: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2354: 			'<input type="hidden" name="NCT"'.
 2355: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2356: 	if ($env{'form.compmsg'}) {
 2357: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2358: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2359: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2360: 	}
 2361: 	if ($numessay) {
 2362: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2363: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2364: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2365: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2366: 	}
 2367: 
 2368: 	my ($cts,$prnmsg) = (1,'');
 2369: 	while ($cts <= $env{'form.savemsgN'}) {
 2370: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2371: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2372: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2373: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2374: 		'" />'."\n".
 2375: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2376: 	    $cts++;
 2377: 	}
 2378: 	$request->print($prnmsg);
 2379: 
 2380: 	if ($numessay) {
 2381: 
 2382:             my %lt = &Apache::lonlocal::texthash(
 2383:                           keyh => 'Keyword Highlighting for Essays',
 2384:                           keyw => 'Keyword Options',
 2385:                           list => 'List',
 2386:                           past => 'Paste Selection to List',
 2387:                           high => 'Highlight Attribute',
 2388:                      );
 2389: #
 2390: # Print out the keyword options line
 2391: #
 2392: 	    $request->print(
 2393:                 '<div class="LC_columnSection">'
 2394:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2395:                .&Apache::lonhtmlcommon::funclist_from_array(
 2396:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2397:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2398:  class="page">'.$lt{'past'}.'</a>',
 2399:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2400:                     {legend => $lt{'keyw'}})
 2401:                .'</fieldset></div>'
 2402:             );
 2403: 
 2404: #
 2405: # Load the other essays for similarity check
 2406: #
 2407:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2408:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2409:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2410:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2411:                 if ($cdom ne '' && $cnum ne '') {
 2412:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2413:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2414:                         my $apath = $1.'_'.$id;
 2415:                         $apath=~s/\W/\_/gs;
 2416:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2417:                     }
 2418:                 }
 2419:             } else {
 2420: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2421: 	        $apath=&escape($apath);
 2422: 	        $apath=~s/\W/\_/gs;
 2423:                 &init_old_essays($symb,$apath,$adom,$aname);
 2424:             }
 2425:         }
 2426:     }
 2427: 
 2428: # This is where output for one specific student would start
 2429:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2430:     $request->print(
 2431:         "\n\n"
 2432:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2433:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2434:        ."\n"
 2435:     );
 2436: 
 2437:     # Show additional functions if allowed
 2438:     if ($perm{'vgr'}) {
 2439:         $request->print(
 2440:             &Apache::loncommon::track_student_link(
 2441:                 'View recent activity',
 2442:                 $uname,$udom,'check')
 2443:            .' '
 2444:         );
 2445:     }
 2446:     if ($perm{'opa'}) {
 2447:         $request->print(
 2448:             &Apache::loncommon::pprmlink(
 2449:                 &mt('Set/Change parameters'),
 2450:                 $uname,$udom,$symb,'check'));
 2451:     }
 2452: 
 2453:     # Show Problem
 2454:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2455: 	my $mode;
 2456: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2457: 	    $mode='both';
 2458: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2459: 	    $mode='text';
 2460: 	} elsif ($env{'form.vAns'} eq 'all') {
 2461: 	    $mode='answer';
 2462: 	}
 2463: 	&Apache::lonxml::clear_problem_counter();
 2464: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2465:     }
 2466: 
 2467:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2468: 
 2469:     # Display student info
 2470:     $request->print(($counter == 0 ? '' : '<br />'));
 2471: 
 2472:     my $result='<div class="LC_Box">'
 2473:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2474:     $result.='<input type="hidden" name="name'.$counter.
 2475:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2476:     if ($numresp > $numessay) {
 2477:         $result.='<p class="LC_info">'
 2478:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2479:                 ."</p>\n";
 2480:     }
 2481: 
 2482:     # If any part of the problem is an essayresponse, then check for collaborators
 2483:     my $fullname;
 2484:     my $col_fullnames = [];
 2485:     if ($numessay) {
 2486: 	(my $sub_result,$fullname,$col_fullnames)=
 2487: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2488: 				 $counter);
 2489: 	$result.=$sub_result;
 2490:     }
 2491:     $request->print($result."\n");
 2492: 
 2493:     # print student answer/submission
 2494:     # Options are (1) Last submission only
 2495:     #             (2) Last submission (with detailed information for that submission)
 2496:     #             (3) All transactions (by date)
 2497:     #             (4) The whole record (with detailed information for all transactions)
 2498: 
 2499:     my ($string,$timestamp)= &get_last_submission(\%record);
 2500: 
 2501:     my $lastsubonly;
 2502: 
 2503:     if ($$timestamp eq '') {
 2504:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2505:     } else {
 2506:         $lastsubonly =
 2507:             '<div class="LC_grade_submissions_body">'
 2508:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2509: 
 2510: 	my %seenparts;
 2511: 	my @part_response_id = &flatten_responseType($responseType);
 2512: 	foreach my $part (@part_response_id) {
 2513: 	    my ($partid,$respid) = @{ $part };
 2514: 	    my $display_part=&get_display_part($partid,$symb);
 2515: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2516: 		if (exists($seenparts{$partid})) { next; }
 2517: 		$seenparts{$partid}=1;
 2518:                 $request->print(
 2519:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2520:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2521:                                '<a href="javascript:viewSubmitter(\''.
 2522:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2523:                                '\');" target="_self">'.
 2524:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2525:                     '<br />');
 2526: 		next;
 2527: 	    }
 2528: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2529: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2530:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2531:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2532:                     ' <span class="LC_internal_info">'.
 2533:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2534:                     '</span>&nbsp; &nbsp;'.
 2535: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2536: 		next;
 2537: 	    }
 2538: 	    foreach my $submission (@$string) {
 2539: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2540: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2541: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2542: 		# Similarity check
 2543:                 my $similar='';
 2544:                 my ($type,$trial,$rndseed);
 2545:                 if ($hide eq 'rand') {
 2546:                     $type = 'randomizetry';
 2547:                     $trial = $record{"resource.$partid.tries"};
 2548:                     $rndseed = $record{"resource.$partid.rndseed"};
 2549:                 }
 2550: 		if ($env{'form.checkPlag'}) {
 2551: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2552: 		        &most_similar($uname,$udom,$symb,$subval);
 2553: 		    if ($osim) {
 2554: 		        $osim=int($osim*100.0);
 2555:                         if ($hide eq 'anon') {
 2556:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2557:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2558:                         } else {
 2559: 			    $similar='<hr />';
 2560:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2561:                                 $similar .= '<h3><span class="LC_warning">'.
 2562:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2563:                                                 $osim,
 2564:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2565:                                             '</span></h3>';
 2566:                             } elsif ($ocrsid ne '') {
 2567:                                 my %old_course_desc;
 2568:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2569:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2570:                                 } else {
 2571:                                     my $args;
 2572:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2573:                                         $args = {'one_time' => 1};
 2574:                                     }
 2575:                                     %old_course_desc =
 2576:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2577:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2578:                                 }
 2579:                                 $similar .=
 2580:                                     '<h3><span class="LC_warning">'.
 2581: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2582: 				        $osim,
 2583: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2584: 				        $old_course_desc{'description'},
 2585: 				        $old_course_desc{'num'},
 2586: 				        $old_course_desc{'domain'}).
 2587: 				    '</span></h3>';
 2588:                             } else {
 2589:                                 $similar .=
 2590:                                     '<h3><span class="LC_warning">'.
 2591:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2592:                                         $osim,
 2593:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2594:                                     '</span></h3>';
 2595:                             }
 2596:                             $similar .= '<blockquote><i>'.
 2597:                                         &keywords_highlight($oessay).
 2598:                                         '</i></blockquote><hr />';
 2599: 		        }
 2600:                     }
 2601:                 }
 2602: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2603:                                      undef,$type,$trial,$rndseed);
 2604:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2605:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2606:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2607: 		    my $display_part=&get_display_part($partid,$symb);
 2608:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2609:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2610:                         ' <span class="LC_internal_info">'.
 2611:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2612:                         '</span>&nbsp; &nbsp;';
 2613: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2614: 		    if (@$files) {
 2615:                         if ($hide eq 'anon') {
 2616:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2617:                         } else {
 2618:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2619:                                          .'<br /><span class="LC_warning">';
 2620:                             if(@$files == 1) {
 2621:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2622:                             } else {
 2623:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2624:                             }
 2625:                             $lastsubonly .= '</span>';
 2626:                             foreach my $file (@$files) {
 2627:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2628:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2629:                             }
 2630:                         }
 2631: 			$lastsubonly.='<br />';
 2632: 		    }
 2633:                     if ($hide eq 'anon') {
 2634:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2635:                     } else {
 2636:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2637:                         if ($draft) {
 2638:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2639:                         }
 2640:                         $subval =
 2641: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2642: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2643:                         if ($responsetype eq 'essay') {
 2644:                             $subval =~ s{\n}{<br />}g;
 2645:                         }
 2646:                         $lastsubonly.=$subval."\n";
 2647:                     }
 2648:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2649: 		    $lastsubonly.='</div>';
 2650: 		}
 2651: 	    }
 2652: 	}
 2653: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2654:     }
 2655:     $request->print($lastsubonly);
 2656:     if ($env{'form.lastSub'} eq 'datesub') {
 2657:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2658: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2659:     }
 2660:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2661:         my $identifier = (&canmodify($usec)? $counter : '');
 2662: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2663: 								 $env{'request.course.id'},
 2664: 								 $last,'.submission',
 2665: 								 'Apache::grades::keywords_highlight',
 2666:                                                                  $usec,$identifier));
 2667:     }
 2668:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2669: 	.$udom.'" />'."\n");
 2670:     # return if view submission with no grading option
 2671:     if (!&canmodify($usec)) {
 2672:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2673:         return;
 2674:     } else {
 2675: 	$request->print('</div>'."\n");
 2676:     }
 2677: 
 2678:     # grading message center
 2679: 
 2680:     if ($env{'form.compmsg'}) {
 2681:         my $result='<div class="LC_Box">'.
 2682:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2683:                    '<div class="LC_grade_message_center_body">';
 2684:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2685:         my $msgfor = $givenn.' '.$lastname;
 2686:         if (scalar(@$col_fullnames) > 0) {
 2687:             my $lastone = pop(@$col_fullnames);
 2688:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2689:         }
 2690:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2691:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2692:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2693: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2694:                  ',\''.$msgfor.'\');" target="_self">'.
 2695:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2696:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2697:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2698:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2699:                  '<br />&nbsp;('.
 2700:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2701: 	         '</div></div>';
 2702:         $request->print($result);
 2703:     }
 2704: 
 2705:     my %seen = ();
 2706:     my @partlist;
 2707:     my @gradePartRespid;
 2708:     my @part_response_id = &flatten_responseType($responseType);
 2709:     $request->print(
 2710:         '<div class="LC_Box">'
 2711:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2712:     );
 2713:     $request->print(&gradeBox_start());
 2714:     foreach my $part_response_id (@part_response_id) {
 2715:     	my ($partid,$respid) = @{ $part_response_id };
 2716: 	my $part_resp = join('_',@{ $part_response_id });
 2717: 	next if ($seen{$partid} > 0);
 2718: 	$seen{$partid}++;
 2719: 	push(@partlist,$partid);
 2720: 	push(@gradePartRespid,$partid.'.'.$respid);
 2721: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2722:     }
 2723:     $request->print(&gradeBox_end()); # </div>
 2724:     $request->print('</div>');
 2725: 
 2726:     $request->print('<div class="LC_grade_info_links">');
 2727:     $request->print('</div>');
 2728: 
 2729:     $result='<input type="hidden" name="partlist'.$counter.
 2730: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2731:     $result.='<input type="hidden" name="gradePartRespid'.
 2732: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2733:     my $ctr = 0;
 2734:     while ($ctr < scalar(@partlist)) {
 2735: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2736: 	    $partlist[$ctr].'" />'."\n";
 2737: 	$ctr++;
 2738:     }
 2739:     $request->print($result.''."\n");
 2740: 
 2741: # Done with printing info for one student
 2742: 
 2743:     $request->print('</div>');#LC_grade_show_user
 2744: 
 2745: 
 2746:     # print end of form
 2747:     if ($counter == $total) {
 2748:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2749: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2750: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2751: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2752: 	my $ntstu ='<select name="NTSTU">'.
 2753: 	    '<option>1</option><option>2</option>'.
 2754: 	    '<option>3</option><option>5</option>'.
 2755: 	    '<option>7</option><option>10</option></select>'."\n";
 2756: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2757: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2758:         $endform.=&mt('[_1]student(s)',$ntstu);
 2759: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2760: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2761: 	    '<input type="button" value="'.&mt('Next').'" '.
 2762: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2763:         $endform.='<span class="LC_warning">'.
 2764:                   &mt('(Next and Previous (student) do not save the scores.)').
 2765:                   '</span>'."\n" ;
 2766:         $endform.="<input type='hidden' value='".&get_increment().
 2767:             "' name='increment' />";
 2768: 	$endform.='</td></tr></table></form>';
 2769: 	$request->print($endform);
 2770:     }
 2771:     return '';
 2772: }
 2773: 
 2774: sub check_collaborators {
 2775:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2776:     my ($result,@col_fullnames);
 2777:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2778:     foreach my $part (keys(%$handgrade)) {
 2779: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2780: 					'.maxcollaborators',
 2781: 					$symb,$udom,$uname);
 2782: 	next if ($ncol <= 0);
 2783: 	$part =~ s/\_/\./g;
 2784: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2785: 	my (@good_collaborators, @bad_collaborators);
 2786: 	foreach my $possible_collaborator
 2787: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2788: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2789: 	    next if ($possible_collaborator eq '');
 2790: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2791: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2792: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2793: 	    # Doing this grep allows 'fuzzy' specification
 2794: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2795: 			       keys(%$classlist));
 2796: 	    if (! scalar(@matches)) {
 2797: 		push(@bad_collaborators, $possible_collaborator);
 2798: 	    } else {
 2799: 		push(@good_collaborators, @matches);
 2800: 	    }
 2801: 	}
 2802: 	if (scalar(@good_collaborators) != 0) {
 2803: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2804: 	    foreach my $name (@good_collaborators) {
 2805: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2806: 		push(@col_fullnames, $givenn.' '.$lastname);
 2807: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2808: 	    }
 2809: 	    $result.='</ol><br />'."\n";
 2810: 	    my ($part)=split(/\./,$part);
 2811: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2812: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2813: 		"\n";
 2814: 	}
 2815: 	if (scalar(@bad_collaborators) > 0) {
 2816: 	    $result.='<div class="LC_warning">';
 2817: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2818: 	    $result .= '</div>';
 2819: 	}         
 2820: 	if (scalar(@bad_collaborators > $ncol)) {
 2821: 	    $result .= '<div class="LC_warning">';
 2822: 	    $result .= &mt('This student has submitted too many '.
 2823: 		'collaborators.  Maximum is [_1].',$ncol);
 2824: 	    $result .= '</div>';
 2825: 	}
 2826:     }
 2827:     return ($result,$fullname,\@col_fullnames);
 2828: }
 2829: 
 2830: #--- Retrieve the last submission for all the parts
 2831: sub get_last_submission {
 2832:     my ($returnhash)=@_;
 2833:     my (@string,$timestamp,%lasthidden);
 2834:     if ($$returnhash{'version'}) {
 2835: 	my %lasthash=();
 2836: 	my ($version);
 2837: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2838: 	    foreach my $key (sort(split(/\:/,
 2839: 					$$returnhash{$version.':keys'}))) {
 2840: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2841: 		$timestamp = 
 2842: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2843: 	    }
 2844: 	}
 2845:         my (%typeparts,%randombytry);
 2846:         my $showsurv = 
 2847:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2848:         foreach my $key (sort(keys(%lasthash))) {
 2849:             if ($key =~ /\.type$/) {
 2850:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2851:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2852:                     ($lasthash{$key} eq 'randomizetry')) {
 2853:                     my ($ign,@parts) = split(/\./,$key);
 2854:                     pop(@parts);
 2855:                     my $id = join('.',@parts);
 2856:                     if ($lasthash{$key} eq 'randomizetry') {
 2857:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2858:                     } else {
 2859:                         unless ($showsurv) {
 2860:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2861:                         }
 2862:                     }
 2863:                     delete($lasthash{$key});
 2864:                 }
 2865:             }
 2866:         }
 2867:         my @hidden = keys(%typeparts);
 2868:         my @randomize = keys(%randombytry);
 2869: 	foreach my $key (keys(%lasthash)) {
 2870: 	    next if ($key !~ /\.submission$/);
 2871:             my $hide;
 2872:             if (@hidden) {
 2873:                 foreach my $id (@hidden) {
 2874:                     if ($key =~ /^\Q$id\E/) {
 2875:                         $hide = 'anon';
 2876:                         last;
 2877:                     }
 2878:                 }
 2879:             }
 2880:             unless ($hide) {
 2881:                 if (@randomize) {
 2882:                     foreach my $id (@randomize) {
 2883:                         if ($key =~ /^\Q$id\E/) {
 2884:                             $hide = 'rand';
 2885:                             last;
 2886:                         }
 2887:                     }
 2888:                 }
 2889:             }
 2890: 	    my ($partid,$foo) = split(/submission$/,$key);
 2891: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2892:             push(@string, join(':', $key, $hide, $draft, (
 2893:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2894:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2895: 	}
 2896:     }
 2897:     if (!@string) {
 2898: 	$string[0] =
 2899: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2900:     }
 2901:     return (\@string,\$timestamp);
 2902: }
 2903: 
 2904: #--- High light keywords, with style choosen by user.
 2905: sub keywords_highlight {
 2906:     my $string    = shift;
 2907:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2908:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2909:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2910:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2911:     foreach my $keyword (@keylist) {
 2912: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2913:     }
 2914:     return $string;
 2915: }
 2916: 
 2917: # For Tasks provide a mechanism to display previous version for one specific student
 2918: 
 2919: sub show_previous_task_version {
 2920:     my ($request,$symb) = @_;
 2921:     if ($symb eq '') {
 2922:         $request->print(
 2923:             '<span class="LC_error">'.
 2924:             &mt('Unable to handle ambiguous references.').
 2925:             '</span>');
 2926:         return '';
 2927:     }
 2928:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2929:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2930:     if (!&canview($usec)) {
 2931:         $request->print('<span class="LC_warning">'.
 2932:                         &mt('Unable to view previous version for requested student.').
 2933:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2934:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2935:                         '</span>');
 2936:         return;
 2937:     }
 2938:     my $mode = 'both';
 2939:     my $isTask = ($symb =~/\.task$/);
 2940:     if ($isTask) {
 2941:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2942:             if ($env{'form.fullname'} eq '') {
 2943:                 $env{'form.fullname'} =
 2944:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2945:             }
 2946:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2947:             $request->print("\n\n".
 2948:                             '<div class="LC_grade_show_user">'.
 2949:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2950:                             '</h2>'."\n");
 2951:             &Apache::lonxml::clear_problem_counter();
 2952:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2953:                             {'previousversion' => $env{'form.previousversion'} }));
 2954:             $request->print("\n</div>");
 2955:         }
 2956:     }
 2957:     return;
 2958: }
 2959: 
 2960: sub choose_task_version_form {
 2961:     my ($symb,$uname,$udom,$nomenu) = @_;
 2962:     my $isTask = ($symb =~/\.task$/);
 2963:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2964:     if ($isTask) {
 2965:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2966:                                               $udom,$uname);
 2967:         if (($record{'resource.0.version'} eq '') ||
 2968:             ($record{'resource.0.version'} < 2)) {
 2969:             return ($record{'resource.0.version'},
 2970:                     $record{'resource.0.version'},$result,$js);
 2971:         } else {
 2972:             $current = $record{'resource.0.version'};
 2973:         }
 2974:         if ($env{'form.previousversion'}) {
 2975:             $displayed = $env{'form.previousversion'};
 2976:             $rowtitle = &mt('Choose another version:')
 2977:         } else {
 2978:             $displayed = $current;
 2979:             $rowtitle = &mt('Show earlier version:');
 2980:         }
 2981:         $result = '<div class="LC_left_float">';
 2982:         my $list;
 2983:         my $numversions = 0;
 2984:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2985:             if ($i == $current) {
 2986:                 if (!$env{'form.previousversion'} || $nomenu) {
 2987:                     next;
 2988:                 } else {
 2989:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2990:                     $numversions ++;
 2991:                 }
 2992:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2993:                 unless ($i == $env{'form.previousversion'}) {
 2994:                     $numversions ++;
 2995:                 }
 2996:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2997:             }
 2998:         }
 2999:         if ($numversions) {
 3000:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3001:             $result .=
 3002:                 '<form name="getprev" method="post" action=""'.
 3003:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3004:                 &Apache::loncommon::start_data_table().
 3005:                 &Apache::loncommon::start_data_table_row().
 3006:                 '<th align="left">'.$rowtitle.'</th>'.
 3007:                 '<td><select name="version">'.
 3008:                 '<option>'.&mt('Select').'</option>'.
 3009:                 $list.
 3010:                 '</select></td>'.
 3011:                 &Apache::loncommon::end_data_table_row();
 3012:             unless ($nomenu) {
 3013:                 $result .= &Apache::loncommon::start_data_table_row().
 3014:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3015:                 '<td><span class="LC_nobreak">'.
 3016:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3017:                 &mt('Yes').'</label>'.
 3018:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3019:                 '</span></td>'.
 3020:                 &Apache::loncommon::end_data_table_row();
 3021:             }
 3022:             $result .=
 3023:                 &Apache::loncommon::start_data_table_row().
 3024:                 '<th align="left">&nbsp;</th>'.
 3025:                 '<td>'.
 3026:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3027:                 '</td>'.
 3028:                 &Apache::loncommon::end_data_table_row().
 3029:                 &Apache::loncommon::end_data_table().
 3030:                 '</form>';
 3031:             $js = &previous_display_javascript($nomenu,$current);
 3032:         } elsif ($displayed && $nomenu) {
 3033:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3034:         } else {
 3035:             $result .= &mt('No previous versions to show for this student');
 3036:         }
 3037:         $result .= '</div>';
 3038:     }
 3039:     return ($current,$displayed,$result,$js);
 3040: }
 3041: 
 3042: sub previous_display_javascript {
 3043:     my ($nomenu,$current) = @_;
 3044:     my $js = <<"JSONE";
 3045: <script type="text/javascript">
 3046: // <![CDATA[
 3047: function previousVersion(uname,udom,symb) {
 3048:     var current = '$current';
 3049:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3050:     var prevstr = new RegExp("^\\\\d+\$");
 3051:     if (!prevstr.test(version)) {
 3052:         return false;
 3053:     }
 3054:     var url = '';
 3055:     if (version == current) {
 3056:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3057:     } else {
 3058:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3059:     }
 3060: JSONE
 3061:     if ($nomenu) {
 3062:         $js .= <<"JSTWO";
 3063:     document.location.href = url;
 3064: JSTWO
 3065:     } else {
 3066:         $js .= <<"JSTHREE";
 3067:     var newwin = 0;
 3068:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3069:         if (document.getprev.prevwin[i].checked == true) {
 3070:             newwin = document.getprev.prevwin[i].value;
 3071:         }
 3072:     }
 3073:     if (newwin == 1) {
 3074:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3075:         url = url+'&inhibitmenu=yes';
 3076:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3077:             previousWin = window.open(url,'',options,1);
 3078:         } else {
 3079:             previousWin.location.href = url;
 3080:         }
 3081:         previousWin.focus();
 3082:         return false;
 3083:     } else {
 3084:         document.location.href = url;
 3085:         return false;
 3086:     }
 3087: JSTHREE
 3088:     }
 3089:     $js .= <<"ENDJS";
 3090:     return false;
 3091: }
 3092: // ]]>
 3093: </script>
 3094: ENDJS
 3095: 
 3096: }
 3097: 
 3098: #--- Called from submission routine
 3099: sub processHandGrade {
 3100:     my ($request,$symb) = @_;
 3101:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3102:     my $button = $env{'form.gradeOpt'};
 3103:     my $ngrade = $env{'form.NCT'};
 3104:     my $ntstu  = $env{'form.NTSTU'};
 3105:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3106:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3107: 
 3108:     if ($button eq 'Save & Next') {
 3109: 	my $ctr = 0;
 3110: 	while ($ctr < $ngrade) {
 3111: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3112: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3113:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3114: 	    if ($errorflag eq 'no_score') {
 3115: 		$ctr++;
 3116: 		next;
 3117: 	    }
 3118: 	    if ($errorflag eq 'not_allowed') {
 3119:                 $request->print(
 3120:                     '<span class="LC_error">'
 3121:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3122:                    .'</span>');
 3123: 		$ctr++;
 3124: 		next;
 3125: 	    }
 3126:             if ($numhidden) {
 3127:                 $request->print(
 3128:                     '<span class="LC_info">'
 3129:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3130:                    .'</span><br />');
 3131:             }
 3132: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3133: 	    my ($subject,$message,$msgstatus) = ('','','');
 3134: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3135:             my ($feedurl,$showsymb) =
 3136: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3137: 	    my $messagetail;
 3138: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3139: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3140: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3141: 		$subject.=' ['.$restitle.']';
 3142: 		my (@msgnum) = split(/,/,$includemsg);
 3143: 		foreach (@msgnum) {
 3144: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3145: 		}
 3146: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3147: 		if ($env{'form.withgrades'.$ctr}) {
 3148: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3149: 		    $messagetail = " for <a href=\"".
 3150: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3151: 		}
 3152: 		$msgstatus = 
 3153:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3154: 						     $message.$messagetail,
 3155:                                                      undef,$feedurl,undef,
 3156:                                                      undef,undef,$showsymb,
 3157:                                                      $restitle);
 3158: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3159: 				$msgstatus.'<br />');
 3160: 	    }
 3161: 	    if ($env{'form.collaborator'.$ctr}) {
 3162: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3163: 		foreach my $collabstr (@collabstrs) {
 3164: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3165: 		    foreach my $collaborator (@collaborators) {
 3166: 			my ($errorflag,$pts,$wgt) = 
 3167: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3168: 					   $env{'form.unamedom'.$ctr},$part);
 3169: 			if ($errorflag eq 'not_allowed') {
 3170: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3171: 			    next;
 3172: 			} elsif ($message ne '') {
 3173: 			    my ($baseurl,$showsymb) = 
 3174: 				&get_feedurl_and_symb($symb,$collaborator,
 3175: 						      $udom);
 3176: 			    if ($env{'form.withgrades'.$ctr}) {
 3177: 				$messagetail = " for <a href=\"".
 3178:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3179: 			    }
 3180: 			    $msgstatus = 
 3181: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3182: 			}
 3183: 		    }
 3184: 		}
 3185: 	    }
 3186: 	    $ctr++;
 3187: 	}
 3188:     }
 3189: 
 3190:     my $res_error;
 3191:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3192:     if ($res_error) {
 3193:         $request->print(&navmap_errormsg());
 3194:         return;
 3195:     }
 3196: 
 3197:     my %keyhash = ();
 3198:     if ($numessay) {
 3199: 	# Keywords sorted in alphabatical order
 3200: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3201: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3202: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3203: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3204: 	$env{'form.keywords'} = join(' ',@keywords);
 3205: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3206: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3207: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3208: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3209: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3210:     }
 3211: 
 3212:     if ($env{'form.compmsg'}) {
 3213: 	# message center - Order of message gets changed. Blank line is eliminated.
 3214: 	# New messages are saved in env for the next student.
 3215: 	# All messages are saved in nohist_handgrade.db
 3216: 	my ($ctr,$idx) = (1,1);
 3217: 	while ($ctr <= $env{'form.savemsgN'}) {
 3218: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3219: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3220: 		$idx++;
 3221: 	    }
 3222: 	    $ctr++;
 3223: 	}
 3224: 	$ctr = 0;
 3225: 	while ($ctr < $ngrade) {
 3226: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3227: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3228: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3229: 		$idx++;
 3230: 	    }
 3231: 	    $ctr++;
 3232: 	}
 3233: 	$env{'form.savemsgN'} = --$idx;
 3234: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3235:     }
 3236:     if (($numessay) || ($env{'form.compmsg'})) {
 3237: 	my $putresult = &Apache::lonnet::put
 3238: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3239:     }
 3240: 
 3241:     # Called by Save & Refresh from Highlight Attribute Window
 3242:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3243:     if ($env{'form.refresh'} eq 'on') {
 3244: 	my ($ctr,$total) = (0,0);
 3245: 	while ($ctr < $ngrade) {
 3246: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3247: 	    $ctr++;
 3248: 	}
 3249: 	$env{'form.NTSTU'}=$ngrade;
 3250: 	$ctr = 0;
 3251: 	while ($ctr < $total) {
 3252: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3253: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3254: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3255: 	    &submission($request,$ctr,$total-1,$symb);
 3256: 	    $ctr++;
 3257: 	}
 3258: 	return '';
 3259:     }
 3260: 
 3261:     # Get the next/previous one or group of students
 3262:     my $firststu = $env{'form.unamedom0'};
 3263:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3264:     my $ctr = 2;
 3265:     while ($laststu eq '') {
 3266: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3267: 	$ctr++;
 3268: 	$laststu = $firststu if ($ctr > $ngrade);
 3269:     }
 3270: 
 3271:     my (@parsedlist,@nextlist);
 3272:     my ($nextflg) = 0;
 3273:     foreach my $item (sort 
 3274: 	     {
 3275: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3276: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3277: 		 }
 3278: 		 return $a cmp $b;
 3279: 	     } (keys(%$fullname))) {
 3280: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3281: 	    push(@parsedlist,$item);
 3282: 	}
 3283: 	$nextflg = 1 if ($item eq $laststu);
 3284: 	if ($button eq 'Previous') {
 3285: 	    last if ($item eq $firststu);
 3286: 	    push(@parsedlist,$item);
 3287: 	}
 3288:     }
 3289:     $ctr = 0;
 3290:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3291:     foreach my $student (@parsedlist) {
 3292: 	my $submitonly=$env{'form.submitonly'};
 3293: 	my ($uname,$udom) = split(/:/,$student);
 3294: 	
 3295: 	if ($submitonly eq 'queued') {
 3296: 	    my %queue_status = 
 3297: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3298: 							$udom,$uname);
 3299: 	    next if (!defined($queue_status{'gradingqueue'}));
 3300: 	}
 3301: 
 3302: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3303: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3304: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3305: 	    my $submitted = 0;
 3306: 	    my $ungraded = 0;
 3307: 	    my $incorrect = 0;
 3308: 	    foreach my $item (keys(%status)) {
 3309: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3310: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3311: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3312: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3313: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3314: 		    $submitted = 0;
 3315: 		}
 3316: 	    }
 3317: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3318: 				     $submitonly eq 'incorrect' ||
 3319: 				     $submitonly eq 'graded'));
 3320: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3321: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3322: 	}
 3323: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3324: 	last if ($ctr == $ntstu);
 3325: 	$ctr++;
 3326:     }
 3327: 
 3328:     $ctr = 0;
 3329:     my $total = scalar(@nextlist)-1;
 3330: 
 3331:     foreach (sort(@nextlist)) {
 3332: 	my ($uname,$udom,$submitter) = split(/:/);
 3333: 	$env{'form.student'}  = $uname;
 3334: 	$env{'form.userdom'}  = $udom;
 3335: 	$env{'form.fullname'} = $$fullname{$_};
 3336: 	&submission($request,$ctr,$total,$symb);
 3337: 	$ctr++;
 3338:     }
 3339:     if ($total < 0) {
 3340:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3341: 	$request->print($the_end);
 3342:     }
 3343:     return '';
 3344: }
 3345: 
 3346: #---- Save the score and award for each student, if changed
 3347: sub saveHandGrade {
 3348:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3349:     my @version_parts;
 3350:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3351: 					   $env{'request.course.id'});
 3352:     if (!&canmodify($usec)) { return('not_allowed'); }
 3353:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3354:     my @parts_graded;
 3355:     my %newrecord  = ();
 3356:     my ($pts,$wgt,$totchg) = ('','',0);
 3357:     my %aggregate = ();
 3358:     my $aggregateflag = 0;
 3359:     if ($env{'form.HIDE'.$newflg}) {
 3360:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3361:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3362:         $totchg += $numchgs;
 3363:     }
 3364:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3365:     foreach my $new_part (@parts) {
 3366: 	#collaborator ($submi may vary for different parts
 3367: 	if ($submitter && $new_part ne $part) { next; }
 3368: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3369: 	if ($dropMenu eq 'excused') {
 3370: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3371: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3372: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3373: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3374: 		}
 3375: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3376: 	    }
 3377: 	} elsif ($dropMenu eq 'reset status'
 3378: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3379: 	    foreach my $key (keys(%record)) {
 3380: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3381: 	    }
 3382: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3383: 		"$env{'user.name'}:$env{'user.domain'}";
 3384:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3385: 
 3386:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3387: 					       [$new_part]);
 3388:             my $aggtries =$totaltries;
 3389:             if ($last_resets{$new_part}) {
 3390:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3391: 					   $new_part);
 3392:             }
 3393: 
 3394:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3395:             if ($aggtries > 0) {
 3396:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3397:                 $aggregateflag = 1;
 3398:             }
 3399: 	} elsif ($dropMenu eq '') {
 3400: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3401: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3402: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3403: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3404: 		next;
 3405: 	    }
 3406: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3407: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3408: 	    my $partial= $pts/$wgt;
 3409: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3410: 		#do not update score for part if not changed.
 3411:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3412: 		next;
 3413: 	    } else {
 3414: 	        push(@parts_graded,$new_part);
 3415: 	    }
 3416: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3417: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3418: 	    }
 3419: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3420: 	    if ($partial == 0) {
 3421: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3422: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3423: 		}
 3424: 	    } else {
 3425: 		if ($record{$reckey} ne 'correct_by_override') {
 3426: 		    $newrecord{$reckey} = 'correct_by_override';
 3427: 		}
 3428: 	    }	    
 3429: 	    if ($submitter && 
 3430: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3431: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3432: 	    }
 3433: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3434: 		"$env{'user.name'}:$env{'user.domain'}";
 3435: 	}
 3436: 	# unless problem has been graded, set flag to version the submitted files
 3437: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3438: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3439: 	        $dropMenu eq 'reset status')
 3440: 	   {
 3441: 	    push(@version_parts,$new_part);
 3442: 	}
 3443:     }
 3444:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3445:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3446: 
 3447:     if (%newrecord) {
 3448:         if (@version_parts) {
 3449:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3450:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3451: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3452: 	    foreach my $new_part (@version_parts) {
 3453: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3454: 				$new_part,\%newrecord);
 3455: 	    }
 3456:         }
 3457: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3458: 				$env{'request.course.id'},$domain,$stuname);
 3459: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3460: 				     $cdom,$cnum,$domain,$stuname);
 3461:     }
 3462:     if ($aggregateflag) {
 3463:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3464: 			      $cdom,$cnum);
 3465:     }
 3466:     return ('',$pts,$wgt,$totchg);
 3467: }
 3468: 
 3469: sub makehidden {
 3470:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3471:     return unless (ref($record) eq 'HASH');
 3472:     my %modified;
 3473:     my $numchanged = 0;
 3474:     if (exists($record->{$version.':keys'})) {
 3475:         my $partsregexp = $parts;
 3476:         $partsregexp =~ s/,/|/g;
 3477:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3478:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3479:                  my $item = $1;
 3480:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3481:                      $modified{$key} = $record->{$version.':'.$key};
 3482:                  }
 3483:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3484:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3485:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3486:                 $modified{$key} = $record->{$version.':'.$key};
 3487:             }
 3488:         }
 3489:         if (keys(%modified)) {
 3490:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3491:                                           $domain,$stuname,$tolog) eq 'ok') {
 3492:                 $numchanged ++;
 3493:             }
 3494:         }
 3495:     }
 3496:     return $numchanged;
 3497: }
 3498: 
 3499: sub check_and_remove_from_queue {
 3500:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3501:     my @ungraded_parts;
 3502:     foreach my $part (@{$parts}) {
 3503: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3504: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3505: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3506: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3507: 		) {
 3508: 	    push(@ungraded_parts, $part);
 3509: 	}
 3510:     }
 3511:     if ( !@ungraded_parts ) {
 3512: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3513: 					       $cnum,$domain,$stuname);
 3514:     }
 3515: }
 3516: 
 3517: sub handback_files {
 3518:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3519:     my $portfolio_root = '/userfiles/portfolio';
 3520:     my $res_error;
 3521:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3522:     if ($res_error) {
 3523:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3524:         return;
 3525:     }
 3526:     my @handedback;
 3527:     my $file_msg;
 3528:     my @part_response_id = &flatten_responseType($responseType);
 3529:     foreach my $part_response_id (@part_response_id) {
 3530:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3531: 	my $part_resp = join('_',@{ $part_response_id });
 3532:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3533:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3534:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3535: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3536:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3537:                     my ($directory,$answer_file) = 
 3538:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3539:                     my ($answer_name,$answer_ver,$answer_ext) =
 3540: 		        &file_name_version_ext($answer_file);
 3541: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3542:                     my $getpropath = 1;
 3543:                     my ($dir_list,$listerror) =
 3544:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3545:                                                  $domain,$stuname,$getpropath);
 3546: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3547:                     # fix filename
 3548:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3549:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3550:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3551:             	                                $save_file_name);
 3552:                     if ($result !~ m|^/uploaded/|) {
 3553:                         $request->print('<br /><span class="LC_error">'.
 3554:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3555:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3556:                                         '</span>');
 3557:                     } else {
 3558:                         # mark the file as read only
 3559:                         push(@handedback,$save_file_name);
 3560: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3561: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3562: 			}
 3563:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3564: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3565: 
 3566:                     }
 3567:                     $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>'));
 3568:                 }
 3569:             }
 3570:         }
 3571:     }
 3572:     if (@handedback > 0) {
 3573:         $request->print('<br />');
 3574:         my @what = ($symb,$env{'request.course.id'},'handback');
 3575:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3576:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3577:         my ($subject,$message);
 3578:         if (scalar(@handedback) == 1) {
 3579:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3580:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3581:         } else {
 3582:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3583:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3584:         }
 3585:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3586:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3587:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3588:         my ($feedurl,$showsymb) =
 3589:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3590:         my $restitle = &Apache::lonnet::gettitle($symb);
 3591:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3592:         my $msgstatus =
 3593:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3594:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3595:                  $restitle);
 3596:         if ($msgstatus) {
 3597:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3598:         }
 3599:     }
 3600:     return;
 3601: }
 3602: 
 3603: sub get_feedurl_and_symb {
 3604:     my ($symb,$uname,$udom) = @_;
 3605:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3606:     $url = &Apache::lonnet::clutter($url);
 3607:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3608: 					$symb,$udom,$uname);
 3609:     if ($encrypturl =~ /^yes$/i) {
 3610: 	&Apache::lonenc::encrypted(\$url,1);
 3611: 	&Apache::lonenc::encrypted(\$symb,1);
 3612:     }
 3613:     return ($url,$symb);
 3614: }
 3615: 
 3616: sub get_submitted_files {
 3617:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3618:     my @files;
 3619:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3620:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3621:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3622:     	    push(@files,$file_url.$file);
 3623:         }
 3624:     }
 3625:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3626:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3627:     }
 3628:     return (\@files);
 3629: }
 3630: 
 3631: # ----------- Provides number of tries since last reset.
 3632: sub get_num_tries {
 3633:     my ($record,$last_reset,$part) = @_;
 3634:     my $timestamp = '';
 3635:     my $num_tries = 0;
 3636:     if ($$record{'version'}) {
 3637:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3638:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3639:                 $timestamp = $$record{$version.':timestamp'};
 3640:                 if ($timestamp > $last_reset) {
 3641:                     $num_tries ++;
 3642:                 } else {
 3643:                     last;
 3644:                 }
 3645:             }
 3646:         }
 3647:     }
 3648:     return $num_tries;
 3649: }
 3650: 
 3651: # ----------- Determine decrements required in aggregate totals 
 3652: sub decrement_aggs {
 3653:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3654:     my %decrement = (
 3655:                         attempts => 0,
 3656:                         users => 0,
 3657:                         correct => 0
 3658:                     );
 3659:     $decrement{'attempts'} = $aggtries;
 3660:     if ($solvedstatus =~ /^correct/) {
 3661:         $decrement{'correct'} = 1;
 3662:     }
 3663:     if ($aggtries == $totaltries) {
 3664:         $decrement{'users'} = 1;
 3665:     }
 3666:     foreach my $type (keys(%decrement)) {
 3667:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3668:     }
 3669:     return;
 3670: }
 3671: 
 3672: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3673: sub get_last_resets {
 3674:     my ($symb,$courseid,$partids) =@_;
 3675:     my %last_resets;
 3676:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3677:     my $cname = $env{'course.'.$courseid.'.num'};
 3678:     my @keys;
 3679:     foreach my $part (@{$partids}) {
 3680: 	push(@keys,"$symb\0$part\0resettime");
 3681:     }
 3682:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3683: 				     $cdom,$cname);
 3684:     foreach my $part (@{$partids}) {
 3685: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3686:     }
 3687:     return %last_resets;
 3688: }
 3689: 
 3690: # ----------- Handles creating versions for portfolio files as answers
 3691: sub version_portfiles {
 3692:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3693:     my $version_parts = join('|',@$v_flag);
 3694:     my @returned_keys;
 3695:     my $parts = join('|', @$parts_graded);
 3696:     my $portfolio_root = '/userfiles/portfolio';
 3697:     foreach my $key (keys(%$record)) {
 3698:         my $new_portfiles;
 3699:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3700:             my @versioned_portfiles;
 3701:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3702:             foreach my $file (@portfiles) {
 3703:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3704:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3705: 		my ($answer_name,$answer_ver,$answer_ext) =
 3706: 		    &file_name_version_ext($answer_file);
 3707:                 my $getpropath = 1;
 3708:                 my ($dir_list,$listerror) =
 3709:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3710:                                              $stu_name,$getpropath);
 3711:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3712:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3713:                 if ($new_answer ne 'problem getting file') {
 3714:                     push(@versioned_portfiles, $directory.$new_answer);
 3715:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3716:                         [$directory.$new_answer],
 3717:                         [$symb,$env{'request.course.id'},'graded']);
 3718:                 }
 3719:             }
 3720:             $$record{$key} = join(',',@versioned_portfiles);
 3721:             push(@returned_keys,$key);
 3722:         }
 3723:     } 
 3724:     return (@returned_keys);   
 3725: }
 3726: 
 3727: sub get_next_version {
 3728:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3729:     my $version;
 3730:     if (ref($dir_list) eq 'ARRAY') {
 3731:         foreach my $row (@{$dir_list}) {
 3732:             my ($file) = split(/\&/,$row,2);
 3733:             my ($file_name,$file_version,$file_ext) =
 3734: 	        &file_name_version_ext($file);
 3735:             if (($file_name eq $answer_name) && 
 3736: 	        ($file_ext eq $answer_ext)) {
 3737:                 # gets here if filename and extension match, 
 3738:                 # regardless of version
 3739:                 if ($file_version ne '') {
 3740:                     # a versioned file is found  so save it for later
 3741:                     if ($file_version > $version) {
 3742: 		        $version = $file_version;
 3743:                     }
 3744: 	        }
 3745:             }
 3746:         }
 3747:     }
 3748:     $version ++;
 3749:     return($version);
 3750: }
 3751: 
 3752: sub version_selected_portfile {
 3753:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3754:     my ($answer_name,$answer_ver,$answer_ext) =
 3755:         &file_name_version_ext($file_name);
 3756:     my $new_answer;
 3757:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3758:     if($env{'form.copy'} eq '-1') {
 3759:         $new_answer = 'problem getting file';
 3760:     } else {
 3761:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3762:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3763:                             $stu_name,$domain,'copy',
 3764: 		        '/portfolio'.$directory.$new_answer);
 3765:     }    
 3766:     return ($new_answer);
 3767: }
 3768: 
 3769: sub file_name_version_ext {
 3770:     my ($file)=@_;
 3771:     my @file_parts = split(/\./, $file);
 3772:     my ($name,$version,$ext);
 3773:     if (@file_parts > 1) {
 3774: 	$ext=pop(@file_parts);
 3775: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3776: 	    $version=pop(@file_parts);
 3777: 	}
 3778: 	$name=join('.',@file_parts);
 3779:     } else {
 3780: 	$name=join('.',@file_parts);
 3781:     }
 3782:     return($name,$version,$ext);
 3783: }
 3784: 
 3785: #--------------------------------------------------------------------------------------
 3786: #
 3787: #-------------------------- Next few routines handles grading by section or whole class
 3788: #
 3789: #--- Javascript to handle grading by section or whole class
 3790: sub viewgrades_js {
 3791:     my ($request) = shift;
 3792: 
 3793:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3794:     &js_escape(\$alertmsg);
 3795:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3796:    function writePoint(partid,weight,point) {
 3797: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3798: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3799: 	if (point == "textval") {
 3800: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3801: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3802: 		alert("$alertmsg"+parseFloat(point));
 3803: 		var resetbox = false;
 3804: 		for (var i=0; i<radioButton.length; i++) {
 3805: 		    if (radioButton[i].checked) {
 3806: 			textbox.value = i;
 3807: 			resetbox = true;
 3808: 		    }
 3809: 		}
 3810: 		if (!resetbox) {
 3811: 		    textbox.value = "";
 3812: 		}
 3813: 		return;
 3814: 	    }
 3815: 	    if (parseFloat(point) > parseFloat(weight)) {
 3816: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3817: 				   ") greater than the weight for the part. Accept?");
 3818: 		if (resp == false) {
 3819: 		    textbox.value = "";
 3820: 		    return;
 3821: 		}
 3822: 	    }
 3823: 	    for (var i=0; i<radioButton.length; i++) {
 3824: 		radioButton[i].checked=false;
 3825: 		if (parseFloat(point) == i) {
 3826: 		    radioButton[i].checked=true;
 3827: 		}
 3828: 	    }
 3829: 
 3830: 	} else {
 3831: 	    textbox.value = parseFloat(point);
 3832: 	}
 3833: 	for (i=0;i<document.classgrade.total.value;i++) {
 3834: 	    var user = document.classgrade["ctr"+i].value;
 3835: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3836: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3837: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3838: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3839: 	    if (saveval != "correct") {
 3840: 		scorename.value = point;
 3841: 		if (selname[0].selected != true) {
 3842: 		    selname[0].selected = true;
 3843: 		}
 3844: 	    }
 3845: 	}
 3846: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3847:     }
 3848: 
 3849:     function writeRadText(partid,weight) {
 3850: 	var selval   = document.classgrade["SELVAL_"+partid];
 3851: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3852:         var override = document.classgrade["FORCE_"+partid].checked;
 3853: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3854: 	if (selval[1].selected || selval[2].selected) {
 3855: 	    for (var i=0; i<radioButton.length; i++) {
 3856: 		radioButton[i].checked=false;
 3857: 
 3858: 	    }
 3859: 	    textbox.value = "";
 3860: 
 3861: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3862: 		var user = document.classgrade["ctr"+i].value;
 3863: 		user = user.replace(new RegExp(':', 'g'),"_");
 3864: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3865: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3866: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3867: 		if ((saveval != "correct") || override) {
 3868: 		    scorename.value = "";
 3869: 		    if (selval[1].selected) {
 3870: 			selname[1].selected = true;
 3871: 		    } else {
 3872: 			selname[2].selected = true;
 3873: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3874: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3875: 		    }
 3876: 		}
 3877: 	    }
 3878: 	} else {
 3879: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3880: 		var user = document.classgrade["ctr"+i].value;
 3881: 		user = user.replace(new RegExp(':', 'g'),"_");
 3882: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3883: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3884: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3885: 		if ((saveval != "correct") || override) {
 3886: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3887: 		    selname[0].selected = true;
 3888: 		}
 3889: 	    }
 3890: 	}	    
 3891:     }
 3892: 
 3893:     function changeSelect(partid,user) {
 3894: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3895: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3896: 	var point  = textbox.value;
 3897: 	var weight = document.classgrade["weight_"+partid].value;
 3898: 
 3899: 	if (isNaN(point) || parseFloat(point) < 0) {
 3900: 	    alert("$alertmsg"+parseFloat(point));
 3901: 	    textbox.value = "";
 3902: 	    return;
 3903: 	}
 3904: 	if (parseFloat(point) > parseFloat(weight)) {
 3905: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3906: 			       ") greater than the weight of the part. Accept?");
 3907: 	    if (resp == false) {
 3908: 		textbox.value = "";
 3909: 		return;
 3910: 	    }
 3911: 	}
 3912: 	selval[0].selected = true;
 3913:     }
 3914: 
 3915:     function changeOneScore(partid,user) {
 3916: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3917: 	if (selval[1].selected || selval[2].selected) {
 3918: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3919: 	    if (selval[2].selected) {
 3920: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3921: 	    }
 3922:         }
 3923:     }
 3924: 
 3925:     function resetEntry(numpart) {
 3926: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3927: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3928: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3929: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3930: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3931: 	    for (var i=0; i<radioButton.length; i++) {
 3932: 		radioButton[i].checked=false;
 3933: 
 3934: 	    }
 3935: 	    textbox.value = "";
 3936: 	    selval[0].selected = true;
 3937: 
 3938: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3939: 		var user = document.classgrade["ctr"+i].value;
 3940: 		user = user.replace(new RegExp(':', 'g'),"_");
 3941: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3942: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3943: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3944: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3945: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3946: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3947: 		if (saveselval == "excused") {
 3948: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3949: 		} else {
 3950: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3951: 		}
 3952: 	    }
 3953: 	}
 3954:     }
 3955: 
 3956: VIEWJAVASCRIPT
 3957: }
 3958: 
 3959: #--- show scores for a section or whole class w/ option to change/update a score
 3960: sub viewgrades {
 3961:     my ($request,$symb) = @_;
 3962:     &viewgrades_js($request);
 3963: 
 3964:     #need to make sure we have the correct data for later EXT calls, 
 3965:     #thus invalidate the cache
 3966:     &Apache::lonnet::devalidatecourseresdata(
 3967:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3968:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3969:     &Apache::lonnet::clear_EXT_cache_status();
 3970: 
 3971:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3972: 
 3973:     #view individual student submission form - called using Javascript viewOneStudent
 3974:     $result.=&jscriptNform($symb);
 3975: 
 3976:     #beginning of class grading form
 3977:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3978:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3979: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3980: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3981: 	&build_section_inputs().
 3982: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3983: 
 3984:     #retrieve selected groups
 3985:     my (@groups,$group_display);
 3986:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3987:     if (grep(/^all$/,@groups)) {
 3988:         @groups = ('all');
 3989:     } elsif (grep(/^none$/,@groups)) {
 3990:         @groups = ('none');
 3991:     } elsif (@groups > 0) {
 3992:         $group_display = join(', ',@groups);
 3993:     }
 3994: 
 3995:     my ($common_header,$specific_header,@sections,$section_display);
 3996:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3997:     if (grep(/^all$/,@sections)) {
 3998:         @sections = ('all');
 3999:         if ($group_display) {
 4000:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4001:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4002:         } elsif (grep(/^none$/,@groups)) {
 4003:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4004:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4005:         } else {
 4006:             $common_header = &mt('Assign Common Grade to Class');
 4007:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4008:         }
 4009:     } elsif (grep(/^none$/,@sections)) {
 4010:         @sections = ('none');
 4011:         if ($group_display) {
 4012:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4013:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4014:         } elsif (grep(/^none$/,@groups)) {
 4015:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4016:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4017:         } else {
 4018:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4019:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4020:         }
 4021:     } else {
 4022:         $section_display = join (", ",@sections);
 4023:         if ($group_display) {
 4024:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4025:                                  $section_display,$group_display);
 4026:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4027:                                    $section_display,$group_display);
 4028:         } elsif (grep(/^none$/,@groups)) {
 4029:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4030:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4031:         } else {
 4032:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4033:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4034:         }
 4035:     }
 4036:     my %submit_types = &substatus_options();
 4037:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4038: 
 4039:     if ($env{'form.submitonly'} eq 'all') {
 4040:         $result.= '<h3>'.$common_header.'</h3>';
 4041:     } else {
 4042:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 4043:     }
 4044:     $result .= &Apache::loncommon::start_data_table();
 4045:     #radio buttons/text box for assigning points for a section or class.
 4046:     #handles different parts of a problem
 4047:     my $res_error;
 4048:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4049:     if ($res_error) {
 4050:         return &navmap_errormsg();
 4051:     }
 4052:     my %weight = ();
 4053:     my $ctsparts = 0;
 4054:     my %seen = ();
 4055:     my @part_response_id = &flatten_responseType($responseType);
 4056:     foreach my $part_response_id (@part_response_id) {
 4057:     	my ($partid,$respid) = @{ $part_response_id };
 4058: 	my $part_resp = join('_',@{ $part_response_id });
 4059: 	next if $seen{$partid};
 4060: 	$seen{$partid}++;
 4061: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4062: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4063: 
 4064: 	my $display_part=&get_display_part($partid,$symb);
 4065: 	my $radio.='<table border="0"><tr>';  
 4066: 	my $ctr = 0;
 4067: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4068: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4069: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4070: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4071: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4072: 	    $ctr++;
 4073: 	}
 4074: 	$radio.='</tr></table>';
 4075: 	my $line = '<input type="text" name="TEXTVAL_'.
 4076: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4077: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4078: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4079: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4080:                 '<select name="SELVAL_'.$partid.'" '.
 4081: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4082: 		$weight{$partid}.')"> '.
 4083: 	    '<option selected="selected"> </option>'.
 4084: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4085: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4086: 	    '</select></td>'.
 4087:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4088: 	$line.='<input type="hidden" name="partid_'.
 4089: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4090: 	$line.='<input type="hidden" name="weight_'.
 4091: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4092: 
 4093: 	$result.=
 4094: 	    &Apache::loncommon::start_data_table_row()."\n".
 4095: 	    '<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>'.
 4096: 	    &Apache::loncommon::end_data_table_row()."\n";
 4097: 	$ctsparts++;
 4098:     }
 4099:     $result.=&Apache::loncommon::end_data_table()."\n".
 4100: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4101:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4102: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4103: 
 4104:     #table listing all the students in a section/class
 4105:     #header of table
 4106:     if ($env{'form.submitonly'} eq 'all') { 
 4107:         $result.= '<h3>'.$specific_header.'</h3>';
 4108:     } else {
 4109:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 4110:     }
 4111:     $result.= &Apache::loncommon::start_data_table().
 4112: 	      &Apache::loncommon::start_data_table_header_row().
 4113: 	      '<th>'.&mt('No.').'</th>'.
 4114: 	      '<th>'.&nameUserString('header')."</th>\n";
 4115:     my $partserror;
 4116:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4117:     if ($partserror) {
 4118:         return &navmap_errormsg();
 4119:     }
 4120:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4121:     my @partids = ();
 4122:     foreach my $part (@parts) {
 4123: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4124:         my $narrowtext = &mt('Tries');
 4125: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4126: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 4127: 	my ($partid) = &split_part_type($part);
 4128:         push(@partids,$partid);
 4129: #
 4130: # FIXME: Looks like $display looks at English text
 4131: #
 4132: 	my $display_part=&get_display_part($partid,$symb);
 4133: 	if ($display =~ /^Partial Credit Factor/) {
 4134: 	    $result.='<th>'.
 4135:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4136:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4137: 	    next;
 4138: 	    
 4139: 	} else {
 4140: 	    if ($display =~ /Problem Status/) {
 4141: 		my $grade_status_mt = &mt('Grade Status');
 4142: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4143: 	    }
 4144: 	    my $part_mt = &mt('Part:');
 4145: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4146: 	}
 4147: 
 4148: 	$result.='<th>'.$display.'</th>'."\n";
 4149:     }
 4150:     $result.=&Apache::loncommon::end_data_table_header_row();
 4151: 
 4152:     my %last_resets = 
 4153: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4154: 
 4155:     #get info for each student
 4156:     #list all the students - with points and grade status
 4157:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4158:     my $ctr = 0;
 4159:     foreach (sort 
 4160: 	     {
 4161: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4162: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4163: 		 }
 4164: 		 return $a cmp $b;
 4165: 	     } (keys(%$fullname))) {
 4166: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4167: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 4168:     }
 4169:     $result.=&Apache::loncommon::end_data_table();
 4170:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4171:     $result.='<input type="button" value="'.&mt('Save').'" '.
 4172: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4173:     if ($ctr == 0) {
 4174:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4175:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4176:                 '<span class="LC_warning">';
 4177:         if ($env{'form.submitonly'} eq 'all') {
 4178:             if (grep(/^all$/,@sections)) {
 4179:                 if (grep(/^all$/,@groups)) {
 4180:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4181:                                    $stu_status);
 4182:                 } elsif (grep(/^none$/,@groups)) {
 4183:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4184:                                    $stu_status);
 4185:                 } else {
 4186:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4187:                                    $group_display,$stu_status);
 4188:                 }
 4189:             } elsif (grep(/^none$/,@sections)) {
 4190:                 if (grep(/^all$/,@groups)) {
 4191:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4192:                                    $stu_status);
 4193:                 } elsif (grep(/^none$/,@groups)) {
 4194:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4195:                                    $stu_status);
 4196:                 } else {
 4197:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4198:                                    $group_display,$stu_status);
 4199:                 }
 4200:             } else {
 4201:                 if (grep(/^all$/,@groups)) {
 4202:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4203:                                    $section_display,$stu_status);
 4204:                 } elsif (grep(/^none$/,@groups)) {
 4205:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4206:                                    $section_display,$stu_status);
 4207:                 } else {
 4208:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4209:                                    $section_display,$group_display,$stu_status);
 4210:                 }
 4211:             }
 4212:         } else {
 4213:             if (grep(/^all$/,@sections)) {
 4214:                 if (grep(/^all$/,@groups)) {
 4215:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4216:                                    $stu_status,$submission_status);
 4217:                 } elsif (grep(/^none$/,@groups)) {
 4218:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4219:                                    $stu_status,$submission_status);
 4220:                 } else {
 4221:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4222:                                    $group_display,$stu_status,$submission_status);
 4223:                 }
 4224:             } elsif (grep(/^none$/,@sections)) {
 4225:                 if (grep(/^all$/,@groups)) {
 4226:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4227:                                    $stu_status,$submission_status);
 4228:                 } elsif (grep(/^none$/,@groups)) {
 4229:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4230:                                    $stu_status,$submission_status);
 4231:                 } else {
 4232:                     $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.',
 4233:                                    $group_display,$stu_status,$submission_status);
 4234:                 }
 4235:             } else {
 4236:                 if (grep(/^all$/,@groups)) {
 4237:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4238:                                    $section_display,$stu_status,$submission_status);
 4239:                 } elsif (grep(/^none$/,@groups)) {
 4240:                     $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.',
 4241:                                    $section_display,$stu_status,$submission_status);
 4242:                 } else {
 4243:                     $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.',
 4244:                                    $section_display,$group_display,$stu_status,$submission_status);
 4245:                 }
 4246:             }
 4247: 	}
 4248: 	$result .= '</span><br />';
 4249:     }
 4250:     return $result;
 4251: }
 4252: 
 4253: #--- call by previous routine to display each student who satisfies submission filter.
 4254: sub viewstudentgrade {
 4255:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4256:     my ($uname,$udom) = split(/:/,$student);
 4257:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4258:     my $submitonly = $env{'form.submitonly'};
 4259:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4260:         my %partstatus = ();
 4261:         if (ref($parts) eq 'ARRAY') {
 4262:             foreach my $apart (@{$parts}) {
 4263:                 my ($part,$type) = &split_part_type($apart);
 4264:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4265:                 $status = 'nothing' if ($status eq '');
 4266:                 $partstatus{$part}      = $status;
 4267:                 my $subkey = "resource.$part.submitted_by";
 4268:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4269:             }
 4270:             my $submitted = 0;
 4271:             my $graded = 0;
 4272:             my $incorrect = 0;
 4273:             foreach my $key (keys(%partstatus)) {
 4274:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4275:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4276:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4277: 
 4278:                 my $partid = (split(/\./,$key))[1];
 4279:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4280:                     $submitted = 0;
 4281:                 }
 4282:             }
 4283:             return if (!$submitted && ($submitonly eq 'yes' ||
 4284:                                        $submitonly eq 'incorrect' ||
 4285:                                        $submitonly eq 'graded'));
 4286:             return if (!$graded && ($submitonly eq 'graded'));
 4287:             return if (!$incorrect && $submitonly eq 'incorrect');
 4288:         }
 4289:     }
 4290:     if ($submitonly eq 'queued') {
 4291:         my ($cdom,$cnum) = split(/_/,$courseid);
 4292:         my %queue_status =
 4293:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4294:                                                     $udom,$uname);
 4295:         return if (!defined($queue_status{'gradingqueue'}));
 4296:     }
 4297:     $$ctr++;
 4298:     my %aggregates = ();
 4299:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4300: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4301: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4302: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4303: 	'\');" target="_self">'.$fullname.'</a> '.
 4304: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4305:     $student=~s/:/_/; # colon doen't work in javascript for names
 4306:     foreach my $apart (@$parts) {
 4307: 	my ($part,$type) = &split_part_type($apart);
 4308: 	my $score=$record{"resource.$part.$type"};
 4309:         $result.='<td align="center">';
 4310:         my ($aggtries,$totaltries);
 4311:         unless (exists($aggregates{$part})) {
 4312: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4313: 
 4314: 	    $aggtries = $totaltries;
 4315:             if ($$last_resets{$part}) {  
 4316:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4317: 					   $part);
 4318:             }
 4319:             $result.='<input type="hidden" name="'.
 4320:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4321:             $result.='<input type="hidden" name="'.
 4322:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4323:             $aggregates{$part} = 1;
 4324:         }
 4325: 	if ($type eq 'awarded') {
 4326: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4327: 	    $result.='<input type="hidden" name="'.
 4328: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4329: 	    $result.='<input type="text" name="'.
 4330: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4331:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4332: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4333: 	} elsif ($type eq 'solved') {
 4334: 	    my ($status,$foo)=split(/_/,$score,2);
 4335: 	    $status = 'nothing' if ($status eq '');
 4336: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4337: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4338: 	    $result.='&nbsp;<select name="'.
 4339: 		'GD_'.$student.'_'.$part.'_solved" '.
 4340:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4341: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4342: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4343: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4344: 	    $result.="</select>&nbsp;</td>\n";
 4345: 	} else {
 4346: 	    $result.='<input type="hidden" name="'.
 4347: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4348: 		    "\n";
 4349: 	    $result.='<input type="text" name="'.
 4350: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4351: 		'value="'.$score.'" size="4" /></td>'."\n";
 4352: 	}
 4353:     }
 4354:     $result.=&Apache::loncommon::end_data_table_row();
 4355:     return $result;
 4356: }
 4357: 
 4358: #--- change scores for all the students in a section/class
 4359: #    record does not get update if unchanged
 4360: sub editgrades {
 4361:     my ($request,$symb) = @_;
 4362: 
 4363:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4364:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4365:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4366: 
 4367:     my $result= &Apache::loncommon::start_data_table().
 4368: 	&Apache::loncommon::start_data_table_header_row().
 4369: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4370: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4371:     my %scoreptr = (
 4372: 		    'correct'  =>'correct_by_override',
 4373: 		    'incorrect'=>'incorrect_by_override',
 4374: 		    'excused'  =>'excused',
 4375: 		    'ungraded' =>'ungraded_attempted',
 4376:                     'credited' =>'credit_attempted',
 4377: 		    'nothing'  => '',
 4378: 		    );
 4379:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4380: 
 4381:     my (@partid);
 4382:     my %weight = ();
 4383:     my %columns = ();
 4384:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4385: 
 4386:     my $partserror;
 4387:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4388:     if ($partserror) {
 4389:         return &navmap_errormsg();
 4390:     }
 4391:     my $header;
 4392:     while ($ctr < $env{'form.totalparts'}) {
 4393: 	my $partid = $env{'form.partid_'.$ctr};
 4394: 	push(@partid,$partid);
 4395: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4396: 	$ctr++;
 4397:     }
 4398:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4399:     my $totcolspan = 0;
 4400:     foreach my $partid (@partid) {
 4401: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4402: 	    '<th align="center">'.&mt('New Score').'</th>';
 4403: 	$columns{$partid}=2;
 4404: 	foreach my $stores (@parts) {
 4405: 	    my ($part,$type) = &split_part_type($stores);
 4406: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4407: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4408: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4409: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4410:             my $narrowtext = &mt('Tries');
 4411: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4412: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4413: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4414: 	    $columns{$partid}+=2;
 4415: 	}
 4416:         $totcolspan += $columns{$partid};
 4417:     }
 4418:     foreach my $partid (@partid) {
 4419: 	my $display_part=&get_display_part($partid,$symb);
 4420: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4421: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4422: 	    '</th>';
 4423: 
 4424:     }
 4425:     $result .= &Apache::loncommon::end_data_table_header_row().
 4426: 	&Apache::loncommon::start_data_table_header_row().
 4427: 	$header.
 4428: 	&Apache::loncommon::end_data_table_header_row();
 4429:     my @noupdate;
 4430:     my ($updateCtr,$noupdateCtr) = (1,1);
 4431:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4432: 	my $user = $env{'form.ctr'.$i};
 4433: 	my ($uname,$udom)=split(/:/,$user);
 4434: 	my %newrecord;
 4435: 	my $updateflag = 0;
 4436:         my $usec=$classlist->{"$uname:$udom"}[5];
 4437:         my $canmodify = &canmodify($usec);
 4438:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4439:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4440:         if (!$canmodify) {
 4441:             push(@noupdate,
 4442:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4443:                  &mt('Not allowed to modify student')."</span></td>");
 4444:             next;
 4445:         }
 4446:         my %aggregate = ();
 4447:         my $aggregateflag = 0;
 4448: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4449: 	foreach (@partid) {
 4450: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4451: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4452: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4453: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4454: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4455: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4456: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4457: 	    my $score;
 4458: 	    if ($partial eq '') {
 4459: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4460: 	    } elsif ($partial > 0) {
 4461: 		$score = 'correct_by_override';
 4462: 	    } elsif ($partial == 0) {
 4463: 		$score = 'incorrect_by_override';
 4464: 	    }
 4465: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4466: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4467: 
 4468: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4469: 		"$env{'user.name'}:$env{'user.domain'}";
 4470: 	    if ($dropMenu eq 'reset status' &&
 4471: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4472: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4473: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4474: 		$newrecord{'resource.'.$_.'.award'} = '';
 4475: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4476: 		$updateflag = 1;
 4477:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4478:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4479:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4480:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4481:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4482:                     $aggregateflag = 1;
 4483:                 }
 4484: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4485: 		$updateflag = 1;
 4486: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4487: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4488: 		$rec_update++;
 4489: 	    }
 4490: 
 4491: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4492: 		'<td align="center">'.$awarded.
 4493: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4494: 
 4495: 
 4496: 	    my $partid=$_;
 4497: 	    foreach my $stores (@parts) {
 4498: 		my ($part,$type) = &split_part_type($stores);
 4499: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4500: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4501: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4502: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4503: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4504: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4505: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4506: 		    $updateflag=1;
 4507: 		}
 4508: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4509: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4510: 	    }
 4511: 	}
 4512: 	$line.="\n";
 4513: 
 4514: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4515: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4516: 
 4517: 	if ($updateflag) {
 4518: 	    $count++;
 4519: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4520: 				    $udom,$uname);
 4521: 
 4522: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4523: 					      $cnum,$udom,$uname)) {
 4524: 		# need to figure out if should be in queue.
 4525: 		my %record =  
 4526: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4527: 					     $udom,$uname);
 4528: 		my $all_graded = 1;
 4529: 		my $none_graded = 1;
 4530: 		foreach my $part (@parts) {
 4531: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4532: 			$all_graded = 0;
 4533: 		    } else {
 4534: 			$none_graded = 0;
 4535: 		    }
 4536: 		}
 4537: 
 4538: 		if ($all_graded || $none_graded) {
 4539: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4540: 							   $symb,$cdom,$cnum,
 4541: 							   $udom,$uname);
 4542: 		}
 4543: 	    }
 4544: 
 4545: 	    $result.=&Apache::loncommon::start_data_table_row().
 4546: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4547: 		&Apache::loncommon::end_data_table_row();
 4548: 	    $updateCtr++;
 4549: 	} else {
 4550: 	    push(@noupdate,
 4551: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4552: 	    $noupdateCtr++;
 4553: 	}
 4554:         if ($aggregateflag) {
 4555:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4556: 				  $cdom,$cnum);
 4557:         }
 4558:     }
 4559:     if (@noupdate) {
 4560:         my $numcols=$totcolspan+2;
 4561: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4562: 	    '<td align="center" colspan="'.$numcols.'">'.
 4563: 	    &mt('No Changes Occurred For the Students Below').
 4564: 	    '</td>'.
 4565: 	    &Apache::loncommon::end_data_table_row();
 4566: 	foreach my $line (@noupdate) {
 4567: 	    $result.=
 4568: 		&Apache::loncommon::start_data_table_row().
 4569: 		$line.
 4570: 		&Apache::loncommon::end_data_table_row();
 4571: 	}
 4572:     }
 4573:     $result .= &Apache::loncommon::end_data_table();
 4574:     my $msg = '<p><b>'.
 4575: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4576: 	    $rec_update,$count).'</b><br />'.
 4577: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4578: 	'</b></p>';
 4579:     return $title.$msg.$result;
 4580: }
 4581: 
 4582: sub split_part_type {
 4583:     my ($partstr) = @_;
 4584:     my ($temp,@allparts)=split(/_/,$partstr);
 4585:     my $type=pop(@allparts);
 4586:     my $part=join('_',@allparts);
 4587:     return ($part,$type);
 4588: }
 4589: 
 4590: #------------- end of section for handling grading by section/class ---------
 4591: #
 4592: #----------------------------------------------------------------------------
 4593: 
 4594: 
 4595: #----------------------------------------------------------------------------
 4596: #
 4597: #-------------------------- Next few routines handles grading by csv upload
 4598: #
 4599: #--- Javascript to handle csv upload
 4600: sub csvupload_javascript_reverse_associate {
 4601:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4602:     my $error2=&mt('You need to specify at least one grading field');
 4603:   &js_escape(\$error1);
 4604:   &js_escape(\$error2);
 4605:   return(<<ENDPICK);
 4606:   function verify(vf) {
 4607:     var foundsomething=0;
 4608:     var founduname=0;
 4609:     var foundID=0;
 4610:     for (i=0;i<=vf.nfields.value;i++) {
 4611:       tw=eval('vf.f'+i+'.selectedIndex');
 4612:       if (i==0 && tw!=0) { foundID=1; }
 4613:       if (i==1 && tw!=0) { founduname=1; }
 4614:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4615:     }
 4616:     if (founduname==0 && foundID==0) {
 4617: 	alert('$error1');
 4618: 	return;
 4619:     }
 4620:     if (foundsomething==0) {
 4621: 	alert('$error2');
 4622: 	return;
 4623:     }
 4624:     vf.submit();
 4625:   }
 4626:   function flip(vf,tf) {
 4627:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4628:     var i;
 4629:     for (i=0;i<=vf.nfields.value;i++) {
 4630:       //can not pick the same destination field for both name and domain
 4631:       if (((i ==0)||(i ==1)) && 
 4632:           ((tf==0)||(tf==1)) && 
 4633:           (i!=tf) &&
 4634:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4635:         eval('vf.f'+i+'.selectedIndex=0;')
 4636:       }
 4637:     }
 4638:   }
 4639: ENDPICK
 4640: }
 4641: 
 4642: sub csvupload_javascript_forward_associate {
 4643:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4644:     my $error2=&mt('You need to specify at least one grading field');
 4645:   &js_escape(\$error1);
 4646:   &js_escape(\$error2);
 4647:   return(<<ENDPICK);
 4648:   function verify(vf) {
 4649:     var foundsomething=0;
 4650:     var founduname=0;
 4651:     var foundID=0;
 4652:     for (i=0;i<=vf.nfields.value;i++) {
 4653:       tw=eval('vf.f'+i+'.selectedIndex');
 4654:       if (tw==1) { foundID=1; }
 4655:       if (tw==2) { founduname=1; }
 4656:       if (tw>3) { foundsomething=1; }
 4657:     }
 4658:     if (founduname==0 && foundID==0) {
 4659: 	alert('$error1');
 4660: 	return;
 4661:     }
 4662:     if (foundsomething==0) {
 4663: 	alert('$error2');
 4664: 	return;
 4665:     }
 4666:     vf.submit();
 4667:   }
 4668:   function flip(vf,tf) {
 4669:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4670:     var i;
 4671:     //can not pick the same destination field twice
 4672:     for (i=0;i<=vf.nfields.value;i++) {
 4673:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4674:         eval('vf.f'+i+'.selectedIndex=0;')
 4675:       }
 4676:     }
 4677:   }
 4678: ENDPICK
 4679: }
 4680: 
 4681: sub csvuploadmap_header {
 4682:     my ($request,$symb,$datatoken,$distotal)= @_;
 4683:     my $javascript;
 4684:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4685: 	$javascript=&csvupload_javascript_reverse_associate();
 4686:     } else {
 4687: 	$javascript=&csvupload_javascript_forward_associate();
 4688:     }
 4689: 
 4690:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4691:     my $ignore=&mt('Ignore First Line');
 4692:     $symb = &Apache::lonenc::check_encrypt($symb);
 4693:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4694:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4695:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4696:     my $reverse=&mt("Reverse Association");
 4697:     $request->print(<<ENDPICK);
 4698: <br />
 4699: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4700: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4701: <input type="hidden" name="associate"  value="" />
 4702: <input type="hidden" name="phase"      value="three" />
 4703: <input type="hidden" name="datatoken"  value="$datatoken" />
 4704: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4705: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4706: <input type="hidden" name="upfile_associate" 
 4707:                                        value="$env{'form.upfile_associate'}" />
 4708: <input type="hidden" name="symb"       value="$symb" />
 4709: <input type="hidden" name="command"    value="csvuploadoptions" />
 4710: <hr />
 4711: ENDPICK
 4712:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4713:     return '';
 4714: 
 4715: }
 4716: 
 4717: sub csvupload_fields {
 4718:     my ($symb,$errorref) = @_;
 4719:     my (@parts) = &getpartlist($symb,$errorref);
 4720:     if (ref($errorref)) {
 4721:         if ($$errorref) {
 4722:             return;
 4723:         }
 4724:     }
 4725: 
 4726:     my @fields=(['ID','Student/Employee ID'],
 4727: 		['username','Student Username'],
 4728: 		['domain','Student Domain']);
 4729:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4730:     foreach my $part (sort(@parts)) {
 4731: 	my @datum;
 4732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4733: 	my $name=$part;
 4734: 	if  (!$display) { $display = $name; }
 4735: 	@datum=($name,$display);
 4736: 	if ($name=~/^stores_(.*)_awarded/) {
 4737: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4738: 	}
 4739: 	push(@fields,\@datum);
 4740:     }
 4741:     return (@fields);
 4742: }
 4743: 
 4744: sub csvuploadmap_footer {
 4745:     my ($request,$i,$keyfields) =@_;
 4746:     my $buttontext = &mt('Assign Grades');
 4747:     $request->print(<<ENDPICK);
 4748: </table>
 4749: <input type="hidden" name="nfields" value="$i" />
 4750: <input type="hidden" name="keyfields" value="$keyfields" />
 4751: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4752: </form>
 4753: ENDPICK
 4754: }
 4755: 
 4756: sub checkforfile_js {
 4757:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4758:     &js_escape(\$alertmsg);
 4759:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4760:     function checkUpload(formname) {
 4761: 	if (formname.upfile.value == "") {
 4762: 	    alert("$alertmsg");
 4763: 	    return false;
 4764: 	}
 4765: 	formname.submit();
 4766:     }
 4767: CSVFORMJS
 4768:     return $result;
 4769: }
 4770: 
 4771: sub upcsvScores_form {
 4772:     my ($request,$symb) = @_;
 4773:     if (!$symb) {return '';}
 4774:     my $result=&checkforfile_js();
 4775:     $result.=&Apache::loncommon::start_data_table().
 4776:              &Apache::loncommon::start_data_table_header_row().
 4777:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4778:              &Apache::loncommon::end_data_table_header_row().
 4779:              &Apache::loncommon::start_data_table_row().'<td>';
 4780:     my $upload=&mt("Upload Scores");
 4781:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4782:     my $ignore=&mt('Ignore First Line');
 4783:     $symb = &Apache::lonenc::check_encrypt($symb);
 4784:     $result.=<<ENDUPFORM;
 4785: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4786: <input type="hidden" name="symb" value="$symb" />
 4787: <input type="hidden" name="command" value="csvuploadmap" />
 4788: $upfile_select
 4789: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4790: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4791: </form>
 4792: ENDUPFORM
 4793:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4794:                            &mt("How do I create a CSV file from a spreadsheet")).
 4795:             '</td>'.
 4796:             &Apache::loncommon::end_data_table_row().
 4797:             &Apache::loncommon::end_data_table();
 4798:     return $result;
 4799: }
 4800: 
 4801: 
 4802: sub csvuploadmap {
 4803:     my ($request,$symb) = @_;
 4804:     if (!$symb) {return '';}
 4805: 
 4806:     my $datatoken;
 4807:     if (!$env{'form.datatoken'}) {
 4808: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4809:     } else {
 4810:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4811:         if ($datatoken ne '') { 
 4812: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4813:         }
 4814:     }
 4815:     my @records=&Apache::loncommon::upfile_record_sep();
 4816:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4817:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4818:     my ($i,$keyfields);
 4819:     if (@records) {
 4820:         my $fieldserror;
 4821: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4822:         if ($fieldserror) {
 4823:             $request->print(&navmap_errormsg());
 4824:             return;
 4825:         }
 4826: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4827: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4828: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4829: 							  \@fields);
 4830: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4831: 	    chop($keyfields);
 4832: 	} else {
 4833: 	    unshift(@fields,['none','']);
 4834: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4835: 							    \@fields);
 4836:             foreach my $rec (@records) {
 4837:                 my %temp = &Apache::loncommon::record_sep($rec);
 4838:                 if (%temp) {
 4839:                     $keyfields=join(',',sort(keys(%temp)));
 4840:                     last;
 4841:                 }
 4842:             }
 4843: 	}
 4844:     }
 4845:     &csvuploadmap_footer($request,$i,$keyfields);
 4846: 
 4847:     return '';
 4848: }
 4849: 
 4850: sub csvuploadoptions {
 4851:     my ($request,$symb)= @_;
 4852:     my $overwrite=&mt('Overwrite any existing score');
 4853:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4854:     my $ignore=&mt('Ignore First Line');
 4855:     $request->print(<<ENDPICK);
 4856: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4857: <input type="hidden" name="command"    value="csvuploadassign" />
 4858: <p>
 4859: <label>
 4860:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4861:    $overwrite
 4862: </label>
 4863: </p>
 4864: ENDPICK
 4865:     my %fields=&get_fields();
 4866:     if (!defined($fields{'domain'})) {
 4867: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4868:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4869:     }
 4870:     foreach my $key (sort(keys(%env))) {
 4871: 	if ($key !~ /^form\.(.*)$/) { next; }
 4872: 	my $cleankey=$1;
 4873: 	if ($cleankey eq 'command') { next; }
 4874: 	$request->print('<input type="hidden" name="'.$cleankey.
 4875: 			'"  value="'.$env{$key}.'" />'."\n");
 4876:     }
 4877:     # FIXME do a check for any duplicated user ids...
 4878:     # FIXME do a check for any invalid user ids?...
 4879:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4880: <hr /></form>'."\n");
 4881:     return '';
 4882: }
 4883: 
 4884: sub get_fields {
 4885:     my %fields;
 4886:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4887:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4888: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4889: 	    if ($env{'form.f'.$i} ne 'none') {
 4890: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4891: 	    }
 4892: 	} else {
 4893: 	    if ($env{'form.f'.$i} ne 'none') {
 4894: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4895: 	    }
 4896: 	}
 4897:     }
 4898:     return %fields;
 4899: }
 4900: 
 4901: sub csvuploadassign {
 4902:     my ($request,$symb) = @_;
 4903:     if (!$symb) {return '';}
 4904:     my $error_msg = '';
 4905:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4906:     if ($datatoken ne '') {
 4907:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4908:     }
 4909:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4910:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4911:     my %fields=&get_fields();
 4912:     my $courseid=$env{'request.course.id'};
 4913:     my ($classlist) = &getclasslist('all',0);
 4914:     my @notallowed;
 4915:     my @skipped;
 4916:     my @warnings;
 4917:     my $countdone=0;
 4918:     foreach my $grade (@gradedata) {
 4919: 	my %entries=&Apache::loncommon::record_sep($grade);
 4920: 	my $domain;
 4921: 	if ($entries{$fields{'domain'}}) {
 4922: 	    $domain=$entries{$fields{'domain'}};
 4923: 	} else {
 4924: 	    $domain=$env{'form.default_domain'};
 4925: 	}
 4926: 	$domain=~s/\s//g;
 4927: 	my $username=$entries{$fields{'username'}};
 4928: 	$username=~s/\s//g;
 4929: 	if (!$username) {
 4930: 	    my $id=$entries{$fields{'ID'}};
 4931: 	    $id=~s/\s//g;
 4932: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4933: 	    $username=$ids{$id};
 4934: 	}
 4935: 	if (!exists($$classlist{"$username:$domain"})) {
 4936: 	    my $id=$entries{$fields{'ID'}};
 4937: 	    $id=~s/\s//g;
 4938: 	    if ($id) {
 4939: 		push(@skipped,"$id:$domain");
 4940: 	    } else {
 4941: 		push(@skipped,"$username:$domain");
 4942: 	    }
 4943: 	    next;
 4944: 	}
 4945: 	my $usec=$classlist->{"$username:$domain"}[5];
 4946: 	if (!&canmodify($usec)) {
 4947: 	    push(@notallowed,"$username:$domain");
 4948: 	    next;
 4949: 	}
 4950: 	my %points;
 4951: 	my %grades;
 4952: 	foreach my $dest (keys(%fields)) {
 4953: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4954: 		$dest eq 'domain') { next; }
 4955: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4956: 	    if ($dest=~/stores_(.*)_points/) {
 4957: 		my $part=$1;
 4958: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4959: 					      $symb,$domain,$username);
 4960:                 if ($wgt) {
 4961:                     $entries{$fields{$dest}}=~s/\s//g;
 4962:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4963:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4964:                                           : 'correct_by_override';
 4965:                     if ($pcr>1) {
 4966:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4967:                     }
 4968:                     $grades{"resource.$part.awarded"}=$pcr;
 4969:                     $grades{"resource.$part.solved"}=$award;
 4970:                     $points{$part}=1;
 4971:                 } else {
 4972:                     $error_msg = "<br />" .
 4973:                         &mt("Some point values were assigned"
 4974:                             ." for problems with a weight "
 4975:                             ."of zero. These values were "
 4976:                             ."ignored.");
 4977:                 }
 4978: 	    } else {
 4979: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4980: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4981: 		my $store_key=$dest;
 4982: 		$store_key=~s/^stores/resource/;
 4983: 		$store_key=~s/_/\./g;
 4984: 		$grades{$store_key}=$entries{$fields{$dest}};
 4985: 	    }
 4986: 	}
 4987: 	if (! %grades) {
 4988:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4989:         } else {
 4990: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4991: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4992: 					   $env{'request.course.id'},
 4993: 					   $domain,$username);
 4994: 	   if ($result eq 'ok') {
 4995: # Successfully stored
 4996: 	      $request->print('.');
 4997: # Remove from grading queue
 4998:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4999:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5000:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5001:                                              $domain,$username);
 5002: 	   } else {
 5003: 	      $request->print("<p><span class=\"LC_error\">".
 5004:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5005:                                   "$username:$domain",$result)."</span></p>");
 5006: 	   }
 5007: 	   $request->rflush();
 5008: 	   $countdone++;
 5009:         }
 5010:     }
 5011:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5012:     if (@warnings) {
 5013:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5014:         $request->print(join(', ',@warnings));
 5015:     }
 5016:     if (@skipped) {
 5017: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5018:         $request->print(join(', ',@skipped));
 5019:     }
 5020:     if (@notallowed) {
 5021: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5022: 	$request->print(join(', ',@notallowed));
 5023:     }
 5024:     $request->print("<br />\n");
 5025:     return $error_msg;
 5026: }
 5027: #------------- end of section for handling csv file upload ---------
 5028: #
 5029: #-------------------------------------------------------------------
 5030: #
 5031: #-------------- Next few routines handle grading by page/sequence
 5032: #
 5033: #--- Select a page/sequence and a student to grade
 5034: sub pickStudentPage {
 5035:     my ($request,$symb) = @_;
 5036: 
 5037:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5038:     &js_escape(\$alertmsg);
 5039:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5040: 
 5041: function checkPickOne(formname) {
 5042:     if (radioSelection(formname.student) == null) {
 5043: 	alert("$alertmsg");
 5044: 	return;
 5045:     }
 5046:     ptr = pullDownSelection(formname.selectpage);
 5047:     formname.page.value = formname["page"+ptr].value;
 5048:     formname.title.value = formname["title"+ptr].value;
 5049:     formname.submit();
 5050: }
 5051: 
 5052: LISTJAVASCRIPT
 5053:     &commonJSfunctions($request);
 5054: 
 5055:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5056:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5057:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5058:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5059: 
 5060:     my $result='<h3><span class="LC_info">&nbsp;'.
 5061: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5062: 
 5063:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5064:     my $map_error;
 5065:     my ($titles,$symbx) = &getSymbMap($map_error);
 5066:     if ($map_error) {
 5067:         $request->print(&navmap_errormsg());
 5068:         return; 
 5069:     }
 5070:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5071: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5072: #    my $type=($curpage =~ /\.(page|sequence)/);
 5073: 
 5074:     # Collection of hidden fields
 5075:     my $ctr=0;
 5076:     foreach (@$titles) {
 5077: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5078: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5079: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5080: 	$ctr++;
 5081:     }
 5082:     $result.='<input type="hidden" name="page" />'."\n".
 5083: 	'<input type="hidden" name="title" />'."\n";
 5084: 
 5085:     $result.=&build_section_inputs();
 5086:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5087:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5088:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5089:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5090: 
 5091:     # Show grading options
 5092:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5093:     my $select = '<select name="selectpage">'."\n";
 5094:     $ctr=0;
 5095:     foreach (@$titles) {
 5096:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5097:         $select.='<option value="'.$ctr.'"'.
 5098:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5099:             '>'.$showtitle.'</option>'."\n";
 5100:         $ctr++;
 5101:     }
 5102:     $select.= '</select>';
 5103: 
 5104:     $result.=
 5105:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5106:        .$select
 5107:        .&Apache::lonhtmlcommon::row_closure();
 5108: 
 5109:     $result.=
 5110:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5111:        .'<label><input type="radio" name="vProb" value="no"'
 5112:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5113:        .'<label><input type="radio" name="vProb" value="yes" />'
 5114:            .&mt('yes').'</label>'."\n"
 5115:        .&Apache::lonhtmlcommon::row_closure();
 5116: 
 5117:     $result.=
 5118:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5119:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5120:            .&mt('none').' </label>'."\n"
 5121:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5122:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5123:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5124:            .&mt('all submissions with details').' </label>'
 5125:        .&Apache::lonhtmlcommon::row_closure();
 5126: 
 5127:     $result.=
 5128:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5129:        .'<input type="text" name="CODE" value="" />'
 5130:        .&Apache::lonhtmlcommon::row_closure(1)
 5131:        .&Apache::lonhtmlcommon::end_pick_box();
 5132: 
 5133:     # Show list of students to select for grading
 5134:     $result.='<br /><input type="button" '.
 5135:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5136: 
 5137:     $request->print($result);
 5138: 
 5139:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5140: 	&Apache::loncommon::start_data_table().
 5141: 	&Apache::loncommon::start_data_table_header_row().
 5142: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5143: 	'<th>'.&nameUserString('header').'</th>'.
 5144: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5145: 	'<th>'.&nameUserString('header').'</th>'.
 5146: 	&Apache::loncommon::end_data_table_header_row();
 5147:  
 5148:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5149:     my $ptr = 1;
 5150:     foreach my $student (sort 
 5151: 			 {
 5152: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5153: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5154: 			     }
 5155: 			     return $a cmp $b;
 5156: 			 } (keys(%$fullname))) {
 5157: 	my ($uname,$udom) = split(/:/,$student);
 5158: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5159:                                   : '</td>');
 5160: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5161: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5162: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5163: 	$studentTable.=
 5164: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5165:                          : '');
 5166: 	$ptr++;
 5167:     }
 5168:     if ($ptr%2 == 0) {
 5169: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5170: 	    &Apache::loncommon::end_data_table_row();
 5171:     }
 5172:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5173:     $studentTable.='<input type="button" '.
 5174:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5175: 
 5176:     $request->print($studentTable);
 5177: 
 5178:     return '';
 5179: }
 5180: 
 5181: sub getSymbMap {
 5182:     my ($map_error) = @_;
 5183:     my $navmap = Apache::lonnavmaps::navmap->new();
 5184:     unless (ref($navmap)) {
 5185:         if (ref($map_error)) {
 5186:             $$map_error = 'navmap';
 5187:         }
 5188:         return;
 5189:     }
 5190:     my %symbx = ();
 5191:     my @titles = ();
 5192:     my $minder = 0;
 5193: 
 5194:     # Gather every sequence that has problems.
 5195:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5196: 					       1,0,1);
 5197:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5198: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5199: 	    my $title = $minder.'.'.
 5200: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5201: 	    push(@titles, $title); # minder in case two titles are identical
 5202: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5203: 	    $minder++;
 5204: 	}
 5205:     }
 5206:     return \@titles,\%symbx;
 5207: }
 5208: 
 5209: #
 5210: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5211: sub displayPage {
 5212:     my ($request,$symb) = @_;
 5213:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5214:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5215:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5216:     my $pageTitle = $env{'form.page'};
 5217:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5218:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5219:     my $usec=$classlist->{$env{'form.student'}}[5];
 5220: 
 5221:     #need to make sure we have the correct data for later EXT calls, 
 5222:     #thus invalidate the cache
 5223:     &Apache::lonnet::devalidatecourseresdata(
 5224:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5225:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5226:     &Apache::lonnet::clear_EXT_cache_status();
 5227: 
 5228:     if (!&canview($usec)) {
 5229: 	$request->print(
 5230:             '<span class="LC_warning">'.
 5231:             &mt('Unable to view requested student. ([_1])',
 5232:                 $env{'form.student'}).
 5233:             '</span>');
 5234:         return;
 5235:     }
 5236:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5237:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5238: 	'</h3>'."\n";
 5239:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5240:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5241: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5242:     } else {
 5243: 	delete($env{'form.CODE'});
 5244:     }
 5245:     &sub_page_js($request);
 5246:     $request->print($result);
 5247: 
 5248:     my $navmap = Apache::lonnavmaps::navmap->new();
 5249:     unless (ref($navmap)) {
 5250:         $request->print(&navmap_errormsg());
 5251:         return;
 5252:     }
 5253:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5254:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5255:     if (!$map) {
 5256: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5257: 	return; 
 5258:     }
 5259:     my $iterator = $navmap->getIterator($map->map_start(),
 5260: 					$map->map_finish());
 5261: 
 5262:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5263: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5264: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5265: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5266: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5267: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5268: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5269: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5270: 
 5271:     if (defined($env{'form.CODE'})) {
 5272: 	$studentTable.=
 5273: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5274:     }
 5275:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5276: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5277: 
 5278:     $studentTable.='&nbsp;<span class="LC_info">'.
 5279:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5280:         '</span>'."\n".
 5281: 	&Apache::loncommon::start_data_table().
 5282: 	&Apache::loncommon::start_data_table_header_row().
 5283: 	'<th>'.&mt('Prob.').'</th>'.
 5284: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5285: 	&Apache::loncommon::end_data_table_header_row();
 5286: 
 5287:     &Apache::lonxml::clear_problem_counter();
 5288:     my ($depth,$question,$prob) = (1,1,1);
 5289:     $iterator->next(); # skip the first BEGIN_MAP
 5290:     my $curRes = $iterator->next(); # for "current resource"
 5291:     while ($depth > 0) {
 5292:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5293:         if($curRes == $iterator->END_MAP) { $depth--; }
 5294: 
 5295:         if (ref($curRes) && $curRes->is_problem()) {
 5296: 	    my $parts = $curRes->parts();
 5297:             my $title = $curRes->compTitle();
 5298: 	    my $symbx = $curRes->symb();
 5299: 	    $studentTable.=
 5300: 		&Apache::loncommon::start_data_table_row().
 5301: 		'<td align="center" valign="top" >'.$prob.
 5302: 		(scalar(@{$parts}) == 1 ? '' 
 5303: 		                        : '<br />('.&mt('[_1]parts',
 5304: 							scalar(@{$parts}).'&nbsp;').')'
 5305: 		 ).
 5306: 		 '</td>';
 5307: 	    $studentTable.='<td valign="top">';
 5308: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5309: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5310: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5311: 					     undef,'both',\%form);
 5312: 	    } else {
 5313: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5314: 		$companswer =~ s|<form(.*?)>||g;
 5315: 		$companswer =~ s|</form>||g;
 5316: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5317: #		    $companswer =~ s/$1/ /ms;
 5318: #		    $request->print('match='.$1."<br />\n");
 5319: #		}
 5320: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5321: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5322: 	    }
 5323: 
 5324: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5325: 
 5326: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5327: 		if ($record{'version'} eq '') {
 5328: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5329: 		} else {
 5330: 		    my %responseType = ();
 5331: 		    foreach my $partid (@{$parts}) {
 5332: 			my @responseIds =$curRes->responseIds($partid);
 5333: 			my @responseType =$curRes->responseType($partid);
 5334: 			my %responseIds;
 5335: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5336: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5337: 			}
 5338: 			$responseType{$partid} = \%responseIds;
 5339: 		    }
 5340: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5341: 
 5342: 		}
 5343: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5344: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5345:                 my $identifier = (&canmodify($usec)? $prob : '');
 5346: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5347: 									$env{'request.course.id'},
 5348: 									'','.submission',undef,
 5349:                                                                         $usec,$identifier);
 5350:  
 5351: 	    }
 5352: 	    if (&canmodify($usec)) {
 5353:             $studentTable.=&gradeBox_start();
 5354: 		foreach my $partid (@{$parts}) {
 5355: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5356: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5357: 		    $question++;
 5358: 		}
 5359:             $studentTable.=&gradeBox_end();
 5360: 		$prob++;
 5361: 	    }
 5362: 	    $studentTable.='</td></tr>';
 5363: 
 5364: 	}
 5365:         $curRes = $iterator->next();
 5366:     }
 5367: 
 5368:     $studentTable.=
 5369:         '</table>'."\n".
 5370:         '<input type="button" value="'.&mt('Save').'" '.
 5371:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5372:         '</form>'."\n";
 5373:     $request->print($studentTable);
 5374: 
 5375:     return '';
 5376: }
 5377: 
 5378: sub displaySubByDates {
 5379:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5380:     my $isCODE=0;
 5381:     my $isTask = ($symb =~/\.task$/);
 5382:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5383:     my $studentTable=&Apache::loncommon::start_data_table().
 5384: 	&Apache::loncommon::start_data_table_header_row().
 5385: 	'<th>'.&mt('Date/Time').'</th>'.
 5386: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5387:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5388: 	'<th>'.&mt('Submission').'</th>'.
 5389: 	'<th>'.&mt('Status').'</th>'.
 5390: 	&Apache::loncommon::end_data_table_header_row();
 5391:     my ($version);
 5392:     my %mark;
 5393:     my %orders;
 5394:     $mark{'correct_by_student'} = $checkIcon;
 5395:     if (!exists($$record{'1:timestamp'})) {
 5396: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5397:     }
 5398: 
 5399:     my $interaction;
 5400:     my $no_increment = 1;
 5401:     my (%lastrndseed,%lasttype);
 5402:     for ($version=1;$version<=$$record{'version'};$version++) {
 5403: 	my $timestamp = 
 5404: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5405: 	if (exists($$record{$version.':resource.0.version'})) {
 5406: 	    $interaction = $$record{$version.':resource.0.version'};
 5407: 	}
 5408:         if ($isTask && $env{'form.previousversion'}) {
 5409:             next unless ($interaction == $env{'form.previousversion'});
 5410:         }
 5411: 	my $where = ($isTask ? "$version:resource.$interaction"
 5412: 		             : "$version:resource");
 5413: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5414: 	    '<td>'.$timestamp.'</td>';
 5415: 	if ($isCODE) {
 5416: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5417: 	}
 5418:         if ($isTask) {
 5419:             $studentTable.='<td>'.$interaction.'</td>';
 5420:         }
 5421: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5422: 	my @displaySub = ();
 5423: 	foreach my $partid (@{$parts}) {
 5424:             my ($hidden,$type);
 5425:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5426:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5427:                 $hidden = 1;
 5428:             }
 5429: 	    my @matchKey;
 5430:             if ($isTask) {
 5431:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5432:             } else {
 5433: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5434:             }
 5435: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5436: 	    my $display_part=&get_display_part($partid,$symb);
 5437: 	    foreach my $matchKey (@matchKey) {
 5438: 		if (exists($$record{$version.':'.$matchKey}) &&
 5439: 		    $$record{$version.':'.$matchKey} ne '') {
 5440:                     
 5441: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5442: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5443:                     $displaySub[0].='<span class="LC_nobreak">';
 5444:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5445:                                    .' <span class="LC_internal_info">'
 5446:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5447:                                    .'</span>'
 5448:                                    .' <b>';
 5449:                     if ($hidden) {
 5450:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5451:                     } else {
 5452:                         my ($trial,$rndseed,$newvariation);
 5453:                         if ($type eq 'randomizetry') {
 5454:                             $trial = $$record{"$where.$partid.tries"};
 5455:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5456:                         }
 5457: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5458: 			    $displaySub[0].=&mt('Trial not counted');
 5459: 		        } else {
 5460: 			    $displaySub[0].=&mt('Trial: [_1]',
 5461: 					    $$record{"$where.$partid.tries"});
 5462:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5463:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5464:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5465:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5466:                                 }
 5467:                             }
 5468:                             $lastrndseed{$partid} = $rndseed;
 5469:                             $lasttype{$partid} = $type;
 5470: 		        }
 5471: 		        my $responseType=($isTask ? 'Task'
 5472:                                               : $responseType->{$partid}->{$responseId});
 5473: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5474: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5475: 			    $orders{$partid}->{$responseId}=
 5476: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5477:                                            $no_increment,$type,$trial,$rndseed);
 5478: 		        }
 5479: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5480: 		        $displaySub[0].='&nbsp; '.
 5481: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5482:                     }
 5483: 		}
 5484: 	    }
 5485: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5486: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5487: 				    $$record{"$where.$partid.checkedin"},
 5488: 				    $$record{"$where.$partid.checkedin.slot"}).
 5489: 					'<br />';
 5490: 	    }
 5491: 	    if (exists $$record{"$where.$partid.award"}) {
 5492: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5493: 		    lc($$record{"$where.$partid.award"}).' '.
 5494: 		    $mark{$$record{"$where.$partid.solved"}}.
 5495: 		    '<br />';
 5496: 	    }
 5497: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5498: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5499: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5500: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5501: 		$displaySub[2].=
 5502: 		    $$record{"$version:resource.$partid.regrader"}.
 5503: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5504: 	    }
 5505: 	}
 5506: 	# needed because old essay regrader has not parts info
 5507: 	if (exists $$record{"$version:resource.regrader"}) {
 5508: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5509: 	}
 5510: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5511: 	if ($displaySub[2]) {
 5512: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5513: 	}
 5514: 	$studentTable.='&nbsp;</td>'.
 5515: 	    &Apache::loncommon::end_data_table_row();
 5516:     }
 5517:     $studentTable.=&Apache::loncommon::end_data_table();
 5518:     return $studentTable;
 5519: }
 5520: 
 5521: sub updateGradeByPage {
 5522:     my ($request,$symb) = @_;
 5523: 
 5524:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5525:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5526:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5527:     my $pageTitle = $env{'form.page'};
 5528:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5529:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5530:     my $usec=$classlist->{$env{'form.student'}}[5];
 5531:     if (!&canmodify($usec)) {
 5532: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5533: 	return;
 5534:     }
 5535:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5536:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5537: 	'</h3>'."\n";
 5538: 
 5539:     $request->print($result);
 5540: 
 5541: 
 5542:     my $navmap = Apache::lonnavmaps::navmap->new();
 5543:     unless (ref($navmap)) {
 5544:         $request->print(&navmap_errormsg());
 5545:         return;
 5546:     }
 5547:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5548:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5549:     if (!$map) {
 5550: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5551: 	return; 
 5552:     }
 5553:     my $iterator = $navmap->getIterator($map->map_start(),
 5554: 					$map->map_finish());
 5555: 
 5556:     my $studentTable=
 5557: 	&Apache::loncommon::start_data_table().
 5558: 	&Apache::loncommon::start_data_table_header_row().
 5559: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5560: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5561: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5562: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5563: 	&Apache::loncommon::end_data_table_header_row();
 5564: 
 5565:     $iterator->next(); # skip the first BEGIN_MAP
 5566:     my $curRes = $iterator->next(); # for "current resource"
 5567:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5568:     while ($depth > 0) {
 5569:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5570:         if($curRes == $iterator->END_MAP) { $depth--; }
 5571: 
 5572:         if (ref($curRes) && $curRes->is_problem()) {
 5573: 	    my $parts = $curRes->parts();
 5574:             my $title = $curRes->compTitle();
 5575: 	    my $symbx = $curRes->symb();
 5576: 	    $studentTable.=
 5577: 		&Apache::loncommon::start_data_table_row().
 5578: 		'<td align="center" valign="top" >'.$prob.
 5579: 		(scalar(@{$parts}) == 1 ? '' 
 5580:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5581: 		.')').'</td>';
 5582: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5583: 
 5584: 	    my %newrecord=();
 5585: 	    my @displayPts=();
 5586:             my %aggregate = ();
 5587:             my $aggregateflag = 0;
 5588:             if ($env{'form.HIDE'.$prob}) {
 5589:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5590:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5591:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5592:                 $hideflag += $numchgs;
 5593:             }
 5594: 	    foreach my $partid (@{$parts}) {
 5595: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5596: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5597: 
 5598: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5599: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5600: 		my $partial = $newpts/$wgt;
 5601: 		my $score;
 5602: 		if ($partial > 0) {
 5603: 		    $score = 'correct_by_override';
 5604: 		} elsif ($newpts ne '') { #empty is taken as 0
 5605: 		    $score = 'incorrect_by_override';
 5606: 		}
 5607: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5608: 		if ($dropMenu eq 'excused') {
 5609: 		    $partial = '';
 5610: 		    $score = 'excused';
 5611: 		} elsif ($dropMenu eq 'reset status'
 5612: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5613: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5614: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5615: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5616: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5617: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5618: 		    $changeflag++;
 5619: 		    $newpts = '';
 5620:                     
 5621:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5622:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5623:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5624:                     if ($aggtries > 0) {
 5625:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5626:                         $aggregateflag = 1;
 5627:                     }
 5628: 		}
 5629: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5630: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5631: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5632: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5633: 		    '&nbsp;<br />';
 5634: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5635: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5636: 		    '&nbsp;<br />';
 5637: 		$question++;
 5638: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5639: 
 5640: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5641: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5642: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5643: 		    if (scalar(keys(%newrecord)) > 0);
 5644: 
 5645: 		$changeflag++;
 5646: 	    }
 5647: 	    if (scalar(keys(%newrecord)) > 0) {
 5648: 		my %record = 
 5649: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5650: 					     $udom,$uname);
 5651: 
 5652: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5653: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5654: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5655: 		    $newrecord{'resource.CODE'} = '';
 5656: 		}
 5657: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5658: 					$udom,$uname);
 5659: 		%record = &Apache::lonnet::restore($symbx,
 5660: 						   $env{'request.course.id'},
 5661: 						   $udom,$uname);
 5662: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5663: 					     $cdom,$cnum,$udom,$uname);
 5664: 	    }
 5665: 	    
 5666:             if ($aggregateflag) {
 5667:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5668:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5669:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5670:             }
 5671: 
 5672: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5673: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5674: 		&Apache::loncommon::end_data_table_row();
 5675: 
 5676: 	    $prob++;
 5677: 	}
 5678:         $curRes = $iterator->next();
 5679:     }
 5680: 
 5681:     $studentTable.=&Apache::loncommon::end_data_table();
 5682:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5683: 		  &mt('The scores were changed for [quant,_1,problem].',
 5684: 		  $changeflag).'<br />');
 5685:     my $hidemsg=($hideflag == 0 ? '' :
 5686:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5687:                      $hideflag).'<br />');
 5688:     $request->print($hidemsg.$grademsg.$studentTable);
 5689: 
 5690:     return '';
 5691: }
 5692: 
 5693: #-------- end of section for handling grading by page/sequence ---------
 5694: #
 5695: #-------------------------------------------------------------------
 5696: 
 5697: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5698: #
 5699: #------ start of section for handling grading by page/sequence ---------
 5700: 
 5701: =pod
 5702: 
 5703: =head1 Bubble sheet grading routines
 5704: 
 5705:   For this documentation:
 5706: 
 5707:    'scanline' refers to the full line of characters
 5708:    from the file that we are parsing that represents one entire sheet
 5709: 
 5710:    'bubble line' refers to the data
 5711:    representing the line of bubbles that are on the physical bubblesheet
 5712: 
 5713: 
 5714: The overall process is that a scanned in bubblesheet data is uploaded
 5715: into a course. When a user wants to grade, they select a
 5716: sequence/folder of resources, a file of bubblesheet info, and pick
 5717: one of the predefined configurations for what each scanline looks
 5718: like.
 5719: 
 5720: Next each scanline is checked for any errors of either 'missing
 5721: bubbles' (it's an error because it may have been mis-scanned
 5722: because too light bubbling), 'double bubble' (each bubble line should
 5723: have no more than one letter picked), invalid or duplicated CODE,
 5724: invalid student/employee ID
 5725: 
 5726: If the CODE option is used that determines the randomization of the
 5727: homework problems, either way the student/employee ID is looked up into a
 5728: username:domain.
 5729: 
 5730: During the validation phase the instructor can choose to skip scanlines. 
 5731: 
 5732: After the validation phase, there are now 3 bubblesheet files
 5733: 
 5734:   scantron_original_filename (unmodified original file)
 5735:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5736:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5737: 
 5738: Also there is a separate hash nohist_scantrondata that contains extra
 5739: correction information that isn't representable in the bubblesheet
 5740: file (see &scantron_getfile() for more information)
 5741: 
 5742: After all scanlines are either valid, marked as valid or skipped, then
 5743: foreach line foreach problem in the picked sequence, an ssi request is
 5744: made that simulates a user submitting their selected letter(s) against
 5745: the homework problem.
 5746: 
 5747: =over 4
 5748: 
 5749: 
 5750: 
 5751: =item defaultFormData
 5752: 
 5753:   Returns html hidden inputs used to hold context/default values.
 5754: 
 5755:  Arguments:
 5756:   $symb - $symb of the current resource 
 5757: 
 5758: =cut
 5759: 
 5760: sub defaultFormData {
 5761:     my ($symb)=@_;
 5762:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5763: }
 5764: 
 5765: 
 5766: =pod 
 5767: 
 5768: =item getSequenceDropDown
 5769: 
 5770:    Return html dropdown of possible sequences to grade
 5771:  
 5772:  Arguments:
 5773:    $symb - $symb of the current resource
 5774:    $map_error - ref to scalar which will container error if
 5775:                 $navmap object is unavailable in &getSymbMap().
 5776: 
 5777: =cut
 5778: 
 5779: sub getSequenceDropDown {
 5780:     my ($symb,$map_error)=@_;
 5781:     my $result='<select name="selectpage">'."\n";
 5782:     my ($titles,$symbx) = &getSymbMap($map_error);
 5783:     if (ref($map_error)) {
 5784:         return if ($$map_error);
 5785:     }
 5786:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5787:     my $ctr=0;
 5788:     foreach (@$titles) {
 5789: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5790: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5791: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5792: 	    '>'.$showtitle.'</option>'."\n";
 5793: 	$ctr++;
 5794:     }
 5795:     $result.= '</select>';
 5796:     return $result;
 5797: }
 5798: 
 5799: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5800:                                    # key is zero-based index - 0, 1, 2 ...
 5801: 
 5802: my %first_bubble_line;             # First bubble line no. for each bubble.
 5803: 
 5804: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5805:                                    # matchresponse or rankresponse, where 
 5806:                                    # an individual response can have multiple 
 5807:                                    # lines
 5808: 
 5809: my %responsetype_per_response;     # responsetype for each response
 5810: 
 5811: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5812:                                    # numbered response. Needed when randomorder
 5813:                                    # or randompick are in use. Key is ID, value 
 5814:                                    # is response number.
 5815: 
 5816: # Save and restore the bubble lines array to the form env.
 5817: 
 5818: 
 5819: sub save_bubble_lines {
 5820:     foreach my $line (keys(%bubble_lines_per_response)) {
 5821: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5822: 	$env{"form.scantron.first_bubble_line.$line"} =
 5823: 	    $first_bubble_line{$line};
 5824:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5825:             $subdivided_bubble_lines{$line};
 5826:         $env{"form.scantron.responsetype.$line"} =
 5827:             $responsetype_per_response{$line};
 5828:     }
 5829:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5830:         my $line = $masterseq_id_responsenum{$resid};
 5831:         $env{"form.scantron.residpart.$line"} = $resid;
 5832:     }
 5833: }
 5834: 
 5835: 
 5836: sub restore_bubble_lines {
 5837:     my $line = 0;
 5838:     %bubble_lines_per_response = ();
 5839:     %masterseq_id_responsenum = ();
 5840:     while ($env{"form.scantron.bubblelines.$line"}) {
 5841: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5842: 	$bubble_lines_per_response{$line} = $value;
 5843: 	$first_bubble_line{$line}  =
 5844: 	    $env{"form.scantron.first_bubble_line.$line"};
 5845:         $subdivided_bubble_lines{$line} =
 5846:             $env{"form.scantron.sub_bubblelines.$line"};
 5847:         $responsetype_per_response{$line} =
 5848:             $env{"form.scantron.responsetype.$line"};
 5849:         my $id = $env{"form.scantron.residpart.$line"};
 5850:         $masterseq_id_responsenum{$id} = $line;
 5851: 	$line++;
 5852:     }
 5853: }
 5854: 
 5855: =pod 
 5856: 
 5857: =item scantron_filenames
 5858: 
 5859:    Returns a list of the scantron files in the current course 
 5860: 
 5861: =cut
 5862: 
 5863: sub scantron_filenames {
 5864:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5865:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5866:     my $getpropath = 1;
 5867:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5868:                                                         $cname,$getpropath);
 5869:     my @possiblenames;
 5870:     if (ref($dirlist) eq 'ARRAY') {
 5871:         foreach my $filename (sort(@{$dirlist})) {
 5872: 	    ($filename)=split(/&/,$filename);
 5873: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5874: 	    $filename=~s/^scantron_orig_//;
 5875: 	    push(@possiblenames,$filename);
 5876:         }
 5877:     }
 5878:     return @possiblenames;
 5879: }
 5880: 
 5881: =pod 
 5882: 
 5883: =item scantron_uploads
 5884: 
 5885:    Returns  html drop-down list of scantron files in current course.
 5886: 
 5887:  Arguments:
 5888:    $file2grade - filename to set as selected in the dropdown
 5889: 
 5890: =cut
 5891: 
 5892: sub scantron_uploads {
 5893:     my ($file2grade) = @_;
 5894:     my $result=	'<select name="scantron_selectfile">';
 5895:     $result.="<option></option>";
 5896:     foreach my $filename (sort(&scantron_filenames())) {
 5897: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5898:     }
 5899:     $result.="</select>";
 5900:     return $result;
 5901: }
 5902: 
 5903: =pod 
 5904: 
 5905: =item scantron_scantab
 5906: 
 5907:   Returns html drop down of the scantron formats in the scantronformat.tab
 5908:   file.
 5909: 
 5910: =cut
 5911: 
 5912: sub scantron_scantab {
 5913:     my $result='<select name="scantron_format">'."\n";
 5914:     $result.='<option></option>'."\n";
 5915:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5916:     if (@lines > 0) {
 5917:         foreach my $line (@lines) {
 5918:             next if (($line =~ /^\#/) || ($line eq ''));
 5919: 	    my ($name,$descrip)=split(/:/,$line);
 5920: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5921:         }
 5922:     }
 5923:     $result.='</select>'."\n";
 5924:     return $result;
 5925: }
 5926: 
 5927: =pod 
 5928: 
 5929: =item scantron_CODElist
 5930: 
 5931:   Returns html drop down of the saved CODE lists from current course,
 5932:   generated from earlier printings.
 5933: 
 5934: =cut
 5935: 
 5936: sub scantron_CODElist {
 5937:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5938:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5939:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5940:     my $namechoice='<option></option>';
 5941:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5942: 	if ($name =~ /^error: 2 /) { next; }
 5943: 	if ($name =~ /^type\0/) { next; }
 5944: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5945:     }
 5946:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5947:     return $namechoice;
 5948: }
 5949: 
 5950: =pod 
 5951: 
 5952: =item scantron_CODEunique
 5953: 
 5954:   Returns the html for "Each CODE to be used once" radio.
 5955: 
 5956: =cut
 5957: 
 5958: sub scantron_CODEunique {
 5959:     my $result='<span class="LC_nobreak">
 5960:                  <label><input type="radio" name="scantron_CODEunique"
 5961:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5962:                 </span>
 5963:                 <span class="LC_nobreak">
 5964:                  <label><input type="radio" name="scantron_CODEunique"
 5965:                         value="no" />'.&mt('No').' </label>
 5966:                 </span>';
 5967:     return $result;
 5968: }
 5969: 
 5970: =pod 
 5971: 
 5972: =item scantron_selectphase
 5973: 
 5974:   Generates the initial screen to start the bubblesheet process.
 5975:   Allows for - starting a grading run.
 5976:              - downloading existing scan data (original, corrected
 5977:                                                 or skipped info)
 5978: 
 5979:              - uploading new scan data
 5980: 
 5981:  Arguments:
 5982:   $r          - The Apache request object
 5983:   $file2grade - name of the file that contain the scanned data to score
 5984: 
 5985: =cut
 5986: 
 5987: sub scantron_selectphase {
 5988:     my ($r,$file2grade,$symb) = @_;
 5989:     if (!$symb) {return '';}
 5990:     my $map_error;
 5991:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5992:     if ($map_error) {
 5993:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5994:         return;
 5995:     }
 5996:     my $default_form_data=&defaultFormData($symb);
 5997:     my $file_selector=&scantron_uploads($file2grade);
 5998:     my $format_selector=&scantron_scantab();
 5999:     my $CODE_selector=&scantron_CODElist();
 6000:     my $CODE_unique=&scantron_CODEunique();
 6001:     my $result;
 6002: 
 6003:     $ssi_error = 0;
 6004: 
 6005:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6006:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6007: 
 6008:         # Chunk of form to prompt for a scantron file upload.
 6009: 
 6010:         $r->print('
 6011:     <br />');
 6012:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6013:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6014:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6015:         &js_escape(\$alertmsg);
 6016:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6017:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6018:     function checkUpload(formname) {
 6019:         if (formname.upfile.value == "") {
 6020:             alert("'.$alertmsg.'");
 6021:             return false;
 6022:         }
 6023:         formname.submit();
 6024:     }'."\n".$formatjs));
 6025:         $r->print('
 6026:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6027:                 '.$default_form_data.'
 6028:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6029:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6030:                 <input name="command" value="scantronupload_save" type="hidden" />
 6031:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6032:               '.&Apache::loncommon::start_data_table_header_row().'
 6033:                 <th>
 6034:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6035:                 </th>
 6036:               '.&Apache::loncommon::end_data_table_header_row().'
 6037:               '.&Apache::loncommon::start_data_table_row().'
 6038:             <td>
 6039:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6040:         if ($formatoptions) {
 6041:             $r->print('</td>
 6042:                  '.&Apache::loncommon::end_data_table_row().'
 6043:                  '.&Apache::loncommon::start_data_table_row().'
 6044:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6045:                  </td>
 6046:                  '.&Apache::loncommon::end_data_table_row().'
 6047:                  '.&Apache::loncommon::start_data_table_row().'
 6048:                  <td>'
 6049:             );
 6050:         } else {
 6051:             $r->print(' <br />');
 6052:         }
 6053:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6054:               </td>
 6055:              '.&Apache::loncommon::end_data_table_row().'
 6056:              '.&Apache::loncommon::end_data_table().'
 6057:              </form>'
 6058:         );
 6059: 
 6060:     }
 6061: 
 6062:     # Chunk of form to prompt for a file to grade and how:
 6063: 
 6064:     $result.= '
 6065:     <br />
 6066:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6067:     <input type="hidden" name="command" value="scantron_warning" />
 6068:     '.$default_form_data.'
 6069:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6070:        '.&Apache::loncommon::start_data_table_header_row().'
 6071:             <th colspan="2">
 6072:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6073:             </th>
 6074:        '.&Apache::loncommon::end_data_table_header_row().'
 6075:        '.&Apache::loncommon::start_data_table_row().'
 6076:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6077:        '.&Apache::loncommon::end_data_table_row().'
 6078:        '.&Apache::loncommon::start_data_table_row().'
 6079:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6080:        '.&Apache::loncommon::end_data_table_row().'
 6081:        '.&Apache::loncommon::start_data_table_row().'
 6082:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6083:        '.&Apache::loncommon::end_data_table_row().'
 6084:        '.&Apache::loncommon::start_data_table_row().'
 6085:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6086:        '.&Apache::loncommon::end_data_table_row().'
 6087:        '.&Apache::loncommon::start_data_table_row().'
 6088:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6089:        '.&Apache::loncommon::end_data_table_row().'
 6090:        '.&Apache::loncommon::start_data_table_row().'
 6091: 	    <td> '.&mt('Options:').' </td>
 6092:             <td>
 6093: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6094:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6095:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6096: 	    </td>
 6097:        '.&Apache::loncommon::end_data_table_row().'
 6098:        '.&Apache::loncommon::start_data_table_row().'
 6099:             <td colspan="2">
 6100:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6101:             </td>
 6102:        '.&Apache::loncommon::end_data_table_row().'
 6103:     '.&Apache::loncommon::end_data_table().'
 6104:     </form>
 6105: ';
 6106:    
 6107:     $r->print($result);
 6108: 
 6109:     # Chunk of the form that prompts to view a scoring office file,
 6110:     # corrected file, skipped records in a file.
 6111: 
 6112:     $r->print('
 6113:    <br />
 6114:    <form action="/adm/grades" name="scantron_download">
 6115:      '.$default_form_data.'
 6116:      <input type="hidden" name="command" value="scantron_download" />
 6117:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6118:        '.&Apache::loncommon::start_data_table_header_row().'
 6119:               <th>
 6120:                 &nbsp;'.&mt('Download a scoring office file').'
 6121:               </th>
 6122:        '.&Apache::loncommon::end_data_table_header_row().'
 6123:        '.&Apache::loncommon::start_data_table_row().'
 6124:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6125:                 <br />
 6126:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6127:        '.&Apache::loncommon::end_data_table_row().'
 6128:      '.&Apache::loncommon::end_data_table().'
 6129:    </form>
 6130:    <br />
 6131: ');
 6132: 
 6133:     &Apache::lonpickcode::code_list($r,2);
 6134: 
 6135:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6136:              $default_form_data."\n".
 6137:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6138:              &Apache::loncommon::start_data_table_header_row()."\n".
 6139:              '<th colspan="2">
 6140:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6141:              '</th>'."\n".
 6142:               &Apache::loncommon::end_data_table_header_row()."\n".
 6143:               &Apache::loncommon::start_data_table_row()."\n".
 6144:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6145:               '<td> '.$sequence_selector.' </td>'.
 6146:               &Apache::loncommon::end_data_table_row()."\n".
 6147:               &Apache::loncommon::start_data_table_row()."\n".
 6148:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6149:               '<td> '.$file_selector.' </td>'."\n".
 6150:               &Apache::loncommon::end_data_table_row()."\n".
 6151:               &Apache::loncommon::start_data_table_row()."\n".
 6152:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6153:               '<td> '.$format_selector.' </td>'."\n".
 6154:               &Apache::loncommon::end_data_table_row()."\n".
 6155:               &Apache::loncommon::start_data_table_row()."\n".
 6156:               '<td> '.&mt('Options').' </td>'."\n".
 6157:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6158:               &Apache::loncommon::end_data_table_row()."\n".
 6159:               &Apache::loncommon::start_data_table_row()."\n".
 6160:               '<td colspan="2">'."\n".
 6161:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6162:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6163:               '</td>'."\n".
 6164:               &Apache::loncommon::end_data_table_row()."\n".
 6165:               &Apache::loncommon::end_data_table()."\n".
 6166:               '</form><br />');
 6167:     return;
 6168: }
 6169: 
 6170: =pod 
 6171: 
 6172: =item username_to_idmap
 6173: 
 6174:     creates a hash keyed by student/employee ID with values of the corresponding
 6175:     student username:domain.
 6176: 
 6177:   Arguments:
 6178: 
 6179:     $classlist - reference to the class list hash. This is a hash
 6180:                  keyed by student name:domain  whose elements are references
 6181:                  to arrays containing various chunks of information
 6182:                  about the student. (See loncoursedata for more info).
 6183: 
 6184:   Returns
 6185:     %idmap - the constructed hash
 6186: 
 6187: =cut
 6188: 
 6189: sub username_to_idmap {
 6190:     my ($classlist)= @_;
 6191:     my %idmap;
 6192:     foreach my $student (keys(%$classlist)) {
 6193:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6194:         unless ($id eq '') {
 6195:             if (!exists($idmap{$id})) {
 6196:                 $idmap{$id} = $student;
 6197:             } else {
 6198:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6199:                 if ($status eq 'Active') {
 6200:                     $idmap{$id} = $student;
 6201:                 }
 6202:             }
 6203:         }
 6204:     }
 6205:     return %idmap;
 6206: }
 6207: 
 6208: =pod
 6209: 
 6210: =item scantron_fixup_scanline
 6211: 
 6212:    Process a requested correction to a scanline.
 6213: 
 6214:   Arguments:
 6215:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6216:     $scan_data         - hash of correction information 
 6217:                           (see &scantron_getfile())
 6218:     $line              - existing scanline
 6219:     $whichline         - line number of the passed in scanline
 6220:     $field             - type of change to process 
 6221:                          (either 
 6222:                           'ID'     -> correct the student/employee ID
 6223:                           'CODE'   -> correct the CODE
 6224:                           'answer' -> fixup the submitted answers)
 6225:     
 6226:    $args               - hash of additional info,
 6227:                           - 'ID' 
 6228:                                'newid' -> studentID to use in replacement
 6229:                                           of existing one
 6230:                           - 'CODE' 
 6231:                                'CODE_ignore_dup' - set to true if duplicates
 6232:                                                    should be ignored.
 6233: 	                       'CODE' - is new code or 'use_unfound'
 6234:                                         if the existing unfound code should
 6235:                                         be used as is
 6236:                           - 'answer'
 6237:                                'response' - new answer or 'none' if blank
 6238:                                'question' - the bubble line to change
 6239:                                'questionnum' - the question identifier,
 6240:                                                may include subquestion. 
 6241: 
 6242:   Returns:
 6243:     $line - the modified scanline
 6244: 
 6245:   Side effects: 
 6246:     $scan_data - may be updated
 6247: 
 6248: =cut
 6249: 
 6250: 
 6251: sub scantron_fixup_scanline {
 6252:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6253:     if ($field eq 'ID') {
 6254: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6255: 	    return ($line,1,'New value too large');
 6256: 	}
 6257: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6258: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6259: 				     $args->{'newid'});
 6260: 	}
 6261: 	substr($line,$$scantron_config{'IDstart'}-1,
 6262: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6263: 	if ($args->{'newid'}=~/^\s*$/) {
 6264: 	    &scan_data($scan_data,"$whichline.user",
 6265: 		       $args->{'username'}.':'.$args->{'domain'});
 6266: 	}
 6267:     } elsif ($field eq 'CODE') {
 6268: 	if ($args->{'CODE_ignore_dup'}) {
 6269: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6270: 	}
 6271: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6272: 	if ($args->{'CODE'} ne 'use_unfound') {
 6273: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6274: 		return ($line,1,'New CODE value too large');
 6275: 	    }
 6276: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6277: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6278: 	    }
 6279: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6280: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6281: 	}
 6282:     } elsif ($field eq 'answer') {
 6283: 	my $length=$scantron_config->{'Qlength'};
 6284: 	my $off=$scantron_config->{'Qoff'};
 6285: 	my $on=$scantron_config->{'Qon'};
 6286: 	my $answer=${off}x$length;
 6287: 	if ($args->{'response'} eq 'none') {
 6288: 	    &scan_data($scan_data,
 6289: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6290: 	} else {
 6291: 	    if ($on eq 'letter') {
 6292: 		my @alphabet=('A'..'Z');
 6293: 		$answer=$alphabet[$args->{'response'}];
 6294: 	    } elsif ($on eq 'number') {
 6295: 		$answer=$args->{'response'}+1;
 6296: 		if ($answer == 10) { $answer = '0'; }
 6297: 	    } else {
 6298: 		substr($answer,$args->{'response'},1)=$on;
 6299: 	    }
 6300: 	    &scan_data($scan_data,
 6301: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6302: 	}
 6303: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6304: 	substr($line,$where-1,$length)=$answer;
 6305:     }
 6306:     return $line;
 6307: }
 6308: 
 6309: =pod
 6310: 
 6311: =item scan_data
 6312: 
 6313:     Edit or look up  an item in the scan_data hash.
 6314: 
 6315:   Arguments:
 6316:     $scan_data  - The hash (see scantron_getfile)
 6317:     $key        - shorthand of the key to edit (actual key is
 6318:                   scantronfilename_key).
 6319:     $data        - New value of the hash entry.
 6320:     $delete      - If true, the entry is removed from the hash.
 6321: 
 6322:   Returns:
 6323:     The new value of the hash table field (undefined if deleted).
 6324: 
 6325: =cut
 6326: 
 6327: 
 6328: sub scan_data {
 6329:     my ($scan_data,$key,$value,$delete)=@_;
 6330:     my $filename=$env{'form.scantron_selectfile'};
 6331:     if (defined($value)) {
 6332: 	$scan_data->{$filename.'_'.$key} = $value;
 6333:     }
 6334:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6335:     return $scan_data->{$filename.'_'.$key};
 6336: }
 6337: 
 6338: # ----- These first few routines are general use routines.----
 6339: 
 6340: # Return the number of occurences of a pattern in a string.
 6341: 
 6342: sub occurence_count {
 6343:     my ($string, $pattern) = @_;
 6344: 
 6345:     my @matches = ($string =~ /$pattern/g);
 6346: 
 6347:     return scalar(@matches);
 6348: }
 6349: 
 6350: 
 6351: # Take a string known to have digits and convert all the
 6352: # digits into letters in the range J,A..I.
 6353: 
 6354: sub digits_to_letters {
 6355:     my ($input) = @_;
 6356: 
 6357:     my @alphabet = ('J', 'A'..'I');
 6358: 
 6359:     my @input    = split(//, $input);
 6360:     my $output ='';
 6361:     for (my $i = 0; $i < scalar(@input); $i++) {
 6362: 	if ($input[$i] =~ /\d/) {
 6363: 	    $output .= $alphabet[$input[$i]];
 6364: 	} else {
 6365: 	    $output .= $input[$i];
 6366: 	}
 6367:     }
 6368:     return $output;
 6369: }
 6370: 
 6371: =pod 
 6372: 
 6373: =item scantron_parse_scanline
 6374: 
 6375:   Decodes a scanline from the selected scantron file
 6376: 
 6377:  Arguments:
 6378:     line             - The text of the scantron file line to process
 6379:     whichline        - Line number
 6380:     scantron_config  - Hash describing the format of the scantron lines.
 6381:     scan_data        - Hash of extra information about the scanline
 6382:                        (see scantron_getfile for more information)
 6383:     just_header      - True if should not process question answers but only
 6384:                        the stuff to the left of the answers.
 6385:     randomorder      - True if randomorder in use
 6386:     randompick       - True if randompick in use
 6387:     sequence         - Exam folder URL
 6388:     master_seq       - Ref to array containing symbs in exam folder
 6389:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6390:                        (corresponding values are resource objects)
 6391:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6392:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6393:                        are refs to an array of resource objects, ordered
 6394:                        according to order used for CODE, when randomorder
 6395:                        and or randompick are in use.
 6396:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6397:                        for current line to question number used for same question
 6398:                         in "Master Sequence" (as seen by Course Coordinator).
 6399:     startline        - Ref to hash where key is question number (0 is first)
 6400:                        and value is number of first bubble line for current 
 6401:                        student or code-based randompick and/or randomorder.
 6402:     totalref         - Ref of scalar used to score total number of bubble
 6403:                        lines needed for responses in a scan line (used when
 6404:                        randompick in use. 
 6405: 
 6406:  Returns:
 6407:    Hash containing the result of parsing the scanline
 6408: 
 6409:    Keys are all proceeded by the string 'scantron.'
 6410: 
 6411:        CODE    - the CODE in use for this scanline
 6412:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6413:                  by the operator
 6414:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6415:                             CODEs were selected, but the usage has been
 6416:                             forced by the operator
 6417:        ID  - student/employee ID
 6418:        PaperID - if used, the ID number printed on the sheet when the 
 6419:                  paper was scanned
 6420:        FirstName - first name from the sheet
 6421:        LastName  - last name from the sheet
 6422: 
 6423:      if just_header was not true these key may also exist
 6424: 
 6425:        missingerror - a list of bubble ranges that are considered to be answers
 6426:                       to a single question that don't have any bubbles filled in.
 6427:                       Of the form questionnumber:firstbubblenumber:count.
 6428:        doubleerror  - a list of bubble ranges that are considered to be answers
 6429:                       to a single question that have more than one bubble filled in.
 6430:                       Of the form questionnumber::firstbubblenumber:count
 6431:    
 6432:                 In the above, count is the number of bubble responses in the
 6433:                 input line needed to represent the possible answers to the question.
 6434:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6435:                 per line would have count = 2.
 6436: 
 6437:        maxquest     - the number of the last bubble line that was parsed
 6438: 
 6439:        (<number> starts at 1)
 6440:        <number>.answer - zero or more letters representing the selected
 6441:                          letters from the scanline for the bubble line 
 6442:                          <number>.
 6443:                          if blank there was either no bubble or there where
 6444:                          multiple bubbles, (consult the keys missingerror and
 6445:                          doubleerror if this is an error condition)
 6446: 
 6447: =cut
 6448: 
 6449: sub scantron_parse_scanline {
 6450:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6451:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6452:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6453: 
 6454:     my %record;
 6455:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6456:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6457: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6458: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6459: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6460: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6461: 	    $record{'scantron.CODE'}=substr($data,
 6462: 					    $$scantron_config{'CODEstart'}-1,
 6463: 					    $$scantron_config{'CODElength'});
 6464: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6465: 		$record{'scantron.useCODE'}=1;
 6466: 	    }
 6467: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6468: 		$record{'scantron.CODE_ignore_dup'}=1;
 6469: 	    }
 6470: 	} else {
 6471: 	    #FIXME interpret first N questions
 6472: 	}
 6473:     }
 6474:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6475: 				  $$scantron_config{'IDlength'});
 6476:     $record{'scantron.PaperID'}=
 6477: 	substr($data,$$scantron_config{'PaperID'}-1,
 6478: 	       $$scantron_config{'PaperIDlength'});
 6479:     $record{'scantron.FirstName'}=
 6480: 	substr($data,$$scantron_config{'FirstName'}-1,
 6481: 	       $$scantron_config{'FirstNamelength'});
 6482:     $record{'scantron.LastName'}=
 6483: 	substr($data,$$scantron_config{'LastName'}-1,
 6484: 	       $$scantron_config{'LastNamelength'});
 6485:     if ($just_header) { return \%record; }
 6486: 
 6487:     my @alphabet=('A'..'Z');
 6488:     my $questnum=0;
 6489:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6490: 
 6491:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6492:     if ($randompick || $randomorder) {
 6493:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6494:                                          $master_seq,$symb_to_resource,
 6495:                                          $partids_by_symb,$orderedforcode,
 6496:                                          $respnumlookup,$startline);
 6497:         if ($total) {
 6498:             $lastpos = $total*$$scantron_config{'Qlength'};
 6499:         }
 6500:         if (ref($totalref)) {
 6501:             $$totalref = $total;
 6502:         }
 6503:     }
 6504:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6505:     chomp($questions);		# Get rid of any trailing \n.
 6506:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6507:     while (length($questions)) {
 6508:         my $answers_needed;
 6509:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6510:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6511:         } else {
 6512:             $answers_needed = $bubble_lines_per_response{$questnum};
 6513:         }
 6514:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6515:                              || 1;
 6516:         $questnum++;
 6517:         my $quest_id = $questnum;
 6518:         my $currentquest = substr($questions,0,$answer_length);
 6519:         $questions       = substr($questions,$answer_length);
 6520:         if (length($currentquest) < $answer_length) { next; }
 6521: 
 6522:         my $subdivided;
 6523:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6524:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6525:         } else {
 6526:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6527:         }
 6528:         if ($subdivided =~ /,/) {
 6529:             my $subquestnum = 1;
 6530:             my $subquestions = $currentquest;
 6531:             my @subanswers_needed = split(/,/,$subdivided);
 6532:             foreach my $subans (@subanswers_needed) {
 6533:                 my $subans_length =
 6534:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6535:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6536:                 $subquestions   = substr($subquestions,$subans_length);
 6537:                 $quest_id = "$questnum.$subquestnum";
 6538:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6539:                     ($$scantron_config{'Qon'} eq 'number')) {
 6540:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6541:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6542:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6543:                         $randomorder,$randompick,$respnumlookup);
 6544:                 } else {
 6545:                     $ansnum = &scantron_validator_positional($ansnum,
 6546:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6547:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6548:                         $randomorder,$randompick,$respnumlookup);
 6549:                 }
 6550:                 $subquestnum ++;
 6551:             }
 6552:         } else {
 6553:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6554:                 ($$scantron_config{'Qon'} eq 'number')) {
 6555:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6556:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6557:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6558:                     $randomorder,$randompick,$respnumlookup);
 6559:             } else {
 6560:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6561:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6562:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6563:                     $randomorder,$randompick,$respnumlookup);
 6564:             }
 6565:         }
 6566:     }
 6567:     $record{'scantron.maxquest'}=$questnum;
 6568:     return \%record;
 6569: }
 6570: 
 6571: sub get_master_seq {
 6572:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6573:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6574:                    (ref($symb_to_resource) eq 'HASH'));
 6575:     my $resource_error;
 6576:     foreach my $resource (@{$resources}) {
 6577:         my $ressymb;
 6578:         if (ref($resource)) {
 6579:             $ressymb = $resource->symb();
 6580:             push(@{$master_seq},$ressymb);
 6581:             $symb_to_resource->{$ressymb} = $resource;
 6582:         } else {
 6583:             $resource_error = 1;
 6584:             last;
 6585:         }
 6586:     }
 6587:     return $resource_error;
 6588: }
 6589: 
 6590: sub get_respnum_lookups {
 6591:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6592:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6593:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6594:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6595:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6596:                    (ref($startline) eq 'HASH'));
 6597:     my ($user,$scancode);
 6598:     if ((exists($record->{'scantron.CODE'})) &&
 6599:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6600:         $scancode = $record->{'scantron.CODE'};
 6601:     } else {
 6602:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6603:     }
 6604:     my @mapresources =
 6605:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6606:                      $orderedforcode);
 6607:     my $total = 0;
 6608:     my $count = 0;
 6609:     foreach my $resource (@mapresources) {
 6610:         my $id = $resource->id();
 6611:         my $symb = $resource->symb();
 6612:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6613:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6614:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6615:                 if ($respnum ne '') {
 6616:                     $respnumlookup->{$count} = $respnum;
 6617:                     $startline->{$count} = $total;
 6618:                     $total += $bubble_lines_per_response{$respnum};
 6619:                     $count ++;
 6620:                 }
 6621:             }
 6622:         }
 6623:     }
 6624:     return $total;
 6625: }
 6626: 
 6627: sub scantron_validator_lettnum {
 6628:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6629:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6630:         $randompick,$respnumlookup) = @_;
 6631: 
 6632:     # Qon 'letter' implies for each slot in currquest we have:
 6633:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6634:     #    about anything else (esp. a value of Qoff) for missing
 6635:     #    bubbles.
 6636:     #
 6637:     # Qon 'number' implies each slot gives a digit that indexes the
 6638:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6639:     #    and * or ? for double bubbles on a single line.
 6640:     #
 6641: 
 6642:     my $matchon;
 6643:     if ($$scantron_config{'Qon'} eq 'letter') {
 6644:         $matchon = '[A-Z]';
 6645:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6646:         $matchon = '\d';
 6647:     }
 6648:     my $occurrences = 0;
 6649:     my $responsenum = $questnum-1;
 6650:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6651:        $responsenum = $respnumlookup->{$questnum-1}
 6652:     }
 6653:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6654:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6655:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6656:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6657:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6658:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6659:         my @singlelines = split('',$currquest);
 6660:         foreach my $entry (@singlelines) {
 6661:             $occurrences = &occurence_count($entry,$matchon);
 6662:             if ($occurrences > 1) {
 6663:                 last;
 6664:             }
 6665:         }
 6666:     } else {
 6667:         $occurrences = &occurence_count($currquest,$matchon); 
 6668:     }
 6669:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6670:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6671:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6672:             my $bubble = substr($currquest,$ans,1);
 6673:             if ($bubble =~ /$matchon/ ) {
 6674:                 if ($$scantron_config{'Qon'} eq 'number') {
 6675:                     if ($bubble == 0) {
 6676:                         $bubble = 10; 
 6677:                     }
 6678:                     $record->{"scantron.$ansnum.answer"} = 
 6679:                         $alphabet->[$bubble-1];
 6680:                 } else {
 6681:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6682:                 }
 6683:             } else {
 6684:                 $record->{"scantron.$ansnum.answer"}='';
 6685:             }
 6686:             $ansnum++;
 6687:         }
 6688:     } elsif (!defined($currquest)
 6689:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6690:             || (&occurence_count($currquest,$matchon) == 0)) {
 6691:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6692:             $record->{"scantron.$ansnum.answer"}='';
 6693:             $ansnum++;
 6694:         }
 6695:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6696:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6697:         }
 6698:     } else {
 6699:         if ($$scantron_config{'Qon'} eq 'number') {
 6700:             $currquest = &digits_to_letters($currquest);            
 6701:         }
 6702:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6703:             my $bubble = substr($currquest,$ans,1);
 6704:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6705:             $ansnum++;
 6706:         }
 6707:     }
 6708:     return $ansnum;
 6709: }
 6710: 
 6711: sub scantron_validator_positional {
 6712:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6713:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6714:         $randomorder,$randompick,$respnumlookup) = @_;
 6715: 
 6716:     # Otherwise there's a positional notation;
 6717:     # each bubble line requires Qlength items, and there are filled in
 6718:     # bubbles for each case where there 'Qon' characters.
 6719:     #
 6720: 
 6721:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6722: 
 6723:     # If the split only gives us one element.. the full length of the
 6724:     # answer string, no bubbles are filled in:
 6725: 
 6726:     if ($answers_needed eq '') {
 6727:         return;
 6728:     }
 6729: 
 6730:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6731:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6732:             $record->{"scantron.$ansnum.answer"}='';
 6733:             $ansnum++;
 6734:         }
 6735:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6736:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6737:         }
 6738:     } elsif (scalar(@array) == 2) {
 6739:         my $location = length($array[0]);
 6740:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6741:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6742:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6743:             if ($ans eq $line_num) {
 6744:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6745:             } else {
 6746:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6747:             }
 6748:             $ansnum++;
 6749:          }
 6750:     } else {
 6751:         #  If there's more than one instance of a bubble character
 6752:         #  That's a double bubble; with positional notation we can
 6753:         #  record all the bubbles filled in as well as the
 6754:         #  fact this response consists of multiple bubbles.
 6755:         #
 6756:         my $responsenum = $questnum-1;
 6757:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6758:             $responsenum = $respnumlookup->{$questnum-1}
 6759:         }
 6760:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6761:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6762:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6763:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6764:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6765:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6766:             my $doubleerror = 0;
 6767:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6768:                    (!$doubleerror)) {
 6769:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6770:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6771:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6772:                if (length(@currarray) > 2) {
 6773:                    $doubleerror = 1;
 6774:                } 
 6775:             }
 6776:             if ($doubleerror) {
 6777:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6778:             }
 6779:         } else {
 6780:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6781:         }
 6782:         my $item = $ansnum;
 6783:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6784:             $record->{"scantron.$item.answer"} = '';
 6785:             $item ++;
 6786:         }
 6787: 
 6788:         my @ans=@array;
 6789:         my $i=0;
 6790:         my $increment = 0;
 6791:         while ($#ans) {
 6792:             $i+=length($ans[0]) + $increment;
 6793:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6794:             my $bubble = $i%$$scantron_config{'Qlength'};
 6795:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6796:             shift(@ans);
 6797:             $increment = 1;
 6798:         }
 6799:         $ansnum += $answers_needed;
 6800:     }
 6801:     return $ansnum;
 6802: }
 6803: 
 6804: =pod
 6805: 
 6806: =item scantron_add_delay
 6807: 
 6808:    Adds an error message that occurred during the grading phase to a
 6809:    queue of messages to be shown after grading pass is complete
 6810: 
 6811:  Arguments:
 6812:    $delayqueue  - arrary ref of hash ref of error messages
 6813:    $scanline    - the scanline that caused the error
 6814:    $errormesage - the error message
 6815:    $errorcode   - a numeric code for the error
 6816: 
 6817:  Side Effects:
 6818:    updates the $delayqueue to have a new hash ref of the error
 6819: 
 6820: =cut
 6821: 
 6822: sub scantron_add_delay {
 6823:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6824:     push(@$delayqueue,
 6825: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6826: 	  'ecode' => $errorcode }
 6827: 	 );
 6828: }
 6829: 
 6830: =pod
 6831: 
 6832: =item scantron_find_student
 6833: 
 6834:    Finds the username for the current scanline
 6835: 
 6836:   Arguments:
 6837:    $scantron_record - hash result from scantron_parse_scanline
 6838:    $scan_data       - hash of correction information 
 6839:                       (see &scantron_getfile() form more information)
 6840:    $idmap           - hash from &username_to_idmap()
 6841:    $line            - number of current scanline
 6842:  
 6843:   Returns:
 6844:    Either 'username:domain' or undef if unknown
 6845: 
 6846: =cut
 6847: 
 6848: sub scantron_find_student {
 6849:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6850:     my $scanID=$$scantron_record{'scantron.ID'};
 6851:     if ($scanID =~ /^\s*$/) {
 6852:  	return &scan_data($scan_data,"$line.user");
 6853:     }
 6854:     foreach my $id (keys(%$idmap)) {
 6855:  	if (lc($id) eq lc($scanID)) {
 6856:  	    return $$idmap{$id};
 6857:  	}
 6858:     }
 6859:     return undef;
 6860: }
 6861: 
 6862: =pod
 6863: 
 6864: =item scantron_filter
 6865: 
 6866:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6867:    hidden resources was selected
 6868: 
 6869: =cut
 6870: 
 6871: sub scantron_filter {
 6872:     my ($curres)=@_;
 6873: 
 6874:     if (ref($curres) && $curres->is_problem()) {
 6875: 	# if the user has asked to not have either hidden
 6876: 	# or 'randomout' controlled resources to be graded
 6877: 	# don't include them
 6878: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6879: 	    && $curres->randomout) {
 6880: 	    return 0;
 6881: 	}
 6882: 	return 1;
 6883:     }
 6884:     return 0;
 6885: }
 6886: 
 6887: =pod
 6888: 
 6889: =item scantron_process_corrections
 6890: 
 6891:    Gets correction information out of submitted form data and corrects
 6892:    the scanline
 6893: 
 6894: =cut
 6895: 
 6896: sub scantron_process_corrections {
 6897:     my ($r) = @_;
 6898:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6899:     my ($scanlines,$scan_data)=&scantron_getfile();
 6900:     my $classlist=&Apache::loncoursedata::get_classlist();
 6901:     my $which=$env{'form.scantron_line'};
 6902:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6903:     my ($skip,$err,$errmsg);
 6904:     if ($env{'form.scantron_skip_record'}) {
 6905: 	$skip=1;
 6906:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6907: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6908: 	    $env{'form.scantron_domain'};
 6909: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6910: 	($line,$err,$errmsg)=
 6911: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6912: 				     'ID',{'newid'=>$newid,
 6913: 				    'username'=>$env{'form.scantron_username'},
 6914: 				    'domain'=>$env{'form.scantron_domain'}});
 6915:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6916: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6917: 	my $newCODE;
 6918: 	my %args;
 6919: 	if      ($resolution eq 'use_unfound') {
 6920: 	    $newCODE='use_unfound';
 6921: 	} elsif ($resolution eq 'use_found') {
 6922: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6923: 	} elsif ($resolution eq 'use_typed') {
 6924: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6925: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6926: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6927: 	}
 6928: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6929: 	    $args{'CODE_ignore_dup'}=1;
 6930: 	}
 6931: 	$args{'CODE'}=$newCODE;
 6932: 	($line,$err,$errmsg)=
 6933: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6934: 				     'CODE',\%args);
 6935:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6936: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6937: 	    ($line,$err,$errmsg)=
 6938: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6939: 					 $which,'answer',
 6940: 					 { 'question'=>$question,
 6941: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6942:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6943: 	    if ($err) { last; }
 6944: 	}
 6945:     }
 6946:     if ($err) {
 6947: 	$r->print(
 6948:             '<p class="LC_error">'
 6949:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6950:                 $errmsg)
 6951:            .'</p>');
 6952:     } else {
 6953: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6954: 	&scantron_putfile($scanlines,$scan_data);
 6955:     }
 6956: }
 6957: 
 6958: =pod
 6959: 
 6960: =item reset_skipping_status
 6961: 
 6962:    Forgets the current set of remember skipped scanlines (and thus
 6963:    reverts back to considering all lines in the
 6964:    scantron_skipped_<filename> file)
 6965: 
 6966: =cut
 6967: 
 6968: sub reset_skipping_status {
 6969:     my ($scanlines,$scan_data)=&scantron_getfile();
 6970:     &scan_data($scan_data,'remember_skipping',undef,1);
 6971:     &scantron_putfile(undef,$scan_data);
 6972: }
 6973: 
 6974: =pod
 6975: 
 6976: =item start_skipping
 6977: 
 6978:    Marks a scanline to be skipped. 
 6979: 
 6980: =cut
 6981: 
 6982: sub start_skipping {
 6983:     my ($scan_data,$i)=@_;
 6984:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6985:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6986: 	$remembered{$i}=2;
 6987:     } else {
 6988: 	$remembered{$i}=1;
 6989:     }
 6990:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6991: }
 6992: 
 6993: =pod
 6994: 
 6995: =item should_be_skipped
 6996: 
 6997:    Checks whether a scanline should be skipped.
 6998: 
 6999: =cut
 7000: 
 7001: sub should_be_skipped {
 7002:     my ($scanlines,$scan_data,$i)=@_;
 7003:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7004: 	# not redoing old skips
 7005: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7006: 	return 0;
 7007:     }
 7008:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7009: 
 7010:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7011: 	return 0;
 7012:     }
 7013:     return 1;
 7014: }
 7015: 
 7016: =pod
 7017: 
 7018: =item remember_current_skipped
 7019: 
 7020:    Discovers what scanlines are in the scantron_skipped_<filename>
 7021:    file and remembers them into scan_data for later use.
 7022: 
 7023: =cut
 7024: 
 7025: sub remember_current_skipped {
 7026:     my ($scanlines,$scan_data)=&scantron_getfile();
 7027:     my %to_remember;
 7028:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7029: 	if ($scanlines->{'skipped'}[$i]) {
 7030: 	    $to_remember{$i}=1;
 7031: 	}
 7032:     }
 7033: 
 7034:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7035:     &scantron_putfile(undef,$scan_data);
 7036: }
 7037: 
 7038: =pod
 7039: 
 7040: =item check_for_error
 7041: 
 7042:     Checks if there was an error when attempting to remove a specific
 7043:     scantron_.. bubblesheet data file. Prints out an error if
 7044:     something went wrong.
 7045: 
 7046: =cut
 7047: 
 7048: sub check_for_error {
 7049:     my ($r,$result)=@_;
 7050:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7051: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7052:     }
 7053: }
 7054: 
 7055: =pod
 7056: 
 7057: =item scantron_warning_screen
 7058: 
 7059:    Interstitial screen to make sure the operator has selected the
 7060:    correct options before we start the validation phase.
 7061: 
 7062: =cut
 7063: 
 7064: sub scantron_warning_screen {
 7065:     my ($button_text,$symb)=@_;
 7066:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7067:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7068:     my $CODElist;
 7069:     if ($scantron_config{'CODElocation'} &&
 7070: 	$scantron_config{'CODEstart'} &&
 7071: 	$scantron_config{'CODElength'}) {
 7072: 	$CODElist=$env{'form.scantron_CODElist'};
 7073: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7074: 	$CODElist=
 7075: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7076: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7077:     }
 7078:     my $lastbubblepoints;
 7079:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7080:         $lastbubblepoints =
 7081:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7082:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7083:     }
 7084:     return ('
 7085: <p>
 7086: <span class="LC_warning">
 7087: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7088: </p>
 7089: <table>
 7090: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7091: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7092: '.$CODElist.$lastbubblepoints.'
 7093: </table>
 7094: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7095: '.&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>
 7096: 
 7097: <br />
 7098: ');
 7099: }
 7100: 
 7101: =pod
 7102: 
 7103: =item scantron_do_warning
 7104: 
 7105:    Check if the operator has picked something for all required
 7106:    fields. Error out if something is missing.
 7107: 
 7108: =cut
 7109: 
 7110: sub scantron_do_warning {
 7111:     my ($r,$symb)=@_;
 7112:     if (!$symb) {return '';}
 7113:     my $default_form_data=&defaultFormData($symb);
 7114:     $r->print(&scantron_form_start().$default_form_data);
 7115:     if ( $env{'form.selectpage'} eq '' ||
 7116: 	 $env{'form.scantron_selectfile'} eq '' ||
 7117: 	 $env{'form.scantron_format'} eq '' ) {
 7118: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7119: 	if ( $env{'form.selectpage'} eq '') {
 7120: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7121: 	} 
 7122: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7123: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7124: 	} 
 7125: 	if ( $env{'form.scantron_format'} eq '') {
 7126: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7127: 	} 
 7128:     } else {
 7129: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7130:         my $bubbledbyhand=&hand_bubble_option();
 7131: 	$r->print('
 7132: '.$warning.$bubbledbyhand.'
 7133: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7134: <input type="hidden" name="command" value="scantron_validate" />
 7135: ');
 7136:     }
 7137:     $r->print("</form><br />");
 7138:     return '';
 7139: }
 7140: 
 7141: =pod
 7142: 
 7143: =item scantron_form_start
 7144: 
 7145:     html hidden input for remembering all selected grading options
 7146: 
 7147: =cut
 7148: 
 7149: sub scantron_form_start {
 7150:     my ($max_bubble)=@_;
 7151:     my $result= <<SCANTRONFORM;
 7152: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7153:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7154:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7155:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7156:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7157:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7158:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7159:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7160:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7161:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7162: SCANTRONFORM
 7163: 
 7164:   my $line = 0;
 7165:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7166:        my $chunk =
 7167: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7168:        $chunk .=
 7169: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7170:        $chunk .= 
 7171:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7172:        $chunk .=
 7173:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7174:        $chunk .=
 7175:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7176:        $result .= $chunk;
 7177:        $line++;
 7178:     }
 7179:     return $result;
 7180: }
 7181: 
 7182: =pod
 7183: 
 7184: =item scantron_validate_file
 7185: 
 7186:     Dispatch routine for doing validation of a bubblesheet data file.
 7187: 
 7188:     Also processes any necessary information resets that need to
 7189:     occur before validation begins (ignore previous corrections,
 7190:     restarting the skipped records processing)
 7191: 
 7192: =cut
 7193: 
 7194: sub scantron_validate_file {
 7195:     my ($r,$symb) = @_;
 7196:     if (!$symb) {return '';}
 7197:     my $default_form_data=&defaultFormData($symb);
 7198:     
 7199:     # do the detection of only doing skipped records first before we delete
 7200:     # them when doing the corrections reset
 7201:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7202: 	&reset_skipping_status();
 7203:     }
 7204:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7205: 	&remember_current_skipped();
 7206: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7207:     }
 7208: 
 7209:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7210: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7211: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7212: 	&check_for_error($r,&scantron_remove_scan_data());
 7213: 	$env{'form.scantron_options_ignore'}='done';
 7214:     }
 7215: 
 7216:     if ($env{'form.scantron_corrections'}) {
 7217: 	&scantron_process_corrections($r);
 7218:     }
 7219:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7220:     #get the student pick code ready
 7221:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7222:     my $nav_error;
 7223:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7224:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7225:     if ($nav_error) {
 7226:         $r->print(&navmap_errormsg());
 7227:         return '';
 7228:     }
 7229:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7230:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7231:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7232:     }
 7233:     $r->print($result);
 7234:     
 7235:     my @validate_phases=( 'sequence',
 7236: 			  'ID',
 7237: 			  'CODE',
 7238: 			  'doublebubble',
 7239: 			  'missingbubbles');
 7240:     if (!$env{'form.validatepass'}) {
 7241: 	$env{'form.validatepass'} = 0;
 7242:     }
 7243:     my $currentphase=$env{'form.validatepass'};
 7244: 
 7245: 
 7246:     my $stop=0;
 7247:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7248: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7249: 	$r->rflush();
 7250: 
 7251: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7252: 	{
 7253: 	    no strict 'refs';
 7254: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7255: 	}
 7256:     }
 7257:     if (!$stop) {
 7258: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7259: 	$r->print(&mt('Validation process complete.').'<br />'.
 7260:                   $warning.
 7261:                   &mt('Perform verification for each student after storage of submissions?').
 7262:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7263:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7264:                   ('&nbsp;'x3).'<label>'.
 7265:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7266:                   '</label></span><br />'.
 7267:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7268:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7269:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7270:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7271:     } else {
 7272: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7273: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7274:     }
 7275:     if ($stop) {
 7276: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7277: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7278: 	    $r->print(' '.&mt('this error').' <br />');
 7279: 
 7280:             $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>');
 7281: 	} else {
 7282:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7283: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7284:             } else {
 7285:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7286:             }
 7287: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7288: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7289: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7290: 	}
 7291:     }
 7292:     $r->print(" </form><br />");
 7293:     return '';
 7294: }
 7295: 
 7296: 
 7297: =pod
 7298: 
 7299: =item scantron_remove_file
 7300: 
 7301:    Removes the requested bubblesheet data file, makes sure that
 7302:    scantron_original_<filename> is never removed
 7303: 
 7304: 
 7305: =cut
 7306: 
 7307: sub scantron_remove_file {
 7308:     my ($which)=@_;
 7309:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7310:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7311:     my $file='scantron_';
 7312:     if ($which eq 'corrected' || $which eq 'skipped') {
 7313: 	$file.=$which.'_';
 7314:     } else {
 7315: 	return 'refused';
 7316:     }
 7317:     $file.=$env{'form.scantron_selectfile'};
 7318:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7319: }
 7320: 
 7321: 
 7322: =pod
 7323: 
 7324: =item scantron_remove_scan_data
 7325: 
 7326:    Removes all scan_data correction for the requested bubblesheet
 7327:    data file.  (In the case that both the are doing skipped records we need
 7328:    to remember the old skipped lines for the time being so that element
 7329:    persists for a while.)
 7330: 
 7331: =cut
 7332: 
 7333: sub scantron_remove_scan_data {
 7334:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7335:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7336:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7337:     my @todelete;
 7338:     my $filename=$env{'form.scantron_selectfile'};
 7339:     foreach my $key (@keys) {
 7340: 	if ($key=~/^\Q$filename\E_/) {
 7341: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7342: 		$key=~/remember_skipping/) {
 7343: 		next;
 7344: 	    }
 7345: 	    push(@todelete,$key);
 7346: 	}
 7347:     }
 7348:     my $result;
 7349:     if (@todelete) {
 7350: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7351: 				       \@todelete,$cdom,$cname);
 7352:     } else {
 7353: 	$result = 'ok';
 7354:     }
 7355:     return $result;
 7356: }
 7357: 
 7358: 
 7359: =pod
 7360: 
 7361: =item scantron_getfile
 7362: 
 7363:     Fetches the requested bubblesheet data file (all 3 versions), and
 7364:     the scan_data hash
 7365:   
 7366:   Arguments:
 7367:     None
 7368: 
 7369:   Returns:
 7370:     2 hash references
 7371: 
 7372:      - first one has 
 7373:          orig      -
 7374:          corrected -
 7375:          skipped   -  each of which points to an array ref of the specified
 7376:                       file broken up into individual lines
 7377:          count     - number of scanlines
 7378:  
 7379:      - second is the scan_data hash possible keys are
 7380:        ($number refers to scanline numbered $number and thus the key affects
 7381:         only that scanline
 7382:         $bubline refers to the specific bubble line element and the aspects
 7383:         refers to that specific bubble line element)
 7384: 
 7385:        $number.user - username:domain to use
 7386:        $number.CODE_ignore_dup 
 7387:                     - ignore the duplicate CODE error 
 7388:        $number.useCODE
 7389:                     - use the CODE in the scanline as is
 7390:        $number.no_bubble.$bubline
 7391:                     - it is valid that there is no bubbled in bubble
 7392:                       at $number $bubline
 7393:        remember_skipping
 7394:                     - a frozen hash containing keys of $number and values
 7395:                       of either 
 7396:                         1 - we are on a 'do skipped records pass' and plan
 7397:                             on processing this line
 7398:                         2 - we are on a 'do skipped records pass' and this
 7399:                             scanline has been marked to skip yet again
 7400: 
 7401: =cut
 7402: 
 7403: sub scantron_getfile {
 7404:     #FIXME really would prefer a scantron directory
 7405:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7406:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7407:     my $lines;
 7408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7409: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7410:     my %scanlines;
 7411:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7412:     my $temp=$scanlines{'orig'};
 7413:     $scanlines{'count'}=$#$temp;
 7414: 
 7415:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7416: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7417:     if ($lines eq '-1') {
 7418: 	$scanlines{'corrected'}=[];
 7419:     } else {
 7420: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7421:     }
 7422:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7423: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7424:     if ($lines eq '-1') {
 7425: 	$scanlines{'skipped'}=[];
 7426:     } else {
 7427: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7428:     }
 7429:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7430:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7431:     my %scan_data = @tmp;
 7432:     return (\%scanlines,\%scan_data);
 7433: }
 7434: 
 7435: =pod
 7436: 
 7437: =item lonnet_putfile
 7438: 
 7439:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7440: 
 7441:  Arguments:
 7442:    $contents - data to store
 7443:    $filename - filename to store $contents into
 7444: 
 7445:  Returns:
 7446:    result value from &Apache::lonnet::finishuserfileupload
 7447: 
 7448: =cut
 7449: 
 7450: sub lonnet_putfile {
 7451:     my ($contents,$filename)=@_;
 7452:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7453:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7454:     $env{'form.sillywaytopassafilearound'}=$contents;
 7455:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7456: 
 7457: }
 7458: 
 7459: =pod
 7460: 
 7461: =item scantron_putfile
 7462: 
 7463:     Stores the current version of the bubblesheet data files, and the
 7464:     scan_data hash. (Does not modify the original version only the
 7465:     corrected and skipped versions.
 7466: 
 7467:  Arguments:
 7468:     $scanlines - hash ref that looks like the first return value from
 7469:                  &scantron_getfile()
 7470:     $scan_data - hash ref that looks like the second return value from
 7471:                  &scantron_getfile()
 7472: 
 7473: =cut
 7474: 
 7475: sub scantron_putfile {
 7476:     my ($scanlines,$scan_data) = @_;
 7477:     #FIXME really would prefer a scantron directory
 7478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7480:     if ($scanlines) {
 7481: 	my $prefix='scantron_';
 7482: # no need to update orig, shouldn't change
 7483: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7484: #		    $env{'form.scantron_selectfile'});
 7485: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7486: 			$prefix.'corrected_'.
 7487: 			$env{'form.scantron_selectfile'});
 7488: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7489: 			$prefix.'skipped_'.
 7490: 			$env{'form.scantron_selectfile'});
 7491:     }
 7492:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7493: }
 7494: 
 7495: =pod
 7496: 
 7497: =item scantron_get_line
 7498: 
 7499:    Returns the correct version of the scanline
 7500: 
 7501:  Arguments:
 7502:     $scanlines - hash ref that looks like the first return value from
 7503:                  &scantron_getfile()
 7504:     $scan_data - hash ref that looks like the second return value from
 7505:                  &scantron_getfile()
 7506:     $i         - number of the requested line (starts at 0)
 7507: 
 7508:  Returns:
 7509:    A scanline, (either the original or the corrected one if it
 7510:    exists), or undef if the requested scanline should be
 7511:    skipped. (Either because it's an skipped scanline, or it's an
 7512:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7513:    pass.
 7514: 
 7515: =cut
 7516: 
 7517: sub scantron_get_line {
 7518:     my ($scanlines,$scan_data,$i)=@_;
 7519:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7520:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7521:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7522:     return $scanlines->{'orig'}[$i]; 
 7523: }
 7524: 
 7525: =pod
 7526: 
 7527: =item scantron_todo_count
 7528: 
 7529:     Counts the number of scanlines that need processing.
 7530: 
 7531:  Arguments:
 7532:     $scanlines - hash ref that looks like the first return value from
 7533:                  &scantron_getfile()
 7534:     $scan_data - hash ref that looks like the second return value from
 7535:                  &scantron_getfile()
 7536: 
 7537:  Returns:
 7538:     $count - number of scanlines to process
 7539: 
 7540: =cut
 7541: 
 7542: sub get_todo_count {
 7543:     my ($scanlines,$scan_data)=@_;
 7544:     my $count=0;
 7545:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7546: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7547: 	if ($line=~/^[\s\cz]*$/) { next; }
 7548: 	$count++;
 7549:     }
 7550:     return $count;
 7551: }
 7552: 
 7553: =pod
 7554: 
 7555: =item scantron_put_line
 7556: 
 7557:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7558:     data file.
 7559: 
 7560:  Arguments:
 7561:     $scanlines - hash ref that looks like the first return value from
 7562:                  &scantron_getfile()
 7563:     $scan_data - hash ref that looks like the second return value from
 7564:                  &scantron_getfile()
 7565:     $i         - line number to update
 7566:     $newline   - contents of the updated scanline
 7567:     $skip      - if true make the line for skipping and update the
 7568:                  'skipped' file
 7569: 
 7570: =cut
 7571: 
 7572: sub scantron_put_line {
 7573:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7574:     if ($skip) {
 7575: 	$scanlines->{'skipped'}[$i]=$newline;
 7576: 	&start_skipping($scan_data,$i);
 7577: 	return;
 7578:     }
 7579:     $scanlines->{'corrected'}[$i]=$newline;
 7580: }
 7581: 
 7582: =pod
 7583: 
 7584: =item scantron_clear_skip
 7585: 
 7586:    Remove a line from the 'skipped' file
 7587: 
 7588:  Arguments:
 7589:     $scanlines - hash ref that looks like the first return value from
 7590:                  &scantron_getfile()
 7591:     $scan_data - hash ref that looks like the second return value from
 7592:                  &scantron_getfile()
 7593:     $i         - line number to update
 7594: 
 7595: =cut
 7596: 
 7597: sub scantron_clear_skip {
 7598:     my ($scanlines,$scan_data,$i)=@_;
 7599:     if (exists($scanlines->{'skipped'}[$i])) {
 7600: 	undef($scanlines->{'skipped'}[$i]);
 7601: 	return 1;
 7602:     }
 7603:     return 0;
 7604: }
 7605: 
 7606: =pod
 7607: 
 7608: =item scantron_filter_not_exam
 7609: 
 7610:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7611:    filter out resources that are not marked as 'exam' mode
 7612: 
 7613: =cut
 7614: 
 7615: sub scantron_filter_not_exam {
 7616:     my ($curres)=@_;
 7617:     
 7618:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7619: 	# if the user has asked to not have either hidden
 7620: 	# or 'randomout' controlled resources to be graded
 7621: 	# don't include them
 7622: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7623: 	    && $curres->randomout) {
 7624: 	    return 0;
 7625: 	}
 7626: 	return 1;
 7627:     }
 7628:     return 0;
 7629: }
 7630: 
 7631: =pod
 7632: 
 7633: =item scantron_validate_sequence
 7634: 
 7635:     Validates the selected sequence, checking for resource that are
 7636:     not set to exam mode.
 7637: 
 7638: =cut
 7639: 
 7640: sub scantron_validate_sequence {
 7641:     my ($r,$currentphase) = @_;
 7642: 
 7643:     my $navmap=Apache::lonnavmaps::navmap->new();
 7644:     unless (ref($navmap)) {
 7645:         $r->print(&navmap_errormsg());
 7646:         return (1,$currentphase);
 7647:     }
 7648:     my (undef,undef,$sequence)=
 7649: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7650: 
 7651:     my $map=$navmap->getResourceByUrl($sequence);
 7652: 
 7653:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7654:                                     value="ignore" />');
 7655:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7656: 	my @resources=
 7657: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7658: 	if (@resources) {
 7659: 	    $r->print('<p class="LC_warning">'
 7660:                .&mt('Some resources in the sequence currently are not set to'
 7661:                    .' exam mode. Grading these resources currently may not'
 7662:                    .' work correctly.')
 7663:                .'</p>'
 7664:             );
 7665: 	    return (1,$currentphase);
 7666: 	}
 7667:     }
 7668: 
 7669:     return (0,$currentphase+1);
 7670: }
 7671: 
 7672: 
 7673: 
 7674: sub scantron_validate_ID {
 7675:     my ($r,$currentphase) = @_;
 7676:     
 7677:     #get student info
 7678:     my $classlist=&Apache::loncoursedata::get_classlist();
 7679:     my %idmap=&username_to_idmap($classlist);
 7680: 
 7681:     #get scantron line setup
 7682:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7683:     my ($scanlines,$scan_data)=&scantron_getfile();
 7684: 
 7685:     my $nav_error;
 7686:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7687:     if ($nav_error) {
 7688:         $r->print(&navmap_errormsg());
 7689:         return(1,$currentphase);
 7690:     }
 7691: 
 7692:     my %found=('ids'=>{},'usernames'=>{});
 7693:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7694: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7695: 	if ($line=~/^[\s\cz]*$/) { next; }
 7696: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7697: 						 $scan_data);
 7698: 	my $id=$$scan_record{'scantron.ID'};
 7699: 	my $found;
 7700: 	foreach my $checkid (keys(%idmap)) {
 7701: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7702: 	}
 7703: 	if ($found) {
 7704: 	    my $username=$idmap{$found};
 7705: 	    if ($found{'ids'}{$found}) {
 7706: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7707: 					 $line,'duplicateID',$found);
 7708: 		return(1,$currentphase);
 7709: 	    } elsif ($found{'usernames'}{$username}) {
 7710: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7711: 					 $line,'duplicateID',$username);
 7712: 		return(1,$currentphase);
 7713: 	    }
 7714: 	    #FIXME store away line we previously saw the ID on to use above
 7715: 	    $found{'ids'}{$found}++;
 7716: 	    $found{'usernames'}{$username}++;
 7717: 	} else {
 7718: 	    if ($id =~ /^\s*$/) {
 7719: 		my $username=&scan_data($scan_data,"$i.user");
 7720: 		if (defined($username) && $found{'usernames'}{$username}) {
 7721: 		    &scantron_get_correction($r,$i,$scan_record,
 7722: 					     \%scantron_config,
 7723: 					     $line,'duplicateID',$username);
 7724: 		    return(1,$currentphase);
 7725: 		} elsif (!defined($username)) {
 7726: 		    &scantron_get_correction($r,$i,$scan_record,
 7727: 					     \%scantron_config,
 7728: 					     $line,'incorrectID');
 7729: 		    return(1,$currentphase);
 7730: 		}
 7731: 		$found{'usernames'}{$username}++;
 7732: 	    } else {
 7733: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7734: 					 $line,'incorrectID');
 7735: 		return(1,$currentphase);
 7736: 	    }
 7737: 	}
 7738:     }
 7739: 
 7740:     return (0,$currentphase+1);
 7741: }
 7742: 
 7743: 
 7744: sub scantron_get_correction {
 7745:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7746:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7747: #FIXME in the case of a duplicated ID the previous line, probably need
 7748: #to show both the current line and the previous one and allow skipping
 7749: #the previous one or the current one
 7750: 
 7751:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7752:         $r->print(
 7753:             '<p class="LC_warning">'
 7754:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7755:                 "<b>$error</b>",
 7756:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7757:            ."</p> \n");
 7758:     } else {
 7759:         $r->print(
 7760:             '<p class="LC_warning">'
 7761:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7762:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7763:            ."</p> \n");
 7764:     }
 7765:     my $message =
 7766:         '<p>'
 7767:        .&mt('The ID on the form is [_1]',
 7768:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7769:        .'<br />'
 7770:        .&mt('The name on the paper is [_1], [_2]',
 7771:             $$scan_record{'scantron.LastName'},
 7772:             $$scan_record{'scantron.FirstName'})
 7773:        .'</p>';
 7774: 
 7775:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7776:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7777:                            # Array populated for doublebubble or
 7778:     my @lines_to_correct;  # missingbubble errors to build javascript
 7779:                            # to validate radio button checking   
 7780: 
 7781:     if ($error =~ /ID$/) {
 7782: 	if ($error eq 'incorrectID') {
 7783: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7784: 		      "</p>\n");
 7785: 	} elsif ($error eq 'duplicateID') {
 7786: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7787: 	}
 7788: 	$r->print($message);
 7789: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7790: 	$r->print("\n<ul><li> ");
 7791: 	#FIXME it would be nice if this sent back the user ID and
 7792: 	#could do partial userID matches
 7793: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7794: 				       'scantron_username','scantron_domain'));
 7795: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7796: 	$r->print("\n:\n".
 7797: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7798: 
 7799: 	$r->print('</li>');
 7800:     } elsif ($error =~ /CODE$/) {
 7801: 	if ($error eq 'incorrectCODE') {
 7802: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7803: 	} elsif ($error eq 'duplicateCODE') {
 7804: 	    $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");
 7805: 	}
 7806:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7807:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7808:                  ."</p>\n");
 7809: 	$r->print($message);
 7810: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7811: 	$r->print("\n<br /> ");
 7812: 	my $i=0;
 7813: 	if ($error eq 'incorrectCODE' 
 7814: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7815: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7816: 	    if ($closest > 0) {
 7817: 		foreach my $testcode (@{$closest}) {
 7818: 		    my $checked='';
 7819: 		    if (!$i) { $checked=' checked="checked"'; }
 7820: 		    $r->print("
 7821:    <label>
 7822:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7823:        ".&mt("Use the similar CODE [_1] instead.",
 7824: 	    "<b><tt>".$testcode."</tt></b>")."
 7825:     </label>
 7826:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7827: 		    $r->print("\n<br />");
 7828: 		    $i++;
 7829: 		}
 7830: 	    }
 7831: 	}
 7832: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7833: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7834: 	    $r->print("
 7835:     <label>
 7836:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7837:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7838: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7839:     </label>");
 7840: 	    $r->print("\n<br />");
 7841: 	}
 7842: 
 7843: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7844: function change_radio(field) {
 7845:     var slct=document.scantronupload.scantron_CODE_resolution;
 7846:     var i;
 7847:     for (i=0;i<slct.length;i++) {
 7848:         if (slct[i].value==field) { slct[i].checked=true; }
 7849:     }
 7850: }
 7851: ENDSCRIPT
 7852: 	my $href="/adm/pickcode?".
 7853: 	   "form=".&escape("scantronupload").
 7854: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7855: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7856: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7857: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7858: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7859: 	    $r->print("
 7860:     <label>
 7861:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7862:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7863: 	     "<a target='_blank' href='$href'>","</a>")."
 7864:     </label> 
 7865:     ".&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\')" />'));
 7866: 	    $r->print("\n<br />");
 7867: 	}
 7868: 	$r->print("
 7869:     <label>
 7870:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7871:        ".&mt("Use [_1] as the CODE.",
 7872: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7873: 	$r->print("\n<br /><br />");
 7874:     } elsif ($error eq 'doublebubble') {
 7875: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7876: 
 7877: 	# The form field scantron_questions is acutally a list of line numbers.
 7878: 	# represented by this form so:
 7879: 
 7880: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7881:                                                 $respnumlookup,$startline);
 7882: 
 7883: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7884: 		  $line_list.'" />');
 7885: 	$r->print($message);
 7886: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7887: 	foreach my $question (@{$arg}) {
 7888: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7889:                                                    $scan_record, $error,
 7890:                                                    $randomorder,$randompick,
 7891:                                                    $respnumlookup,$startline);
 7892:             push(@lines_to_correct,@linenums);
 7893: 	}
 7894:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7895:     } elsif ($error eq 'missingbubble') {
 7896: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7897: 	$r->print($message);
 7898: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7899: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7900: 
 7901: 	# The form field scantron_questions is actually a list of line numbers not
 7902: 	# a list of question numbers. Therefore:
 7903: 	#
 7904: 	
 7905: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7906:                                                 $respnumlookup,$startline);
 7907: 
 7908: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7909: 		  $line_list.'" />');
 7910: 	foreach my $question (@{$arg}) {
 7911: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7912:                                                    $scan_record, $error,
 7913:                                                    $randomorder,$randompick,
 7914:                                                    $respnumlookup,$startline);
 7915:             push(@lines_to_correct,@linenums);
 7916: 	}
 7917:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7918:     } else {
 7919: 	$r->print("\n<ul>");
 7920:     }
 7921:     $r->print("\n</li></ul>");
 7922: }
 7923: 
 7924: sub verify_bubbles_checked {
 7925:     my (@ansnums) = @_;
 7926:     my $ansnumstr = join('","',@ansnums);
 7927:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7928:     &js_escape(\$warning);
 7929:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 7930: function verify_bubble_radio(form) {
 7931:     var ansnumArray = new Array ("$ansnumstr");
 7932:     var need_bubble_count = 0;
 7933:     for (var i=0; i<ansnumArray.length; i++) {
 7934:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7935:             var bubble_picked = 0; 
 7936:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7937:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7938:                     bubble_picked = 1;
 7939:                 }
 7940:             }
 7941:             if (bubble_picked == 0) {
 7942:                 need_bubble_count ++;
 7943:             }
 7944:         }
 7945:     }
 7946:     if (need_bubble_count) {
 7947:         alert("$warning");
 7948:         return;
 7949:     }
 7950:     form.submit(); 
 7951: }
 7952: ENDSCRIPT
 7953:     return $output;
 7954: }
 7955: 
 7956: =pod
 7957: 
 7958: =item  questions_to_line_list
 7959: 
 7960: Converts a list of questions into a string of comma separated
 7961: line numbers in the answer sheet used by the questions.  This is
 7962: used to fill in the scantron_questions form field.
 7963: 
 7964:   Arguments:
 7965:      questions    - Reference to an array of questions.
 7966:      randomorder  - True if randomorder in use.
 7967:      randompick   - True if randompick in use.
 7968:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7969:                      for current line to question number used for same question
 7970:                      in "Master Seqence" (as seen by Course Coordinator).
 7971:      startline    - Reference to hash where key is question number (0 is first)
 7972:                     and key is number of first bubble line for current student
 7973:                     or code-based randompick and/or randomorder.
 7974: 
 7975: =cut
 7976: 
 7977: 
 7978: sub questions_to_line_list {
 7979:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7980:     my @lines;
 7981: 
 7982:     foreach my $item (@{$questions}) {
 7983:         my $question = $item;
 7984:         my ($first,$count,$last);
 7985:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7986:             $question = $1;
 7987:             my $subquestion = $2;
 7988:             my $responsenum = $question-1;
 7989:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7990:                 $responsenum = $respnumlookup->{$question-1};
 7991:                 if (ref($startline) eq 'HASH') {
 7992:                     $first = $startline->{$question-1} + 1;
 7993:                 }
 7994:             } else {
 7995:                 $first = $first_bubble_line{$responsenum} + 1;
 7996:             }
 7997:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7998:             my $subcount = 1;
 7999:             while ($subcount<$subquestion) {
 8000:                 $first += $subans[$subcount-1];
 8001:                 $subcount ++;
 8002:             }
 8003:             $count = $subans[$subquestion-1];
 8004:         } else {
 8005:             my $responsenum = $question-1;
 8006:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8007:                 $responsenum = $respnumlookup->{$question-1};
 8008:                 if (ref($startline) eq 'HASH') {
 8009:                     $first = $startline->{$question-1} + 1;
 8010:                 }
 8011:             } else {
 8012:                 $first = $first_bubble_line{$responsenum} + 1;
 8013:             }
 8014:             $count   = $bubble_lines_per_response{$responsenum};
 8015:         }
 8016:         $last = $first+$count-1;
 8017:         push(@lines, ($first..$last));
 8018:     }
 8019:     return join(',', @lines);
 8020: }
 8021: 
 8022: =pod 
 8023: 
 8024: =item prompt_for_corrections
 8025: 
 8026: Prompts for a potentially multiline correction to the
 8027: user's bubbling (factors out common code from scantron_get_correction
 8028: for multi and missing bubble cases).
 8029: 
 8030:  Arguments:
 8031:    $r           - Apache request object.
 8032:    $question    - The question number to prompt for.
 8033:    $scan_config - The scantron file configuration hash.
 8034:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8035:    $error       - Type of error
 8036:    $randomorder - True if randomorder in use.
 8037:    $randompick  - True if randompick in use.
 8038:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8039:                     for current line to question number used for same question
 8040:                     in "Master Seqence" (as seen by Course Coordinator).
 8041:    $startline   - Reference to hash where key is question number (0 is first)
 8042:                   and value is number of first bubble line for current student
 8043:                   or code-based randompick and/or randomorder.
 8044: 
 8045:  Implicit inputs:
 8046:    %bubble_lines_per_response   - Starting line numbers for each question.
 8047:                                   Numbered from 0 (but question numbers are from
 8048:                                   1.
 8049:    %first_bubble_line           - Starting bubble line for each question.
 8050:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8051:                                   type problems render as separate sub-questions, 
 8052:                                   in exam mode. This hash contains a 
 8053:                                   comma-separated list of the lines per 
 8054:                                   sub-question.
 8055:    %responsetype_per_response   - essayresponse, formularesponse,
 8056:                                   stringresponse, imageresponse, reactionresponse,
 8057:                                   and organicresponse type problem parts can have
 8058:                                   multiple lines per response if the weight
 8059:                                   assigned exceeds 10.  In this case, only
 8060:                                   one bubble per line is permitted, but more 
 8061:                                   than one line might contain bubbles, e.g.
 8062:                                   bubbling of: line 1 - J, line 2 - J, 
 8063:                                   line 3 - B would assign 22 points.  
 8064: 
 8065: =cut
 8066: 
 8067: sub prompt_for_corrections {
 8068:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8069:         $randompick, $respnumlookup, $startline) = @_;
 8070:     my ($current_line,$lines);
 8071:     my @linenums;
 8072:     my $questionnum = $question;
 8073:     my ($first,$responsenum);
 8074:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8075:         $question = $1;
 8076:         my $subquestion = $2;
 8077:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8078:             $responsenum = $respnumlookup->{$question-1};
 8079:             if (ref($startline) eq 'HASH') {
 8080:                 $first = $startline->{$question-1};
 8081:             }
 8082:         } else {
 8083:             $responsenum = $question-1;
 8084:             $first = $first_bubble_line{$responsenum};
 8085:         }
 8086:         $current_line = $first + 1 ;
 8087:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8088:         my $subcount = 1;
 8089:         while ($subcount<$subquestion) {
 8090:             $current_line += $subans[$subcount-1];
 8091:             $subcount ++;
 8092:         }
 8093:         $lines = $subans[$subquestion-1];
 8094:     } else {
 8095:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8096:             $responsenum = $respnumlookup->{$question-1};
 8097:             if (ref($startline) eq 'HASH') {
 8098:                 $first = $startline->{$question-1};
 8099:             }
 8100:         } else {
 8101:             $responsenum = $question-1;
 8102:             $first = $first_bubble_line{$responsenum};
 8103:         }
 8104:         $current_line = $first + 1;
 8105:         $lines        = $bubble_lines_per_response{$responsenum};
 8106:     }
 8107:     if ($lines > 1) {
 8108:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8109:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8110:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8111:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8112:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8113:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8114:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8115:             $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 />');
 8116:         } else {
 8117:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8118:         }
 8119:     }
 8120:     for (my $i =0; $i < $lines; $i++) {
 8121:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8122: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8123: 	        		  $questionnum,$error,split('', $selected));
 8124:         push(@linenums,$current_line);
 8125: 	$current_line++;
 8126:     }
 8127:     if ($lines > 1) {
 8128: 	$r->print("<hr /><br />");
 8129:     }
 8130:     return @linenums;
 8131: }
 8132: 
 8133: =pod
 8134: 
 8135: =item scantron_bubble_selector
 8136:   
 8137:    Generates the html radiobuttons to correct a single bubble line
 8138:    possibly showing the existing the selected bubbles if known
 8139: 
 8140:  Arguments:
 8141:     $r           - Apache request object
 8142:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8143:     $line        - Number of the line being displayed.
 8144:     $questionnum - Question number (may include subquestion)
 8145:     $error       - Type of error.
 8146:     @selected    - Array of bubbles picked on this line.
 8147: 
 8148: =cut
 8149: 
 8150: sub scantron_bubble_selector {
 8151:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8152:     my $max=$$scan_config{'Qlength'};
 8153: 
 8154:     my $scmode=$$scan_config{'Qon'};
 8155:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8156:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8157:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8158:             $max=$$scan_config{'BubblesPerRow'};
 8159:             if (($scmode eq 'number') && ($max > 10)) {
 8160:                 $max = 10;
 8161:             } elsif (($scmode eq 'letter') && $max > 26) {
 8162:                 $max = 26;
 8163:             }
 8164:         } else {
 8165:             $max = 10;
 8166:         }
 8167:     }
 8168: 
 8169:     my @alphabet=('A'..'Z');
 8170:     $r->print(&Apache::loncommon::start_data_table().
 8171:               &Apache::loncommon::start_data_table_row());
 8172:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8173:     for (my $i=0;$i<$max+1;$i++) {
 8174: 	$r->print("\n".'<td align="center">');
 8175: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8176: 	else { $r->print('&nbsp;'); }
 8177: 	$r->print('</td>');
 8178:     }
 8179:     $r->print(&Apache::loncommon::end_data_table_row().
 8180:               &Apache::loncommon::start_data_table_row());
 8181:     for (my $i=0;$i<$max;$i++) {
 8182: 	$r->print("\n".
 8183: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8184: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8185:     }
 8186:     my $nobub_checked = ' ';
 8187:     if ($error eq 'missingbubble') {
 8188:         $nobub_checked = ' checked = "checked" ';
 8189:     }
 8190:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8191: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8192:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8193:               $line.'" value="'.$questionnum.'" /></td>');
 8194:     $r->print(&Apache::loncommon::end_data_table_row().
 8195:               &Apache::loncommon::end_data_table());
 8196: }
 8197: 
 8198: =pod
 8199: 
 8200: =item num_matches
 8201: 
 8202:    Counts the number of characters that are the same between the two arguments.
 8203: 
 8204:  Arguments:
 8205:    $orig - CODE from the scanline
 8206:    $code - CODE to match against
 8207: 
 8208:  Returns:
 8209:    $count - integer count of the number of same characters between the
 8210:             two arguments
 8211: 
 8212: =cut
 8213: 
 8214: sub num_matches {
 8215:     my ($orig,$code) = @_;
 8216:     my @code=split(//,$code);
 8217:     my @orig=split(//,$orig);
 8218:     my $same=0;
 8219:     for (my $i=0;$i<scalar(@code);$i++) {
 8220: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8221:     }
 8222:     return $same;
 8223: }
 8224: 
 8225: =pod
 8226: 
 8227: =item scantron_get_closely_matching_CODEs
 8228: 
 8229:    Cycles through all CODEs and finds the set that has the greatest
 8230:    number of same characters as the provided CODE
 8231: 
 8232:  Arguments:
 8233:    $allcodes - hash ref returned by &get_codes()
 8234:    $CODE     - CODE from the current scanline
 8235: 
 8236:  Returns:
 8237:    2 element list
 8238:     - first elements is number of how closely matching the best fit is 
 8239:       (5 means best set has 5 matching characters)
 8240:     - second element is an arrary ref containing the set of valid CODEs
 8241:       that best fit the passed in CODE
 8242: 
 8243: =cut
 8244: 
 8245: sub scantron_get_closely_matching_CODEs {
 8246:     my ($allcodes,$CODE)=@_;
 8247:     my @CODEs;
 8248:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8249: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8250:     }
 8251: 
 8252:     return ($#CODEs,$CODEs[-1]);
 8253: }
 8254: 
 8255: =pod
 8256: 
 8257: =item get_codes
 8258: 
 8259:    Builds a hash which has keys of all of the valid CODEs from the selected
 8260:    set of remembered CODEs.
 8261: 
 8262:  Arguments:
 8263:   $old_name - name of the set of remembered CODEs
 8264:   $cdom     - domain of the course
 8265:   $cnum     - internal course name
 8266: 
 8267:  Returns:
 8268:   %allcodes - keys are the valid CODEs, values are all 1
 8269: 
 8270: =cut
 8271: 
 8272: sub get_codes {
 8273:     my ($old_name, $cdom, $cnum) = @_;
 8274:     if (!$old_name) {
 8275: 	$old_name=$env{'form.scantron_CODElist'};
 8276:     }
 8277:     if (!$cdom) {
 8278: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8279:     }
 8280:     if (!$cnum) {
 8281: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8282:     }
 8283:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8284: 				    $cdom,$cnum);
 8285:     my %allcodes;
 8286:     if ($result{"type\0$old_name"} eq 'number') {
 8287: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8288:     } else {
 8289: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8290:     }
 8291:     return %allcodes;
 8292: }
 8293: 
 8294: =pod
 8295: 
 8296: =item scantron_validate_CODE
 8297: 
 8298:    Validates all scanlines in the selected file to not have any
 8299:    invalid or underspecified CODEs and that none of the codes are
 8300:    duplicated if this was requested.
 8301: 
 8302: =cut
 8303: 
 8304: sub scantron_validate_CODE {
 8305:     my ($r,$currentphase) = @_;
 8306:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8307:     if ($scantron_config{'CODElocation'} &&
 8308: 	$scantron_config{'CODEstart'} &&
 8309: 	$scantron_config{'CODElength'}) {
 8310: 	if (!defined($env{'form.scantron_CODElist'})) {
 8311: 	    &FIXME_blow_up()
 8312: 	}
 8313:     } else {
 8314: 	return (0,$currentphase+1);
 8315:     }
 8316:     
 8317:     my %usedCODEs;
 8318: 
 8319:     my %allcodes=&get_codes();
 8320: 
 8321:     my $nav_error;
 8322:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8323:     if ($nav_error) {
 8324:         $r->print(&navmap_errormsg());
 8325:         return(1,$currentphase);
 8326:     }
 8327: 
 8328:     my ($scanlines,$scan_data)=&scantron_getfile();
 8329:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8330: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8331: 	if ($line=~/^[\s\cz]*$/) { next; }
 8332: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8333: 						 $scan_data);
 8334: 	my $CODE=$$scan_record{'scantron.CODE'};
 8335: 	my $error=0;
 8336: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8337: 	    &scantron_get_correction($r,$i,$scan_record,
 8338: 				     \%scantron_config,
 8339: 				     $line,'incorrectCODE',\%allcodes);
 8340: 	    return(1,$currentphase);
 8341: 	}
 8342: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8343: 	    && !$$scan_record{'scantron.useCODE'}) {
 8344: 	    &scantron_get_correction($r,$i,$scan_record,
 8345: 				     \%scantron_config,
 8346: 				     $line,'incorrectCODE',\%allcodes);
 8347: 	    return(1,$currentphase);
 8348: 	}
 8349: 	if (exists($usedCODEs{$CODE}) 
 8350: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8351: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8352: 	    &scantron_get_correction($r,$i,$scan_record,
 8353: 				     \%scantron_config,
 8354: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8355: 	    return(1,$currentphase);
 8356: 	}
 8357: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8358:     }
 8359:     return (0,$currentphase+1);
 8360: }
 8361: 
 8362: =pod
 8363: 
 8364: =item scantron_validate_doublebubble
 8365: 
 8366:    Validates all scanlines in the selected file to not have any
 8367:    bubble lines with multiple bubbles marked.
 8368: 
 8369: =cut
 8370: 
 8371: sub scantron_validate_doublebubble {
 8372:     my ($r,$currentphase) = @_;
 8373:     #get student info
 8374:     my $classlist=&Apache::loncoursedata::get_classlist();
 8375:     my %idmap=&username_to_idmap($classlist);
 8376:     my (undef,undef,$sequence)=
 8377:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8378: 
 8379:     #get scantron line setup
 8380:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8381:     my ($scanlines,$scan_data)=&scantron_getfile();
 8382: 
 8383:     my $navmap = Apache::lonnavmaps::navmap->new();
 8384:     unless (ref($navmap)) {
 8385:         $r->print(&navmap_errormsg());
 8386:         return(1,$currentphase);
 8387:     }
 8388:     my $map=$navmap->getResourceByUrl($sequence);
 8389:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8390:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8391:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8392:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8393: 
 8394:     my $nav_error;
 8395:     if (ref($map)) {
 8396:         $randomorder = $map->randomorder();
 8397:         $randompick = $map->randompick();
 8398:         if ($randomorder || $randompick) {
 8399:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8400:             if ($nav_error) {
 8401:                 $r->print(&navmap_errormsg());
 8402:                 return(1,$currentphase);
 8403:             }
 8404:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8405:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8406:         }
 8407:     } else {
 8408:         $r->print(&navmap_errormsg());
 8409:         return(1,$currentphase);
 8410:     }
 8411: 
 8412:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8413:     if ($nav_error) {
 8414:         $r->print(&navmap_errormsg());
 8415:         return(1,$currentphase);
 8416:     }
 8417: 
 8418:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8419: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8420: 	if ($line=~/^[\s\cz]*$/) { next; }
 8421: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8422: 						 $scan_data,undef,\%idmap,$randomorder,
 8423:                                                  $randompick,$sequence,\@master_seq,
 8424:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8425:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8426: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8427: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8428: 				 'doublebubble',
 8429: 				 $$scan_record{'scantron.doubleerror'},
 8430:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8431:     	return (1,$currentphase);
 8432:     }
 8433:     return (0,$currentphase+1);
 8434: }
 8435: 
 8436: 
 8437: sub scantron_get_maxbubble {
 8438:     my ($nav_error,$scantron_config) = @_;
 8439:     if (defined($env{'form.scantron_maxbubble'}) &&
 8440: 	$env{'form.scantron_maxbubble'}) {
 8441: 	&restore_bubble_lines();
 8442: 	return $env{'form.scantron_maxbubble'};
 8443:     }
 8444: 
 8445:     my (undef, undef, $sequence) =
 8446: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8447: 
 8448:     my $navmap=Apache::lonnavmaps::navmap->new();
 8449:     unless (ref($navmap)) {
 8450:         if (ref($nav_error)) {
 8451:             $$nav_error = 1;
 8452:         }
 8453:         return;
 8454:     }
 8455:     my $map=$navmap->getResourceByUrl($sequence);
 8456:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8457:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8458: 
 8459:     &Apache::lonxml::clear_problem_counter();
 8460: 
 8461:     my $uname       = $env{'user.name'};
 8462:     my $udom        = $env{'user.domain'};
 8463:     my $cid         = $env{'request.course.id'};
 8464:     my $total_lines = 0;
 8465:     %bubble_lines_per_response = ();
 8466:     %first_bubble_line         = ();
 8467:     %subdivided_bubble_lines   = ();
 8468:     %responsetype_per_response = ();
 8469:     %masterseq_id_responsenum  = ();
 8470: 
 8471:     my $response_number = 0;
 8472:     my $bubble_line     = 0;
 8473:     foreach my $resource (@resources) {
 8474:         my $resid = $resource->id();
 8475:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8476:                                                           $udom,undef,$bubbles_per_row);
 8477:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8478: 	    foreach my $part_id (@{$parts}) {
 8479:                 my $lines;
 8480: 
 8481: 	        # TODO - make this a persistent hash not an array.
 8482: 
 8483:                 # optionresponse, matchresponse and rankresponse type items 
 8484:                 # render as separate sub-questions in exam mode.
 8485:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8486:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8487:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8488:                     my ($numbub,$numshown);
 8489:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8490:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8491:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8492:                         }
 8493:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8494:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8495:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8496:                         }
 8497:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8498:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8499:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8500:                         }
 8501:                     }
 8502:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8503:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8504:                     }
 8505:                     my $bubbles_per_row =
 8506:                         &bubblesheet_bubbles_per_row($scantron_config);
 8507:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8508:                     if (($numbub % $bubbles_per_row) != 0) {
 8509:                         $inner_bubble_lines++;
 8510:                     }
 8511:                     for (my $i=0; $i<$numshown; $i++) {
 8512:                         $subdivided_bubble_lines{$response_number} .= 
 8513:                             $inner_bubble_lines.',';
 8514:                     }
 8515:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8516:                     $lines = $numshown * $inner_bubble_lines;
 8517:                 } else {
 8518:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8519:                 }
 8520: 
 8521:                 $first_bubble_line{$response_number} = $bubble_line;
 8522: 	        $bubble_lines_per_response{$response_number} = $lines;
 8523:                 $responsetype_per_response{$response_number} = 
 8524:                     $analysis->{$part_id.'.type'};
 8525:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8526: 	        $response_number++;
 8527: 
 8528: 	        $bubble_line +=  $lines;
 8529: 	        $total_lines +=  $lines;
 8530: 	    }
 8531:         }
 8532:     }
 8533:     &Apache::lonnet::delenv('scantron.');
 8534: 
 8535:     &save_bubble_lines();
 8536:     $env{'form.scantron_maxbubble'} =
 8537: 	$total_lines;
 8538:     return $env{'form.scantron_maxbubble'};
 8539: }
 8540: 
 8541: sub bubblesheet_bubbles_per_row {
 8542:     my ($scantron_config) = @_;
 8543:     my $bubbles_per_row;
 8544:     if (ref($scantron_config) eq 'HASH') {
 8545:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8546:     }
 8547:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8548:         $bubbles_per_row = 10;
 8549:     }
 8550:     return $bubbles_per_row;
 8551: }
 8552: 
 8553: sub scantron_validate_missingbubbles {
 8554:     my ($r,$currentphase) = @_;
 8555:     #get student info
 8556:     my $classlist=&Apache::loncoursedata::get_classlist();
 8557:     my %idmap=&username_to_idmap($classlist);
 8558:     my (undef,undef,$sequence)=
 8559:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8560: 
 8561:     #get scantron line setup
 8562:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8563:     my ($scanlines,$scan_data)=&scantron_getfile();
 8564: 
 8565:     my $navmap = Apache::lonnavmaps::navmap->new();
 8566:     unless (ref($navmap)) {
 8567:         $r->print(&navmap_errormsg());
 8568:         return(1,$currentphase);
 8569:     }
 8570: 
 8571:     my $map=$navmap->getResourceByUrl($sequence);
 8572:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8573:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8574:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8575:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8576: 
 8577:     my $nav_error;
 8578:     if (ref($map)) {
 8579:         $randomorder = $map->randomorder();
 8580:         $randompick = $map->randompick();
 8581:         if ($randomorder || $randompick) {
 8582:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8583:             if ($nav_error) {
 8584:                 $r->print(&navmap_errormsg());
 8585:                 return(1,$currentphase);
 8586:             }
 8587:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8588:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8589:         }
 8590:     } else {
 8591:         $r->print(&navmap_errormsg());
 8592:         return(1,$currentphase);
 8593:     }
 8594: 
 8595: 
 8596:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8597:     if ($nav_error) {
 8598:         $r->print(&navmap_errormsg());
 8599:         return(1,$currentphase);
 8600:     }
 8601: 
 8602:     if (!$max_bubble) { $max_bubble=2**31; }
 8603:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8604: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8605: 	if ($line=~/^[\s\cz]*$/) { next; }
 8606:         my $scan_record =
 8607:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8608:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8609:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8610:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8611: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8612: 	my @to_correct;
 8613: 	
 8614: 	# Probably here's where the error is...
 8615: 
 8616: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8617:             my $lastbubble;
 8618:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8619:                 my $question = $1;
 8620:                 my $subquestion = $2;
 8621:                 my ($first,$responsenum);
 8622:                 if ($randomorder || $randompick) {
 8623:                     $responsenum = $respnumlookup{$question-1};
 8624:                     $first = $startline{$question-1};
 8625:                 } else {
 8626:                     $responsenum = $question-1;
 8627:                     $first = $first_bubble_line{$responsenum};
 8628:                 }
 8629:                 if (!defined($first)) { next; }
 8630:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8631:                 my $subcount = 1;
 8632:                 while ($subcount<$subquestion) {
 8633:                     $first += $subans[$subcount-1];
 8634:                     $subcount ++;
 8635:                 }
 8636:                 my $count = $subans[$subquestion-1];
 8637:                 $lastbubble = $first + $count;
 8638:             } else {
 8639:                 my ($first,$responsenum);
 8640:                 if ($randomorder || $randompick) {
 8641:                     $responsenum = $respnumlookup{$missing-1};
 8642:                     $first = $startline{$missing-1};
 8643:                 } else {
 8644:                     $responsenum = $missing-1;
 8645:                     $first = $first_bubble_line{$responsenum};
 8646:                 }
 8647:                 if (!defined($first)) { next; }
 8648:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8649:             }
 8650:             if ($lastbubble > $max_bubble) { next; }
 8651: 	    push(@to_correct,$missing);
 8652: 	}
 8653: 	if (@to_correct) {
 8654: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8655: 				     $line,'missingbubble',\@to_correct,
 8656:                                      $randomorder,$randompick,\%respnumlookup,
 8657:                                      \%startline);
 8658: 	    return (1,$currentphase);
 8659: 	}
 8660: 
 8661:     }
 8662:     return (0,$currentphase+1);
 8663: }
 8664: 
 8665: sub hand_bubble_option {
 8666:     my (undef, undef, $sequence) =
 8667:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8668:     return if ($sequence eq '');
 8669:     my $navmap = Apache::lonnavmaps::navmap->new();
 8670:     unless (ref($navmap)) {
 8671:         return;
 8672:     }
 8673:     my $needs_hand_bubbles;
 8674:     my $map=$navmap->getResourceByUrl($sequence);
 8675:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8676:     foreach my $res (@resources) {
 8677:         if (ref($res)) {
 8678:             if ($res->is_problem()) {
 8679:                 my $partlist = $res->parts();
 8680:                 foreach my $part (@{ $partlist }) {
 8681:                     my @types = $res->responseType($part);
 8682:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8683:                         $needs_hand_bubbles = 1;
 8684:                         last;
 8685:                     }
 8686:                 }
 8687:             }
 8688:         }
 8689:     }
 8690:     if ($needs_hand_bubbles) {
 8691:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8692:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8693:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8694:                &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 />').
 8695:                '<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;'.
 8696:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8697:     }
 8698:     return;
 8699: }
 8700: 
 8701: sub scantron_process_students {
 8702:     my ($r,$symb) = @_;
 8703: 
 8704:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8705:     if (!$symb) {
 8706: 	return '';
 8707:     }
 8708:     my $default_form_data=&defaultFormData($symb);
 8709: 
 8710:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8711:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8712:     my ($scanlines,$scan_data)=&scantron_getfile();
 8713:     my $classlist=&Apache::loncoursedata::get_classlist();
 8714:     my %idmap=&username_to_idmap($classlist);
 8715:     my $navmap=Apache::lonnavmaps::navmap->new();
 8716:     unless (ref($navmap)) {
 8717:         $r->print(&navmap_errormsg());
 8718:         return '';
 8719:     }
 8720:     my $map=$navmap->getResourceByUrl($sequence);
 8721:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8722:         %grader_randomlists_by_symb);
 8723:     if (ref($map)) {
 8724:         $randomorder = $map->randomorder();
 8725:         $randompick = $map->randompick();
 8726:     } else {
 8727:         $r->print(&navmap_errormsg());
 8728:         return '';
 8729:     }
 8730:     my $nav_error;
 8731:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8732:     if ($randomorder || $randompick) {
 8733:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8734:         if ($nav_error) {
 8735:             $r->print(&navmap_errormsg());
 8736:             return '';
 8737:         }
 8738:     }
 8739:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8740:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8741: 
 8742:     my ($uname,$udom);
 8743:     my $result= <<SCANTRONFORM;
 8744: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8745:   <input type="hidden" name="command" value="scantron_configphase" />
 8746:   $default_form_data
 8747: SCANTRONFORM
 8748:     $r->print($result);
 8749: 
 8750:     my @delayqueue;
 8751:     my (%completedstudents,%scandata);
 8752:     
 8753:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8754:     my $count=&get_todo_count($scanlines,$scan_data);
 8755:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8756:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8757:     $r->print('<br />');
 8758:     my $start=&Time::HiRes::time();
 8759:     my $i=-1;
 8760:     my $started;
 8761: 
 8762:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8763:     if ($nav_error) {
 8764:         $r->print(&navmap_errormsg());
 8765:         return '';
 8766:     }
 8767: 
 8768:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8769:     # the user and return.
 8770: 
 8771:     if ($ssi_error) {
 8772: 	$r->print("</form>");
 8773: 	&ssi_print_error($r);
 8774:         &Apache::lonnet::remove_lock($lock);
 8775: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8776:     }
 8777: 
 8778:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8779:     my $numletts = scalar(keys(%lettdig));
 8780:     my %orderedforcode;
 8781: 
 8782:     while ($i<$scanlines->{'count'}) {
 8783:  	($uname,$udom)=('','');
 8784:  	$i++;
 8785:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8786:  	if ($line=~/^[\s\cz]*$/) { next; }
 8787: 	if ($started) {
 8788: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8789: 	}
 8790: 	$started=1;
 8791:         my %respnumlookup = ();
 8792:         my %startline = ();
 8793:         my $total;
 8794:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8795:  						 $scan_data,undef,\%idmap,$randomorder,
 8796:                                                  $randompick,$sequence,\@master_seq,
 8797:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8798:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8799:                                                  \$total);
 8800:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8801:  					      \%idmap,$i)) {
 8802:   	    &scantron_add_delay(\@delayqueue,$line,
 8803:  				'Unable to find a student that matches',1);
 8804:  	    next;
 8805:   	}
 8806:  	if (exists $completedstudents{$uname}) {
 8807:  	    &scantron_add_delay(\@delayqueue,$line,
 8808:  				'Student '.$uname.' has multiple sheets',2);
 8809:  	    next;
 8810:  	}
 8811:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8812:         my $user = $uname.':'.$usec;
 8813:   	($uname,$udom)=split(/:/,$uname);
 8814: 
 8815:         my $scancode;
 8816:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8817:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8818:             $scancode = $scan_record->{'scantron.CODE'};
 8819:         } else {
 8820:             $scancode = '';
 8821:         }
 8822: 
 8823:         my @mapresources = @resources;
 8824:         if ($randomorder || $randompick) {
 8825:             @mapresources =
 8826:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8827:                              \%orderedforcode);
 8828:         }
 8829:         my (%partids_by_symb,$res_error);
 8830:         foreach my $resource (@mapresources) {
 8831:             my $ressymb;
 8832:             if (ref($resource)) {
 8833:                 $ressymb = $resource->symb();
 8834:             } else {
 8835:                 $res_error = 1;
 8836:                 last;
 8837:             }
 8838:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8839:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8840:                 my $currcode;
 8841:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8842:                     $currcode = $scancode;
 8843:                 }
 8844:                 my ($analysis,$parts) =
 8845:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8846:                                               $uname,$udom,undef,$bubbles_per_row,
 8847:                                               $currcode);
 8848:                 $partids_by_symb{$ressymb} = $parts;
 8849:             } else {
 8850:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8851:             }
 8852:         }
 8853: 
 8854:         if ($res_error) {
 8855:             &scantron_add_delay(\@delayqueue,$line,
 8856:                                 'An error occurred while grading student '.$uname,2);
 8857:             next;
 8858:         }
 8859: 
 8860: 	&Apache::lonxml::clear_problem_counter();
 8861:   	&Apache::lonnet::appenv($scan_record);
 8862: 
 8863: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8864: 	    &scantron_putfile($scanlines,$scan_data);
 8865: 	}
 8866: 	
 8867:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8868:                                    \@mapresources,\%partids_by_symb,
 8869:                                    $bubbles_per_row,$randomorder,$randompick,
 8870:                                    \%respnumlookup,\%startline) 
 8871:             eq 'ssi_error') {
 8872:             $ssi_error = 0; # So end of handler error message does not trigger.
 8873:             $r->print("</form>");
 8874:             &ssi_print_error($r);
 8875:             &Apache::lonnet::remove_lock($lock);
 8876:             return '';      # Why return ''?  Beats me.
 8877:         }
 8878: 
 8879:         if (($scancode) && ($randomorder || $randompick)) {
 8880:             my $parmresult =
 8881:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8882:                                                        '0_examcode',2,$scancode,
 8883:                                                        'string_examcode',$uname,
 8884:                                                        $udom);
 8885:         }
 8886: 	$completedstudents{$uname}={'line'=>$line};
 8887:         if ($env{'form.verifyrecord'}) {
 8888:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8889:             if ($randompick) {
 8890:                 if ($total) {
 8891:                     $lastpos = $total*$scantron_config{'Qlength'};
 8892:                 }
 8893:             }
 8894: 
 8895:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8896:             chomp($studentdata);
 8897:             $studentdata =~ s/\r$//;
 8898:             my $studentrecord = '';
 8899:             my $counter = -1;
 8900:             foreach my $resource (@mapresources) {
 8901:                 my $ressymb = $resource->symb();
 8902:                 ($counter,my $recording) =
 8903:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8904:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8905:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8906:                                              $randompick,\%respnumlookup,\%startline);
 8907:                 $studentrecord .= $recording;
 8908:             }
 8909:             if ($studentrecord ne $studentdata) {
 8910:                 &Apache::lonxml::clear_problem_counter();
 8911:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8912:                                            \@mapresources,\%partids_by_symb,
 8913:                                            $bubbles_per_row,$randomorder,$randompick,
 8914:                                            \%respnumlookup,\%startline)
 8915:                     eq 'ssi_error') {
 8916:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8917:                     $r->print("</form>");
 8918:                     &ssi_print_error($r);
 8919:                     &Apache::lonnet::remove_lock($lock);
 8920:                     delete($completedstudents{$uname});
 8921:                     return '';
 8922:                 }
 8923:                 $counter = -1;
 8924:                 $studentrecord = '';
 8925:                 foreach my $resource (@mapresources) {
 8926:                     my $ressymb = $resource->symb();
 8927:                     ($counter,my $recording) =
 8928:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8929:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8930:                                                  \%scantron_config,\%lettdig,$numletts,
 8931:                                                  $randomorder,$randompick,\%respnumlookup,
 8932:                                                  \%startline);
 8933:                     $studentrecord .= $recording;
 8934:                 }
 8935:                 if ($studentrecord ne $studentdata) {
 8936:                     $r->print('<p><span class="LC_warning">');
 8937:                     if ($scancode eq '') {
 8938:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8939:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8940:                     } else {
 8941:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8942:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8943:                     }
 8944:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8945:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8946:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8947:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8948:                               &Apache::loncommon::start_data_table_row().
 8949:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8950:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8951:                               &Apache::loncommon::end_data_table_row().
 8952:                               &Apache::loncommon::start_data_table_row().
 8953:                               '<td>'.&mt('Stored submissions').'</td>'.
 8954:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8955:                               &Apache::loncommon::end_data_table_row().
 8956:                               &Apache::loncommon::end_data_table().'</p>');
 8957:                 } else {
 8958:                     $r->print('<br /><span class="LC_warning">'.
 8959:                              &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 />'.
 8960:                              &mt("As a consequence, this user's submission history records two tries.").
 8961:                                  '</span><br />');
 8962:                 }
 8963:             }
 8964:         }
 8965:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8966:     } continue {
 8967: 	&Apache::lonxml::clear_problem_counter();
 8968: 	&Apache::lonnet::delenv('scantron.');
 8969:     }
 8970:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8971:     &Apache::lonnet::remove_lock($lock);
 8972: #    my $lasttime = &Time::HiRes::time()-$start;
 8973: #    $r->print("<p>took $lasttime</p>");
 8974: 
 8975:     $r->print("</form>");
 8976:     return '';
 8977: }
 8978: 
 8979: sub graders_resources_pass {
 8980:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8981:         $bubbles_per_row) = @_;
 8982:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8983:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8984:         foreach my $resource (@{$resources}) {
 8985:             my $ressymb = $resource->symb();
 8986:             my ($analysis,$parts) =
 8987:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8988:                                           $env{'user.name'},$env{'user.domain'},
 8989:                                           1,$bubbles_per_row);
 8990:             $grader_partids_by_symb->{$ressymb} = $parts;
 8991:             if (ref($analysis) eq 'HASH') {
 8992:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8993:                     $grader_randomlists_by_symb->{$ressymb} =
 8994:                         $analysis->{'parts_withrandomlist'};
 8995:                 }
 8996:             }
 8997:         }
 8998:     }
 8999:     return;
 9000: }
 9001: 
 9002: =pod
 9003: 
 9004: =item users_order
 9005: 
 9006:   Returns array of resources in current map, ordered based on either CODE,
 9007:   if this is a CODEd exam, or based on student's identity if this is a
 9008:   "NAMEd" exam.
 9009: 
 9010:   Should be used when randomorder and/or randompick applied when the 
 9011:   corresponding exam was printed, prior to students completing bubblesheets 
 9012:   for the version of the exam the student received.
 9013: 
 9014: =cut
 9015: 
 9016: sub users_order  {
 9017:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9018:     my @mapresources;
 9019:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9020:         return @mapresources;
 9021:     }
 9022:     if ($scancode) {
 9023:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9024:             @mapresources = @{$orderedforcode->{$scancode}};
 9025:         } else {
 9026:             $env{'form.CODE'} = $scancode;
 9027:             my $actual_seq =
 9028:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9029:                                                                $master_seq,
 9030:                                                                $user,$scancode,1);
 9031:             if (ref($actual_seq) eq 'ARRAY') {
 9032:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9033:                 if (ref($orderedforcode) eq 'HASH') {
 9034:                     if (@mapresources > 0) {
 9035:                         $orderedforcode->{$scancode} = \@mapresources;
 9036:                     }
 9037:                 }
 9038:             }
 9039:             delete($env{'form.CODE'});
 9040:         }
 9041:     } else {
 9042:         my $actual_seq =
 9043:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9044:                                                            $master_seq,
 9045:                                                            $user,undef,1);
 9046:         if (ref($actual_seq) eq 'ARRAY') {
 9047:             @mapresources =
 9048:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9049:         }
 9050:     }
 9051:     return @mapresources;
 9052: }
 9053: 
 9054: sub grade_student_bubbles {
 9055:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9056:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9057:     my $uselookup = 0;
 9058:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9059:         (ref($startline) eq 'HASH')) {
 9060:         $uselookup = 1;
 9061:     }
 9062: 
 9063:     if (ref($resources) eq 'ARRAY') {
 9064:         my $count = 0;
 9065:         foreach my $resource (@{$resources}) {
 9066:             my $ressymb = $resource->symb();
 9067:             my %form = ('submitted'      => 'scantron',
 9068:                         'grade_target'   => 'grade',
 9069:                         'grade_username' => $uname,
 9070:                         'grade_domain'   => $udom,
 9071:                         'grade_courseid' => $env{'request.course.id'},
 9072:                         'grade_symb'     => $ressymb,
 9073:                         'CODE'           => $scancode
 9074:                        );
 9075:             if ($bubbles_per_row ne '') {
 9076:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9077:             }
 9078:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9079:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9080:             }
 9081:             if (ref($parts) eq 'HASH') {
 9082:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9083:                     foreach my $part (@{$parts->{$ressymb}}) {
 9084:                         if ($uselookup) {
 9085:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9086:                         } else {
 9087:                             $form{'scantron_questnum_start.'.$part} =
 9088:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9089:                         }
 9090:                         $count++;
 9091:                     }
 9092:                 }
 9093:             }
 9094:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9095:             return 'ssi_error' if ($ssi_error);
 9096:             last if (&Apache::loncommon::connection_aborted($r));
 9097:         }
 9098:     }
 9099:     return;
 9100: }
 9101: 
 9102: sub scantron_upload_scantron_data {
 9103:     my ($r,$symb) = @_;
 9104:     my $dom = $env{'request.role.domain'};
 9105:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9106:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9107:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9108:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9109: 							  'domainid',
 9110: 							  'coursename',$dom);
 9111:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9112:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9113:     my $default_form_data=&defaultFormData($symb);
 9114:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9115:     &js_escape(\$nofile_alert);
 9116:     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.");
 9117:     &js_escape(\$nocourseid_alert);
 9118:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9119:     function checkUpload(formname) {
 9120: 	if (formname.upfile.value == "") {
 9121: 	    alert("'.$nofile_alert.'");
 9122: 	    return false;
 9123: 	}
 9124:         if (formname.courseid.value == "") {
 9125:             alert("'.$nocourseid_alert.'");
 9126:             return false;
 9127:         }
 9128: 	formname.submit();
 9129:     }
 9130: 
 9131:     function ToSyllabus() {
 9132:         var cdom = '."'$dom'".';
 9133:         var cnum = document.rules.courseid.value;
 9134:         if (cdom == "" || cdom == null) {
 9135:             return;
 9136:         }
 9137:         if (cnum == "" || cnum == null) {
 9138:            return;
 9139:         }
 9140:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9141:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9142:         return;
 9143:     }
 9144: 
 9145:     '.$formatjs.'
 9146: '));
 9147:     $r->print('
 9148: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9149: 
 9150: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9151: '.$default_form_data.
 9152:   &Apache::lonhtmlcommon::start_pick_box().
 9153:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9154:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9155:   &Apache::lonhtmlcommon::row_closure().
 9156:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9157:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9158:   &Apache::lonhtmlcommon::row_closure().
 9159:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9160:   '<input name="domainid" type="hidden" />'.$domdesc.
 9161:   &Apache::lonhtmlcommon::row_closure());
 9162:     if ($formatoptions) {
 9163:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9164:                   &Apache::lonhtmlcommon::row_closure());
 9165:     }
 9166:     $r->print(
 9167:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9168:   '<input type="file" name="upfile" size="50" />'.
 9169:   &Apache::lonhtmlcommon::row_closure(1).
 9170:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9171: 
 9172: <input name="command" value="scantronupload_save" type="hidden" />
 9173: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9174: </form>
 9175: ');
 9176:     return '';
 9177: }
 9178: 
 9179: sub scantron_upload_dataformat {
 9180:     my ($dom) = @_;
 9181:     my ($formatoptions,$formattitle,$formatjs);
 9182:     $formatjs = <<'END';
 9183: function toggleScantab(form) {
 9184:    return;
 9185: }
 9186: END
 9187:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9188:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9189:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9190:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9191:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9192:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9193:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9194:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9195:                             my ($onclick,$formatextra,$singleline);
 9196:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9197:                             my $count = 0;
 9198:                             foreach my $line (@lines) {
 9199:                                 next if ($line =~ /^#/);
 9200:                                 $singleline = $line;
 9201:                                 $count ++;
 9202:                             }
 9203:                             if ($count > 1) {
 9204:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9205:                                                '<span class="LC_nobreak">'.
 9206:                                                &mt('Bubblesheet type').':&nbsp;'.
 9207:                                                &scantron_scantab().'</span></div>';
 9208:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9209:                                 $formatjs = <<"END";
 9210: function toggleScantab(form) {
 9211:     var divid = 'bubbletype';
 9212:     if (document.getElementById(divid)) {
 9213:         var radioname = 'fileformat';
 9214:         var num = form.elements[radioname].length;
 9215:         if (num) {
 9216:             for (var i=0; i<num; i++) {
 9217:                 if (form.elements[radioname][i].checked) {
 9218:                     var chosen = form.elements[radioname][i].value;
 9219:                     if (chosen == 'dat') {
 9220:                         document.getElementById(divid).style.display = 'none';
 9221:                     } else if (chosen == 'csv') {
 9222:                         document.getElementById(divid).style.display = 'block';
 9223:                     }
 9224:                 }
 9225:             }
 9226:         }
 9227:     }
 9228:     return;
 9229: }
 9230: 
 9231: END
 9232:                             } elsif ($count == 1) {
 9233:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9234:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9235:                             }
 9236:                             $formattitle = &mt('File format');
 9237:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9238:                                              &mt('Plain Text (no delimiters)').
 9239:                                              '</label>'.('&nbsp;'x2).
 9240:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9241:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9242:                         }
 9243:                     }
 9244:                 }
 9245:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9246:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9247:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9248:                         $formattitle = &mt('Bubblesheet type');
 9249:                         $formatoptions = &scantron_scantab();
 9250:                     }
 9251:                 }
 9252:             }
 9253:         }
 9254:     }
 9255:     return ($formatoptions,$formattitle,$formatjs);
 9256: }
 9257: 
 9258: sub scantron_upload_scantron_data_save {
 9259:     my ($r,$symb) = @_;
 9260:     my $doanotherupload=
 9261: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9262: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9263: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9264: 	'</form>'."\n";
 9265:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9266: 	!&Apache::lonnet::allowed('usc',
 9267: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9268: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9269:         unless ($symb) {
 9270: 	    $r->print($doanotherupload);
 9271: 	}
 9272: 	return '';
 9273:     }
 9274:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9275:     my $uploadedfile;
 9276:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9277:     if (length($env{'form.upfile'}) < 2) {
 9278:         $r->print(
 9279:             &Apache::lonhtmlcommon::confirm_success(
 9280:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9281:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9282:     } else {
 9283:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9284:         my $parser;
 9285:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9286:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9287:                 my $is_csv;
 9288:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9289:                 if (@possibles > 1) {
 9290:                     if ($env{'form.fileformat'} eq 'csv') {
 9291:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9292:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9293:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9294:                                     $is_csv = 1;
 9295:                                 }
 9296:                             }
 9297:                         }
 9298:                     }
 9299:                 } elsif (@possibles == 1) {
 9300:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9301:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9302:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9303:                                 $is_csv = 1;
 9304:                             }
 9305:                         }
 9306:                     }
 9307:                 }
 9308:                 if ($is_csv) {
 9309:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9310:                 }
 9311:             }
 9312:         }
 9313:         my $result =
 9314:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9315:                                             $env{'form.courseid'},$env{'form.domainid'});
 9316: 	if ($result =~ m{^/uploaded/}) {
 9317:             $r->print(
 9318:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9319:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9320:                         (length($env{'form.upfile'})-1),
 9321:                         '<span class="LC_filename">'.$result.'</span>'));
 9322:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9323:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9324:                                                        $env{'form.courseid'},$uploadedfile));
 9325: 	} else {
 9326:             $r->print(
 9327:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9328:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9329:                           $result,
 9330: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9331: 	}
 9332:     }
 9333:     if ($symb) {
 9334: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9335:     } else {
 9336: 	$r->print($doanotherupload);
 9337:     }
 9338:     return '';
 9339: }
 9340: 
 9341: sub validate_uploaded_scantron_file {
 9342:     my ($cdom,$cname,$fname) = @_;
 9343:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9344:     my @lines;
 9345:     if ($scanlines ne '-1') {
 9346:         @lines=split("\n",$scanlines,-1);
 9347:     }
 9348:     my $output;
 9349:     if (@lines) {
 9350:         my (%counts,$max_match_format);
 9351:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9352:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9353:         my %idmap = &username_to_idmap($classlist);
 9354:         foreach my $key (keys(%idmap)) {
 9355:             my $lckey = lc($key);
 9356:             $idmap{$lckey} = $idmap{$key};
 9357:         }
 9358:         my %unique_formats;
 9359:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9360:         foreach my $line (@formatlines) {
 9361:             chomp($line);
 9362:             my @config = split(/:/,$line);
 9363:             my $idstart = $config[5];
 9364:             my $idlength = $config[6];
 9365:             if (($idstart ne '') && ($idlength > 0)) {
 9366:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9367:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9368:                 } else {
 9369:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9370:                 }
 9371:             }
 9372:         }
 9373:         foreach my $key (keys(%unique_formats)) {
 9374:             my ($idstart,$idlength) = split(':',$key);
 9375:             %{$counts{$key}} = (
 9376:                                'found'   => 0,
 9377:                                'total'   => 0,
 9378:                               );
 9379:             foreach my $line (@lines) {
 9380:                 next if ($line =~ /^#/);
 9381:                 next if ($line =~ /^[\s\cz]*$/);
 9382:                 my $id = substr($line,$idstart-1,$idlength);
 9383:                 $id = lc($id);
 9384:                 if (exists($idmap{$id})) {
 9385:                     $counts{$key}{'found'} ++;
 9386:                 }
 9387:                 $counts{$key}{'total'} ++;
 9388:             }
 9389:             if ($counts{$key}{'total'}) {
 9390:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9391:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9392:                     $max_match_pct = $percent_match;
 9393:                     $max_match_format = $key;
 9394:                     $found_match_count = $counts{$key}{'found'};
 9395:                     $max_match_count = $counts{$key}{'total'};
 9396:                 }
 9397:             }
 9398:         }
 9399:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9400:             my $format_descs;
 9401:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9402:             for (my $i=0; $i<$numwithformat; $i++) {
 9403:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9404:                 if ($i<$numwithformat-2) {
 9405:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9406:                 } elsif ($i==$numwithformat-2) {
 9407:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9408:                 } elsif ($i==$numwithformat-1) {
 9409:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9410:                 }
 9411:             }
 9412:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9413:             $output .= '<br />';
 9414:             if ($found_match_count == $max_match_count) {
 9415:                 # 100% matching entries
 9416:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9417:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9418:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9419:                 &mt('Comparison of student IDs in the uploaded file with'.
 9420:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9421:                     ' in the file (for the format defined for [_3]).',
 9422:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9423:             } else {
 9424:                 # Not all entries matching? -> Show warning and additional info
 9425:                 $output .=
 9426:                     &Apache::lonhtmlcommon::confirm_success(
 9427:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9428:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9429:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9430:                     &mt('Comparison of student IDs in the uploaded file with'.
 9431:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9432:                         ' in the file (for the format defined for [_3]).',
 9433:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9434:                     '<p class="LC_info">'.
 9435:                     &mt('A low percentage of matches results from one of the following:').
 9436:                     '</p><ul>'.
 9437:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9438:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9439:                                '<i>'.$cdom.'</i>').'</li>'.
 9440:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9441:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9442:                     '</ul>';
 9443:             }
 9444:         }
 9445:     } else {
 9446:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9447:     }
 9448:     return $output;
 9449: }
 9450: 
 9451: sub valid_file {
 9452:     my ($requested_file)=@_;
 9453:     foreach my $filename (sort(&scantron_filenames())) {
 9454: 	if ($requested_file eq $filename) { return 1; }
 9455:     }
 9456:     return 0;
 9457: }
 9458: 
 9459: sub scantron_download_scantron_data {
 9460:     my ($r,$symb) = @_;
 9461:     my $default_form_data=&defaultFormData($symb);
 9462:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9463:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9464:     my $file=$env{'form.scantron_selectfile'};
 9465:     if (! &valid_file($file)) {
 9466: 	$r->print('
 9467: 	<p>
 9468: 	    '.&mt('The requested filename was invalid.').'
 9469:         </p>
 9470: ');
 9471: 	return;
 9472:     }
 9473:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9474:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9475:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9476:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9477:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9478:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9479:     $r->print('
 9480:     <p>
 9481: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9482: 	      '<a href="'.$orig.'">','</a>').'
 9483:     </p>
 9484:     <p>
 9485: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9486: 	      '<a href="'.$corrected.'">','</a>').'
 9487:     </p>
 9488:     <p>
 9489: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9490: 	      '<a href="'.$skipped.'">','</a>').'
 9491:     </p>
 9492: ');
 9493:     return '';
 9494: }
 9495: 
 9496: sub checkscantron_results {
 9497:     my ($r,$symb) = @_;
 9498:     if (!$symb) {return '';}
 9499:     my $cid = $env{'request.course.id'};
 9500:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9501:     my $numletts = scalar(keys(%lettdig));
 9502:     my $cnum = $env{'course.'.$cid.'.num'};
 9503:     my $cdom = $env{'course.'.$cid.'.domain'};
 9504:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9505:     my %record;
 9506:     my %scantron_config =
 9507:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9508:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9509:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9510:     my $classlist=&Apache::loncoursedata::get_classlist();
 9511:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9512:     my $navmap=Apache::lonnavmaps::navmap->new();
 9513:     unless (ref($navmap)) {
 9514:         $r->print(&navmap_errormsg());
 9515:         return '';
 9516:     }
 9517:     my $map=$navmap->getResourceByUrl($sequence);
 9518:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9519:         %grader_randomlists_by_symb,%orderedforcode);
 9520:     if (ref($map)) {
 9521:         $randomorder=$map->randomorder();
 9522:         $randompick=$map->randompick();
 9523:     }
 9524:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9525:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9526:     if ($nav_error) {
 9527:         $r->print(&navmap_errormsg());
 9528:         return '';
 9529:     }
 9530:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9531:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9532:     my ($uname,$udom);
 9533:     my (%scandata,%lastname,%bylast);
 9534:     $r->print('
 9535: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9536: 
 9537:     my @delayqueue;
 9538:     my %completedstudents;
 9539: 
 9540:     my $count=&get_todo_count($scanlines,$scan_data);
 9541:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9542:     my ($username,$domain,$started);
 9543:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9544:     if ($nav_error) {
 9545:         $r->print(&navmap_errormsg());
 9546:         return '';
 9547:     }
 9548: 
 9549:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9550:                                           'Processing first student');
 9551:     my $start=&Time::HiRes::time();
 9552:     my $i=-1;
 9553: 
 9554:     while ($i<$scanlines->{'count'}) {
 9555:         ($username,$domain,$uname)=('','','');
 9556:         $i++;
 9557:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9558:         if ($line=~/^[\s\cz]*$/) { next; }
 9559:         if ($started) {
 9560:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9561:                                                      'last student');
 9562:         }
 9563:         $started=1;
 9564:         my $scan_record=
 9565:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9566:                                                      $scan_data);
 9567:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9568:                                               \%idmap,$i)) {
 9569:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9570:                                 'Unable to find a student that matches',1);
 9571:             next;
 9572:         }
 9573:         if (exists $completedstudents{$uname}) {
 9574:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9575:                                 'Student '.$uname.' has multiple sheets',2);
 9576:             next;
 9577:         }
 9578:         my $pid = $scan_record->{'scantron.ID'};
 9579:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9580:         push(@{$bylast{$lastname{$pid}}},$pid);
 9581:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9582:         my $user = $uname.':'.$usec;
 9583:         ($username,$domain)=split(/:/,$uname);
 9584: 
 9585:         my $scancode;
 9586:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9587:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9588:             $scancode = $scan_record->{'scantron.CODE'};
 9589:         } else {
 9590:             $scancode = '';
 9591:         }
 9592: 
 9593:         my @mapresources = @resources;
 9594:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9595:         my %respnumlookup=();
 9596:         my %startline=();
 9597:         if ($randomorder || $randompick) {
 9598:             @mapresources =
 9599:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9600:                              \%orderedforcode);
 9601:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9602:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9603:                                              \%grader_partids_by_symb,\%orderedforcode,
 9604:                                              \%respnumlookup,\%startline);
 9605:             if ($randompick && $total) {
 9606:                 $lastpos = $total*$scantron_config{'Qlength'};
 9607:             }
 9608:         }
 9609:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9610:         chomp($scandata{$pid});
 9611:         $scandata{$pid} =~ s/\r$//;
 9612: 
 9613:         my $counter = -1;
 9614:         foreach my $resource (@mapresources) {
 9615:             my $parts;
 9616:             my $ressymb = $resource->symb();
 9617:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9618:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9619:                 my $currcode;
 9620:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9621:                     $currcode = $scancode;
 9622:                 }
 9623:                 (my $analysis,$parts) =
 9624:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9625:                                               $username,$domain,undef,
 9626:                                               $bubbles_per_row,$currcode);
 9627:             } else {
 9628:                 $parts = $grader_partids_by_symb{$ressymb};
 9629:             }
 9630:             ($counter,my $recording) =
 9631:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9632:                                          $scandata{$pid},$parts,
 9633:                                          \%scantron_config,\%lettdig,$numletts,
 9634:                                          $randomorder,$randompick,
 9635:                                          \%respnumlookup,\%startline);
 9636:             $record{$pid} .= $recording;
 9637:         }
 9638:     }
 9639:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9640:     $r->print('<br />');
 9641:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9642:     $passed = 0;
 9643:     $failed = 0;
 9644:     $numstudents = 0;
 9645:     foreach my $last (sort(keys(%bylast))) {
 9646:         if (ref($bylast{$last}) eq 'ARRAY') {
 9647:             foreach my $pid (sort(@{$bylast{$last}})) {
 9648:                 my $showscandata = $scandata{$pid};
 9649:                 my $showrecord = $record{$pid};
 9650:                 $showscandata =~ s/\s/&nbsp;/g;
 9651:                 $showrecord =~ s/\s/&nbsp;/g;
 9652:                 if ($scandata{$pid} eq $record{$pid}) {
 9653:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9654:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9655: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9656: '</tr>'."\n".
 9657: '<tr class="'.$css_class.'">'."\n".
 9658: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9659:                     $passed ++;
 9660:                 } else {
 9661:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9662:                     $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".
 9663: '</tr>'."\n".
 9664: '<tr class="'.$css_class.'">'."\n".
 9665: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9666: '</tr>'."\n";
 9667:                     $failed ++;
 9668:                 }
 9669:                 $numstudents ++;
 9670:             }
 9671:         }
 9672:     }
 9673:     $r->print('<p>'.
 9674:               &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).',
 9675:                   '<b>',
 9676:                   $numstudents,
 9677:                   '</b>',
 9678:                   $env{'form.scantron_maxbubble'}).
 9679:               '</p>'
 9680:     );
 9681:     $r->print('<p>'
 9682:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9683:              .'<br />'
 9684:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9685:              .'</p>');
 9686:     if ($passed) {
 9687:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9688:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9689:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9690:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9691:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9692:                  $okstudents."\n".
 9693:                  &Apache::loncommon::end_data_table().'<br />');
 9694:     }
 9695:     if ($failed) {
 9696:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9697:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9698:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9699:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9700:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9701:                  $badstudents."\n".
 9702:                  &Apache::loncommon::end_data_table()).'<br />'.
 9703:                  &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.');  
 9704:     }
 9705:     $r->print('</form><br />');
 9706:     return;
 9707: }
 9708: 
 9709: sub verify_scantron_grading {
 9710:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9711:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9712:         $respnumlookup,$startline) = @_;
 9713:     my ($record,%expected,%startpos);
 9714:     return ($counter,$record) if (!ref($resource));
 9715:     return ($counter,$record) if (!$resource->is_problem());
 9716:     my $symb = $resource->symb();
 9717:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9718:     foreach my $part_id (@{$partids}) {
 9719:         $counter ++;
 9720:         $expected{$part_id} = 0;
 9721:         my $respnum = $counter;
 9722:         if ($randomorder || $randompick) {
 9723:             $respnum = $respnumlookup->{$counter};
 9724:             $startpos{$part_id} = $startline->{$counter} + 1;
 9725:         } else {
 9726:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9727:         }
 9728:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9729:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9730:             foreach my $item (@sub_lines) {
 9731:                 $expected{$part_id} += $item;
 9732:             }
 9733:         } else {
 9734:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9735:         }
 9736:     }
 9737:     if ($symb) {
 9738:         my %recorded;
 9739:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9740:         if ($returnhash{'version'}) {
 9741:             my %lasthash=();
 9742:             my $version;
 9743:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9744:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9745:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9746:                 }
 9747:             }
 9748:             foreach my $key (keys(%lasthash)) {
 9749:                 if ($key =~ /\.scantron$/) {
 9750:                     my $value = &unescape($lasthash{$key});
 9751:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9752:                     if ($value eq '') {
 9753:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9754:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9755:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9756:                             }
 9757:                         }
 9758:                     } else {
 9759:                         my @tocheck;
 9760:                         my @items = split(//,$value);
 9761:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9762:                             ($scantron_config->{'Qon'} eq 'number')) {
 9763:                             if (@items < $expected{$part_id}) {
 9764:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9765:                                 my @singles = split(//,$fragment);
 9766:                                 foreach my $pos (@singles) {
 9767:                                     if ($pos eq ' ') {
 9768:                                         push(@tocheck,$pos);
 9769:                                     } else {
 9770:                                         my $next = shift(@items);
 9771:                                         push(@tocheck,$next);
 9772:                                     }
 9773:                                 }
 9774:                             } else {
 9775:                                 @tocheck = @items;
 9776:                             }
 9777:                             foreach my $letter (@tocheck) {
 9778:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9779:                                     if ($letter !~ /^[A-J]$/) {
 9780:                                         $letter = $scantron_config->{'Qoff'};
 9781:                                     }
 9782:                                     $recorded{$part_id} .= $letter;
 9783:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9784:                                     my $digit;
 9785:                                     if ($letter !~ /^[A-J]$/) {
 9786:                                         $digit = $scantron_config->{'Qoff'};
 9787:                                     } else {
 9788:                                         $digit = $lettdig->{$letter};
 9789:                                     }
 9790:                                     $recorded{$part_id} .= $digit;
 9791:                                 }
 9792:                             }
 9793:                         } else {
 9794:                             @tocheck = @items;
 9795:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9796:                                 my $curr_sub = shift(@tocheck);
 9797:                                 my $digit;
 9798:                                 if ($curr_sub =~ /^[A-J]$/) {
 9799:                                     $digit = $lettdig->{$curr_sub}-1;
 9800:                                 }
 9801:                                 if ($curr_sub eq 'J') {
 9802:                                     $digit += scalar($numletts);
 9803:                                 }
 9804:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9805:                                     if ($j == $digit) {
 9806:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9807:                                     } else {
 9808:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9809:                                     }
 9810:                                 }
 9811:                             }
 9812:                         }
 9813:                     }
 9814:                 }
 9815:             }
 9816:         }
 9817:         foreach my $part_id (@{$partids}) {
 9818:             if ($recorded{$part_id} eq '') {
 9819:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9820:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9821:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9822:                     }
 9823:                 }
 9824:             }
 9825:             $record .= $recorded{$part_id};
 9826:         }
 9827:     }
 9828:     return ($counter,$record);
 9829: }
 9830: 
 9831: #-------- end of section for handling grading scantron forms -------
 9832: #
 9833: #-------------------------------------------------------------------
 9834: 
 9835: #-------------------------- Menu interface -------------------------
 9836: #
 9837: #--- Href with symb and command ---
 9838: 
 9839: sub href_symb_cmd {
 9840:     my ($symb,$cmd)=@_;
 9841:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9842: }
 9843: 
 9844: sub grading_menu {
 9845:     my ($request,$symb) = @_;
 9846:     if (!$symb) {return '';}
 9847: 
 9848:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9849:                   'command'=>'individual');
 9850: 
 9851:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9852: 
 9853:     $fields{'command'}='ungraded';
 9854:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9855: 
 9856:     $fields{'command'}='table';
 9857:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9858: 
 9859:     $fields{'command'}='all_for_one';
 9860:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9861: 
 9862:     $fields{'command'}='downloadfilesselect';
 9863:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9864:     
 9865:     $fields{'command'} = 'csvform';
 9866:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9867:     
 9868:     $fields{'command'} = 'processclicker';
 9869:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9870:     
 9871:     $fields{'command'} = 'scantron_selectphase';
 9872:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9873: 
 9874:     $fields{'command'} = 'initialverifyreceipt';
 9875:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9876:     
 9877:     my @menu = ({	categorytitle=>'Hand Grading',
 9878:             items =>[
 9879:                         {       linktext => 'Select individual students to grade',
 9880:                                 url => $url1a,
 9881:                                 permission => 'F',
 9882:                                 icon => 'grade_students.png',
 9883:                                 linktitle => 'Grade current resource for a selection of students.'
 9884:                         },
 9885:                         {       linktext => 'Grade ungraded submissions',
 9886:                                 url => $url1b,
 9887:                                 permission => 'F',
 9888:                                 icon => 'ungrade_sub.png',
 9889:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9890:                         },
 9891: 
 9892:                         {       linktext => 'Grading table',
 9893:                                 url => $url1c,
 9894:                                 permission => 'F',
 9895:                                 icon => 'grading_table.png',
 9896:                                 linktitle => 'Grade current resource for all students.'
 9897:                         },
 9898:                         {       linktext => 'Grade page/folder for one student',
 9899:                                 url => $url1d,
 9900:                                 permission => 'F',
 9901:                                 icon => 'grade_PageFolder.png',
 9902:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9903:                         },
 9904:                         {       linktext => 'Download submitted files',
 9905:                                 url => $url1e,
 9906:                                 permission => 'F',
 9907:                                 icon => 'download_sub.png',
 9908:                                 linktitle => 'Download all files submitted by students.'
 9909:                         }]},
 9910:                          { categorytitle=>'Automated Grading',
 9911:                items =>[
 9912: 
 9913:                 	    {	linktext => 'Upload Scores',
 9914:                     		url => $url2,
 9915:                     		permission => 'F',
 9916:                     		icon => 'uploadscores.png',
 9917:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9918:                 	    },
 9919:                 	    {	linktext => 'Process Clicker',
 9920:                     		url => $url3,
 9921:                     		permission => 'F',
 9922:                     		icon => 'addClickerInfoFile.png',
 9923:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9924:                 	    },
 9925:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9926:                     		url => $url4,
 9927:                     		permission => 'F',
 9928:                     		icon => 'bubblesheet.png',
 9929:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9930:                 	    },
 9931:                             {   linktext => 'Verify Receipt Number',
 9932:                                 url => $url5,
 9933:                                 permission => 'F',
 9934:                                 icon => 'receipt_number.png',
 9935:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9936:                             }
 9937: 
 9938:                     ]
 9939:             });
 9940: 
 9941:     # Create the menu
 9942:     my $Str;
 9943:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9944:     $Str .= '<input type="hidden" name="command" value="" />'.
 9945:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9946: 
 9947:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9948:     return $Str;    
 9949: }
 9950: 
 9951: sub ungraded {
 9952:     my ($request)=@_;
 9953:     &submit_options($request);
 9954: }
 9955: 
 9956: sub submit_options_sequence {
 9957:     my ($request,$symb) = @_;
 9958:     if (!$symb) {return '';}
 9959:     &commonJSfunctions($request);
 9960:     my $result;
 9961: 
 9962:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9963:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9964:     $result.=&selectfield(0).
 9965:             '<input type="hidden" name="command" value="pickStudentPage" />
 9966:             <div>
 9967:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9968:             </div>
 9969:         </div>
 9970:   </form>';
 9971:     return $result;
 9972: }
 9973: 
 9974: sub submit_options_table {
 9975:     my ($request,$symb) = @_;
 9976:     if (!$symb) {return '';}
 9977:     &commonJSfunctions($request);
 9978:     my $result;
 9979: 
 9980:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9981:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9982: 
 9983:     $result.=&selectfield(1).
 9984:             '<input type="hidden" name="command" value="viewgrades" />
 9985:             <div>
 9986:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9987:             </div>
 9988:         </div>
 9989:   </form>';
 9990:     return $result;
 9991: }
 9992: 
 9993: sub submit_options_download {
 9994:     my ($request,$symb) = @_;
 9995:     if (!$symb) {return '';}
 9996: 
 9997:     my $res_error;
 9998:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 9999:         &response_type($symb,\$res_error);
10000:     if ($res_error) {
10001:         $request->print(&mt('An error occurred retrieving response types'));
10002:         return;
10003:     }
10004:     unless ($numessay) {
10005:         $request->print(&mt('No essayresponse items found'));
10006:         return;
10007:     }
10008:     my $table;
10009:     if (ref($partlist) eq 'ARRAY') {
10010:         if (scalar(@$partlist) > 1 ) {
10011:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10012:         }
10013:     }
10014: 
10015:     &commonJSfunctions($request);
10016: 
10017:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10018:         $table."\n".
10019:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10020:     $result.='
10021: <h2>
10022:   '.&mt('Select Students for whom to Download Submitted Files').'
10023: </h2>'.&selectfield(1).'
10024:                 <input type="hidden" name="command" value="downloadfileslink" />
10025:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10026:             </div>
10027:           </div>
10028: 
10029: 
10030:   </form>';
10031:     return $result;
10032: }
10033: 
10034: #--- Displays the submissions first page -------
10035: sub submit_options {
10036:     my ($request,$symb) = @_;
10037:     if (!$symb) {return '';}
10038: 
10039:     &commonJSfunctions($request);
10040:     my $result;
10041: 
10042:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10043: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10044:     $result.=&selectfield(1).'
10045:                 <input type="hidden" name="command" value="submission" />
10046:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10047:             </div>
10048:           </div>
10049:   </form>';
10050:     return $result;
10051: }
10052: 
10053: sub selectfield {
10054:    my ($full)=@_;
10055:    my %options =
10056:        (&substatus_options,
10057:         'select_form_order' => ['yes','queued','graded','incorrect','all']);
10058:    my $result='<div class="LC_columnSection">
10059: 
10060:     <fieldset>
10061:       <legend>
10062:        '.&mt('Sections').'
10063:       </legend>
10064:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10065:     </fieldset>
10066: 
10067:     <fieldset>
10068:       <legend>
10069:         '.&mt('Groups').'
10070:       </legend>
10071:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10072:     </fieldset>
10073:  
10074:     <fieldset>
10075:       <legend>
10076:         '.&mt('Access Status').'
10077:       </legend>
10078:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10079:     </fieldset>';
10080:     if ($full) {
10081:         $result.='
10082:     <fieldset>
10083:       <legend>
10084:         '.&mt('Submission Status').'
10085:       </legend>'.
10086:        &Apache::loncommon::select_form('all','submitonly',\%options).
10087:    '</fieldset>';
10088:     }
10089:     $result.='</div><br />';
10090:     return $result;
10091: }
10092: 
10093: sub substatus_options {
10094:     return &Apache::lonlocal::texthash(
10095:                                       'yes'       => 'with submissions',
10096:                                       'queued'    => 'in grading queue',
10097:                                       'graded'    => 'with ungraded submissions',
10098:                                       'incorrect' => 'with incorrect submissions',
10099:                                       'all'       => 'with any status',
10100:                                       );
10101: }
10102: 
10103: sub transtatus_options {
10104:     return &Apache::lonlocal::texthash(
10105:                                        'yes'       => 'with score transactions',
10106:                                        'incorrect' => 'with less than full credit',
10107:                                        'all'       => 'with any status',
10108:                                       );
10109: }
10110: 
10111: sub reset_perm {
10112:     undef(%perm);
10113: }
10114: 
10115: sub init_perm {
10116:     &reset_perm();
10117:     foreach my $test_perm ('vgr','mgr','opa') {
10118: 
10119: 	my $scope = $env{'request.course.id'};
10120: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10121: 
10122: 	    $scope .= '/'.$env{'request.course.sec'};
10123: 	    if ( $perm{$test_perm}=
10124: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10125: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10126: 	    } else {
10127: 		delete($perm{$test_perm});
10128: 	    }
10129: 	}
10130:     }
10131: }
10132: 
10133: sub init_old_essays {
10134:     my ($symb,$apath,$adom,$aname) = @_;
10135:     if ($symb ne '') {
10136:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10137:         if (keys(%essays) > 0) {
10138:             $old_essays{$symb} = \%essays;
10139:         }
10140:     }
10141:     return;
10142: }
10143: 
10144: sub reset_old_essays {
10145:     undef(%old_essays);
10146: }
10147: 
10148: sub gather_clicker_ids {
10149:     my %clicker_ids;
10150: 
10151:     my $classlist = &Apache::loncoursedata::get_classlist();
10152: 
10153:     # Set up a couple variables.
10154:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10155:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10156:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10157: 
10158:     foreach my $student (keys(%$classlist)) {
10159:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10160:         my $username = $classlist->{$student}->[$username_idx];
10161:         my $domain   = $classlist->{$student}->[$domain_idx];
10162:         my $clickers =
10163: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10164:         foreach my $id (split(/\,/,$clickers)) {
10165:             $id=~s/^[\#0]+//;
10166:             $id=~s/[\-\:]//g;
10167:             if (exists($clicker_ids{$id})) {
10168: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10169:             } else {
10170: 		$clicker_ids{$id}=$username.':'.$domain;
10171:             }
10172:         }
10173:     }
10174:     return %clicker_ids;
10175: }
10176: 
10177: sub gather_adv_clicker_ids {
10178:     my %clicker_ids;
10179:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10180:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10181:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10182:     foreach my $element (sort(keys(%coursepersonnel))) {
10183:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10184:             my ($puname,$pudom)=split(/\:/,$person);
10185:             my $clickers =
10186: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10187:             foreach my $id (split(/\,/,$clickers)) {
10188: 		$id=~s/^[\#0]+//;
10189:                 $id=~s/[\-\:]//g;
10190: 		if (exists($clicker_ids{$id})) {
10191: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10192: 		} else {
10193: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10194: 		}
10195:             }
10196:         }
10197:     }
10198:     return %clicker_ids;
10199: }
10200: 
10201: sub clicker_grading_parameters {
10202:     return ('gradingmechanism' => 'scalar',
10203:             'upfiletype' => 'scalar',
10204:             'specificid' => 'scalar',
10205:             'pcorrect' => 'scalar',
10206:             'pincorrect' => 'scalar');
10207: }
10208: 
10209: sub process_clicker {
10210:     my ($r,$symb)=@_;
10211:     if (!$symb) {return '';}
10212:     my $result=&checkforfile_js();
10213:     $result.=&Apache::loncommon::start_data_table().
10214:              &Apache::loncommon::start_data_table_header_row().
10215:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10216:              &Apache::loncommon::end_data_table_header_row().
10217:              &Apache::loncommon::start_data_table_row()."<td>\n";
10218: # Attempt to restore parameters from last session, set defaults if not present
10219:     my %Saveable_Parameters=&clicker_grading_parameters();
10220:     &Apache::loncommon::restore_course_settings('grades_clicker',
10221:                                                  \%Saveable_Parameters);
10222:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10223:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10224:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10225:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10226: 
10227:     my %checked;
10228:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10229:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10230:           $checked{$gradingmechanism}=' checked="checked"';
10231:        }
10232:     }
10233: 
10234:     my $upload=&mt("Evaluate File");
10235:     my $type=&mt("Type");
10236:     my $attendance=&mt("Award points just for participation");
10237:     my $personnel=&mt("Correctness determined from response by course personnel");
10238:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10239:     my $given=&mt("Correctness determined from given list of answers").' '.
10240:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10241:     my $pcorrect=&mt("Percentage points for correct solution");
10242:     my $pincorrect=&mt("Percentage points for incorrect solution");
10243:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10244:                                                    {'iclicker' => 'i>clicker',
10245:                                                     'interwrite' => 'interwrite PRS',
10246:                                                     'turning' => 'Turning Technologies'});
10247:     $symb = &Apache::lonenc::check_encrypt($symb);
10248:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10249: function sanitycheck() {
10250: // Accept only integer percentages
10251:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10252:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10253: // Find out grading choice
10254:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10255:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10256:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10257:       }
10258:    }
10259: // By default, new choice equals user selection
10260:    newgradingchoice=gradingchoice;
10261: // Not good to give more points for false answers than correct ones
10262:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10263:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10264:    }
10265: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10266:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10267:       document.forms.gradesupload.pcorrect.value=100;
10268:       document.forms.gradesupload.pincorrect.value=100;
10269:    }
10270: // If the values are different, cannot be attendance only
10271:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10272:        (gradingchoice=='attendance')) {
10273:        newgradingchoice='personnel';
10274:    }
10275: // Change grading choice to new one
10276:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10277:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10278:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10279:       } else {
10280:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10281:       }
10282:    }
10283: // Remember the old state
10284:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10285: }
10286: ENDUPFORM
10287:     $result.= <<ENDUPFORM;
10288: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10289: <input type="hidden" name="symb" value="$symb" />
10290: <input type="hidden" name="command" value="processclickerfile" />
10291: <input type="file" name="upfile" size="50" />
10292: <br /><label>$type: $selectform</label>
10293: ENDUPFORM
10294:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10295:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10296:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10297: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10298: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10299: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10300: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10301: <br />&nbsp;&nbsp;&nbsp;
10302: <input type="text" name="givenanswer" size="50" />
10303: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10304: ENDGRADINGFORM
10305:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10306:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10307:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10308: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10309: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10310: </form>
10311: ENDPERCFORM
10312:     $result.='</td>'.
10313:              &Apache::loncommon::end_data_table_row().
10314:              &Apache::loncommon::end_data_table();
10315:     return $result;
10316: }
10317: 
10318: sub process_clicker_file {
10319:     my ($r,$symb) = @_;
10320:     if (!$symb) {return '';}
10321: 
10322:     my %Saveable_Parameters=&clicker_grading_parameters();
10323:     &Apache::loncommon::store_course_settings('grades_clicker',
10324:                                               \%Saveable_Parameters);
10325:     my $result='';
10326:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10327: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10328: 	return $result;
10329:     }
10330:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10331:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10332:         return $result;
10333:     }
10334:     my $foundgiven=0;
10335:     if ($env{'form.gradingmechanism'} eq 'given') {
10336:         $env{'form.givenanswer'}=~s/^\s*//gs;
10337:         $env{'form.givenanswer'}=~s/\s*$//gs;
10338:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10339:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10340:         my @answers=split(/\,/,$env{'form.givenanswer'});
10341:         $foundgiven=$#answers+1;
10342:     }
10343:     my %clicker_ids=&gather_clicker_ids();
10344:     my %correct_ids;
10345:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10346: 	%correct_ids=&gather_adv_clicker_ids();
10347:     }
10348:     if ($env{'form.gradingmechanism'} eq 'specific') {
10349: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10350: 	   $correct_id=~tr/a-z/A-Z/;
10351: 	   $correct_id=~s/\s//gs;
10352: 	   $correct_id=~s/^[\#0]+//;
10353:            $correct_id=~s/[\-\:]//g;
10354:            if ($correct_id) {
10355: 	      $correct_ids{$correct_id}='specified';
10356:            }
10357:         }
10358:     }
10359:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10360: 	$result.=&mt('Score based on attendance only');
10361:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10362:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10363:     } else {
10364: 	my $number=0;
10365: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10366: 	foreach my $id (sort(keys(%correct_ids))) {
10367: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10368: 	    if ($correct_ids{$id} eq 'specified') {
10369: 		$result.=&mt('specified');
10370: 	    } else {
10371: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10372: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10373: 	    }
10374: 	    $number++;
10375: 	}
10376:         $result.="</p>\n";
10377:         if ($number==0) {
10378:             $result .=
10379:                  &Apache::lonhtmlcommon::confirm_success(
10380:                      &mt('No IDs found to determine correct answer'),1);
10381:             return $result;
10382:         }
10383:     }
10384:     if (length($env{'form.upfile'}) < 2) {
10385:         $result .=
10386:             &Apache::lonhtmlcommon::confirm_success(
10387:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10388:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10389:         return $result;
10390:     }
10391:     my $mimetype;
10392:     if ($env{'form.upfiletype'} eq 'iclicker') {
10393:         my $mm = new File::MMagic;
10394:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10395:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10396:             $result.= '<p>'.
10397:                 &Apache::lonhtmlcommon::confirm_success(
10398:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10399:             return $result;
10400:         }
10401:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10402:         $result .= '<p>'.
10403:             &Apache::lonhtmlcommon::confirm_success(
10404:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10405:         return $result;
10406:     }
10407: 
10408: # Were able to get all the info needed, now analyze the file
10409: 
10410:     $result.=&Apache::loncommon::studentbrowser_javascript();
10411:     $symb = &Apache::lonenc::check_encrypt($symb);
10412:     $result.=&Apache::loncommon::start_data_table().
10413:              &Apache::loncommon::start_data_table_header_row().
10414:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10415:              &Apache::loncommon::end_data_table_header_row().
10416:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10417: <td>
10418: <form method="post" action="/adm/grades" name="clickeranalysis">
10419: <input type="hidden" name="symb" value="$symb" />
10420: <input type="hidden" name="command" value="assignclickergrades" />
10421: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10422: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10423: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10424: ENDHEADER
10425:     if ($env{'form.gradingmechanism'} eq 'given') {
10426:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10427:     } 
10428:     my %responses;
10429:     my @questiontitles;
10430:     my $errormsg='';
10431:     my $number=0;
10432:     if ($env{'form.upfiletype'} eq 'iclicker') {
10433:         if ($mimetype eq 'text/plain') {
10434:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10435:         } elsif ($mimetype eq 'text/html') {
10436:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10437:         }
10438:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10439:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10440:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10441:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10442:     }
10443:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10444:              '<input type="hidden" name="number" value="'.$number.'" />'.
10445:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10446:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10447:              '<br />';
10448:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10449:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10450:        return $result;
10451:     } 
10452: # Remember Question Titles
10453: # FIXME: Possibly need delimiter other than ":"
10454:     for (my $i=0;$i<$number;$i++) {
10455:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10456:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10457:     }
10458:     my $correct_count=0;
10459:     my $student_count=0;
10460:     my $unknown_count=0;
10461: # Match answers with usernames
10462: # FIXME: Possibly need delimiter other than ":"
10463:     foreach my $id (keys(%responses)) {
10464:        if ($correct_ids{$id}) {
10465:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10466:           $correct_count++;
10467:        } elsif ($clicker_ids{$id}) {
10468:           if ($clicker_ids{$id}=~/\,/) {
10469: # More than one user with the same clicker!
10470:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10471:                            &Apache::loncommon::start_data_table_row()."<td>".
10472:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10473:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10474:                            "<select name='multi".$id."'>";
10475:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10476:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10477:              }
10478:              $result.='</select>';
10479:              $unknown_count++;
10480:           } else {
10481: # Good: found one and only one user with the right clicker
10482:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10483:              $student_count++;
10484:           }
10485:        } else {
10486:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10487:                            &Apache::loncommon::start_data_table_row()."<td>".
10488:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10489:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10490:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10491:                    "\n".&mt("Domain").": ".
10492:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10493:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10494:           $unknown_count++;
10495:        }
10496:     }
10497:     $result.='<hr />'.
10498:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10499:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10500:        if ($correct_count==0) {
10501:           $errormsg.="Found no correct answers for grading!";
10502:        } elsif ($correct_count>1) {
10503:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10504:        }
10505:     }
10506:     if ($number<1) {
10507:        $errormsg.="Found no questions.";
10508:     }
10509:     if ($errormsg) {
10510:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10511:     } else {
10512:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10513:     }
10514:     $result.='</form></td>'.
10515:              &Apache::loncommon::end_data_table_row().
10516:              &Apache::loncommon::end_data_table();
10517:     return $result;
10518: }
10519: 
10520: sub iclicker_eval {
10521:     my ($questiontitles,$responses)=@_;
10522:     my $number=0;
10523:     my $errormsg='';
10524:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10525:         my %components=&Apache::loncommon::record_sep($line);
10526:         my @entries=map {$components{$_}} (sort(keys(%components)));
10527: 	if ($entries[0] eq 'Question') {
10528: 	    for (my $i=3;$i<$#entries;$i+=6) {
10529: 		$$questiontitles[$number]=$entries[$i];
10530: 		$number++;
10531: 	    }
10532: 	}
10533: 	if ($entries[0]=~/^\#/) {
10534: 	    my $id=$entries[0];
10535: 	    my @idresponses;
10536: 	    $id=~s/^[\#0]+//;
10537: 	    for (my $i=0;$i<$number;$i++) {
10538: 		my $idx=3+$i*6;
10539:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10540: 		push(@idresponses,$entries[$idx]);
10541: 	    }
10542: 	    $$responses{$id}=join(',',@idresponses);
10543: 	}
10544:     }
10545:     return ($errormsg,$number);
10546: }
10547: 
10548: sub iclickerxml_eval {
10549:     my ($questiontitles,$responses)=@_;
10550:     my $number=0;
10551:     my $errormsg='';
10552:     my @state;
10553:     my %respbyid;
10554:     my $p = HTML::Parser->new
10555:     (
10556:         xml_mode => 1,
10557:         start_h =>
10558:             [sub {
10559:                  my ($tagname,$attr) = @_;
10560:                  push(@state,$tagname);
10561:                  if ("@state" eq "ssn p") {
10562:                      my $title = $attr->{qn};
10563:                      $title =~ s/(^\s+|\s+$)//g;
10564:                      $questiontitles->[$number]=$title;
10565:                  } elsif ("@state" eq "ssn p v") {
10566:                      my $id = $attr->{id};
10567:                      my $entry = $attr->{ans};
10568:                      $id=~s/^[\#0]+//;
10569:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10570:                      $respbyid{$id}[$number] = $entry;
10571:                  }
10572:             }, "tagname, attr"],
10573:          end_h =>
10574:                [sub {
10575:                    my ($tagname) = @_;
10576:                    if ("@state" eq "ssn p") {
10577:                        $number++;
10578:                    }
10579:                    pop(@state);
10580:                 }, "tagname"],
10581:     );
10582: 
10583:     $p->parse($env{'form.upfile'});
10584:     $p->eof;
10585:     foreach my $id (keys(%respbyid)) {
10586:         $responses->{$id}=join(',',@{$respbyid{$id}});
10587:     }
10588:     return ($errormsg,$number);
10589: }
10590: 
10591: sub interwrite_eval {
10592:     my ($questiontitles,$responses)=@_;
10593:     my $number=0;
10594:     my $errormsg='';
10595:     my $skipline=1;
10596:     my $questionnumber=0;
10597:     my %idresponses=();
10598:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10599:         my %components=&Apache::loncommon::record_sep($line);
10600:         my @entries=map {$components{$_}} (sort(keys(%components)));
10601:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10602:         if ($entries[1] eq 'Response') { $skipline=1; }
10603:         next if $skipline;
10604:         if ($entries[0]!=$questionnumber) {
10605:            $questionnumber=$entries[0];
10606:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10607:            $number++;
10608:         }
10609:         my $id=$entries[4];
10610:         $id=~s/^[\#0]+//;
10611:         $id=~s/^v\d*\://i;
10612:         $id=~s/[\-\:]//g;
10613:         $idresponses{$id}[$number]=$entries[6];
10614:     }
10615:     foreach my $id (keys(%idresponses)) {
10616:        $$responses{$id}=join(',',@{$idresponses{$id}});
10617:        $$responses{$id}=~s/^\s*\,//;
10618:     }
10619:     return ($errormsg,$number);
10620: }
10621: 
10622: sub turning_eval {
10623:     my ($questiontitles,$responses)=@_;
10624:     my $number=0;
10625:     my $errormsg='';
10626:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10627:         my %components=&Apache::loncommon::record_sep($line);
10628:         my @entries=map {$components{$_}} (sort(keys(%components)));
10629:         if ($#entries>$number) { $number=$#entries; }
10630:         my $id=$entries[0];
10631:         my @idresponses;
10632:         $id=~s/^[\#0]+//;
10633:         unless ($id) { next; }
10634:         for (my $idx=1;$idx<=$#entries;$idx++) {
10635:             $entries[$idx]=~s/\,/\;/g;
10636:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10637:             push(@idresponses,$entries[$idx]);
10638:         }
10639:         $$responses{$id}=join(',',@idresponses);
10640:     }
10641:     for (my $i=1; $i<=$number; $i++) {
10642:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10643:     }
10644:     return ($errormsg,$number);
10645: }
10646: 
10647: sub assign_clicker_grades {
10648:     my ($r,$symb) = @_;
10649:     if (!$symb) {return '';}
10650: # See which part we are saving to
10651:     my $res_error;
10652:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10653:     if ($res_error) {
10654:         return &navmap_errormsg();
10655:     }
10656: # FIXME: This should probably look for the first handgradeable part
10657:     my $part=$$partlist[0];
10658: # Start screen output
10659:     my $result = &Apache::loncommon::start_data_table(). 
10660:                  &Apache::loncommon::start_data_table_header_row().
10661:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10662:                  &Apache::loncommon::end_data_table_header_row().
10663:                  &Apache::loncommon::start_data_table_row().'<td>';
10664: # Get correct result
10665: # FIXME: Possibly need delimiter other than ":"
10666:     my @correct=();
10667:     my $gradingmechanism=$env{'form.gradingmechanism'};
10668:     my $number=$env{'form.number'};
10669:     if ($gradingmechanism ne 'attendance') {
10670:        foreach my $key (keys(%env)) {
10671:           if ($key=~/^form\.correct\:/) {
10672:              my @input=split(/\,/,$env{$key});
10673:              for (my $i=0;$i<=$#input;$i++) {
10674:                  if (($correct[$i]) && ($input[$i]) &&
10675:                      ($correct[$i] ne $input[$i])) {
10676:                     $result.='<br /><span class="LC_warning">'.
10677:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10678:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10679:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10680:                     $correct[$i]=$input[$i];
10681:                  }
10682:              }
10683:           }
10684:        }
10685:        for (my $i=0;$i<$number;$i++) {
10686:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10687:              $result.='<br /><span class="LC_error">'.
10688:                       &mt('No correct result given for question "[_1]"!',
10689:                           $env{'form.question:'.$i}).'</span>';
10690:           }
10691:        }
10692:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10693:     }
10694: # Start grading
10695:     my $pcorrect=$env{'form.pcorrect'};
10696:     my $pincorrect=$env{'form.pincorrect'};
10697:     my $storecount=0;
10698:     my %users=();
10699:     foreach my $key (keys(%env)) {
10700:        my $user='';
10701:        if ($key=~/^form\.student\:(.*)$/) {
10702:           $user=$1;
10703:        }
10704:        if ($key=~/^form\.unknown\:(.*)$/) {
10705:           my $id=$1;
10706:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10707:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10708:           } elsif ($env{'form.multi'.$id}) {
10709:              $user=$env{'form.multi'.$id};
10710:           }
10711:        }
10712:        if ($user) {
10713:           if ($users{$user}) {
10714:              $result.='<br /><span class="LC_warning">'.
10715:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10716:                       '</span><br />';
10717:           }
10718:           $users{$user}=1;
10719:           my @answer=split(/\,/,$env{$key});
10720:           my $sum=0;
10721:           my $realnumber=$number;
10722:           for (my $i=0;$i<$number;$i++) {
10723:              if  ($correct[$i] eq '-') {
10724:                 $realnumber--;
10725:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10726:                 if ($gradingmechanism eq 'attendance') {
10727:                    $sum+=$pcorrect;
10728:                 } elsif ($correct[$i] eq '*') {
10729:                    $sum+=$pcorrect;
10730:                 } else {
10731: # We actually grade if correct or not
10732:                    my $increment=$pincorrect;
10733: # Special case: numerical answer "0"
10734:                    if ($correct[$i] eq '0') {
10735:                       if ($answer[$i]=~/^[0\.]+$/) {
10736:                          $increment=$pcorrect;
10737:                       }
10738: # General numerical answer, both evaluate to something non-zero
10739:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10740:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10741:                          $increment=$pcorrect;
10742:                       }
10743: # Must be just alphanumeric
10744:                    } elsif ($answer[$i] eq $correct[$i]) {
10745:                       $increment=$pcorrect;
10746:                    }
10747:                    $sum+=$increment;
10748:                 }
10749:              }
10750:           }
10751:           my $ave=$sum/(100*$realnumber);
10752: # Store
10753:           my ($username,$domain)=split(/\:/,$user);
10754:           my %grades=();
10755:           $grades{"resource.$part.solved"}='correct_by_override';
10756:           $grades{"resource.$part.awarded"}=$ave;
10757:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10758:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10759:                                                  $env{'request.course.id'},
10760:                                                  $domain,$username);
10761:           if ($returncode ne 'ok') {
10762:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10763:           } else {
10764:              $storecount++;
10765:           }
10766:        }
10767:     }
10768: # We are done
10769:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10770:              '</td>'.
10771:              &Apache::loncommon::end_data_table_row().
10772:              &Apache::loncommon::end_data_table();
10773:     return $result;
10774: }
10775: 
10776: sub navmap_errormsg {
10777:     return '<div class="LC_error">'.
10778:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10779:            &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>').
10780:            '</div>';
10781: }
10782: 
10783: sub startpage {
10784:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
10785:     my %args;
10786:     if ($onload) {
10787:          my %loaditems = (
10788:                         'onload' => $onload,
10789:                       );
10790:          $args{'add_entries'} = \%loaditems;
10791:     }
10792:     if ($nomenu) {
10793:         $args{'only_body'} = 1;
10794:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
10795:     } else {
10796:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10797:         $args{'bread_crumbs'} = $crumbs;
10798:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
10799:     }
10800:     unless ($nodisplayflag) {
10801:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
10802:     }
10803: }
10804: 
10805: sub select_problem {
10806:     my ($r)=@_;
10807:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10808:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
10809:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10810:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10811: }
10812: 
10813: sub handler {
10814:     my $request=$_[0];
10815:     &reset_caches();
10816:     if ($request->header_only) {
10817:         &Apache::loncommon::content_type($request,'text/html');
10818:         $request->send_http_header;
10819:         return OK;
10820:     }
10821:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10822: 
10823: # see what command we need to execute
10824:  
10825:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10826:     my $command=$commands[0];
10827: 
10828:     &init_perm();
10829:     if (!$env{'request.course.id'}) {
10830:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10831:                 ($command =~ /^scantronupload/)) {
10832:             # Not in a course.
10833:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10834:             return HTTP_NOT_ACCEPTABLE;
10835:         }
10836:     } elsif (!%perm) {
10837:         $request->internal_redirect('/adm/quickgrades');
10838:         return OK;
10839:     }
10840:     &Apache::loncommon::content_type($request,'text/html');
10841:     $request->send_http_header;
10842: 
10843:     if ($#commands > 0) {
10844: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10845:     }
10846: 
10847: # see what the symb is
10848: 
10849:     my $symb=$env{'form.symb'};
10850:     unless ($symb) {
10851:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10852:        $symb=&Apache::lonnet::symbread($url);
10853:     }
10854:     &Apache::lonenc::check_decrypt(\$symb);
10855: 
10856:     $ssi_error = 0;
10857:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10858: #
10859: # Not called from a resource, but inside a course
10860: #
10861:         &startpage($request,undef,[],1,1);
10862:         &select_problem($request);
10863:     } else {
10864:         if ($command eq 'submission' && $perm{'vgr'}) {
10865:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
10866:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10867:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10868:                     &choose_task_version_form($symb,$env{'form.student'},
10869:                                               $env{'form.userdom'});
10870:             }
10871:             my $divforres;
10872:             if ($env{'form.student'} eq '') {
10873:                 $js .= &part_selector_js();
10874:                 $onload = "toggleParts('gradesub');";
10875:             } else {
10876:                 $divforres = 1;
10877:             }
10878:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
10879:             if ($versionform) {
10880:                 if ($divforres) {
10881:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
10882:                 }
10883:                 $request->print($versionform);
10884:             }
10885:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
10886:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10887:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10888:                 &choose_task_version_form($symb,$env{'form.student'},
10889:                                           $env{'form.userdom'},
10890:                                           $env{'form.inhibitmenu'});
10891:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10892:             if ($versionform) {
10893:                 $request->print($versionform);
10894:             }
10895:             $request->print('<br clear="all" />');
10896:             $request->print(&show_previous_task_version($request,$symb));
10897:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10898:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10899:                                        {href=>'',text=>'Select student'}],1,1);
10900:             &pickStudentPage($request,$symb);
10901:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10902:             &startpage($request,$symb,
10903:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10904:                                        {href=>'',text=>'Select student'},
10905:                                        {href=>'',text=>'Grade student'}],1,1);
10906:             &displayPage($request,$symb);
10907:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10908:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10909:                                        {href=>'',text=>'Select student'},
10910:                                        {href=>'',text=>'Grade student'},
10911:                                        {href=>'',text=>'Store grades'}],1,1);
10912:             &updateGradeByPage($request,$symb);
10913:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10914:             &startpage($request,$symb,[{href=>'',text=>'...'},
10915:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
10916:             &processGroup($request,$symb);
10917:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10918:             &startpage($request,$symb);
10919:             $request->print(&grading_menu($request,$symb));
10920:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
10921:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10922:             $request->print(&submit_options($request,$symb));
10923:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10924:             my $js = &part_selector_js();
10925:             my $onload = "toggleParts('gradesub');";
10926:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
10927:                        undef,undef,undef,undef,undef,$js,$onload);
10928:             $request->print(&listStudents($request,$symb,'graded'));
10929:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10930:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10931:             $request->print(&submit_options_table($request,$symb));
10932:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10933:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10934:             $request->print(&submit_options_sequence($request,$symb));
10935:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10936:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10937:             $request->print(&viewgrades($request,$symb));
10938:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10939:             &startpage($request,$symb,[{href=>'',text=>'...'},
10940:                                        {href=>'',text=>'Store grades'}]);
10941:             $request->print(&processHandGrade($request,$symb));
10942:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10943:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10944:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10945:                                                                              text=>"Modify grades"},
10946:                                        {href=>'', text=>"Store grades"}]);
10947:             $request->print(&editgrades($request,$symb));
10948:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10949:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10950:             $request->print(&initialverifyreceipt($request,$symb));
10951:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
10952:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10953:                                        {href=>'',text=>'Verification Result'}]);
10954:             $request->print(&verifyreceipt($request,$symb));
10955:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10956:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10957:             $request->print(&process_clicker($request,$symb));
10958:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10959:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10960:                                        {href=>'', text=>'Process clicker file'}]);
10961:             $request->print(&process_clicker_file($request,$symb));
10962:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10963:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10964:                                        {href=>'', text=>'Process clicker file'},
10965:                                        {href=>'', text=>'Store grades'}]);
10966:             $request->print(&assign_clicker_grades($request,$symb));
10967:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10968:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10969:             $request->print(&upcsvScores_form($request,$symb));
10970:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10971:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10972:             $request->print(&csvupload($request,$symb));
10973:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10974:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10975:             $request->print(&csvuploadmap($request,$symb));
10976:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10977:             if ($env{'form.associate'} ne 'Reverse Association') {
10978:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10979:                 $request->print(&csvuploadoptions($request,$symb));
10980:             } else {
10981:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10982:                     $env{'form.upfile_associate'} = 'reverse';
10983:                 } else {
10984:                     $env{'form.upfile_associate'} = 'forward';
10985:                 }
10986:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10987:                 $request->print(&csvuploadmap($request,$symb));
10988:             }
10989:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10990:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10991:             $request->print(&csvuploadassign($request,$symb));
10992:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10993:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
10994:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
10995:             $request->print(&scantron_selectphase($request,undef,$symb));
10996:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10997:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10998:             $request->print(&scantron_do_warning($request,$symb));
10999:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11000:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11001:             $request->print(&scantron_validate_file($request,$symb));
11002:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11003:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11004:             $request->print(&scantron_process_students($request,$symb));
11005:         } elsif ($command eq 'scantronupload' &&
11006:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11007:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11008:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11009:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11010:             $request->print(&scantron_upload_scantron_data($request,$symb));
11011:         } elsif ($command eq 'scantronupload_save' &&
11012:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11013:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11014:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11015:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11016:         } elsif ($command eq 'scantron_download' &&
11017:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11018:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11019:             $request->print(&scantron_download_scantron_data($request,$symb));
11020:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11021:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11022:             $request->print(&checkscantron_results($request,$symb));
11023:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11024:             my $js = &part_selector_js();
11025:             my $onload = "toggleParts('gradingMenu');";
11026:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11027:                        undef,undef,undef,undef,undef,$js,$onload);
11028:             $request->print(&submit_options_download($request,$symb));
11029:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11030:             &startpage($request,$symb,
11031:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11032:     {href=>'', text=>'Download submitted files'}],
11033:                undef,undef,undef,undef,undef,undef,undef,1);
11034:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11035:             &submit_download_link($request,$symb);
11036:         } elsif ($command) {
11037:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11038:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11039:         }
11040:     }
11041:     if ($ssi_error) {
11042: 	&ssi_print_error($request);
11043:     }
11044:     $request->print(&Apache::loncommon::end_page());
11045:     &reset_caches();
11046:     return OK;
11047: }
11048: 
11049: 1;
11050: 
11051: __END__;
11052: 
11053: 
11054: =head1 NAME
11055: 
11056: Apache::grades
11057: 
11058: =head1 SYNOPSIS
11059: 
11060: Handles the viewing of grades.
11061: 
11062: This is part of the LearningOnline Network with CAPA project
11063: described at http://www.lon-capa.org.
11064: 
11065: =head1 OVERVIEW
11066: 
11067: Do an ssi with retries:
11068: While I'd love to factor out this with the vesrion in lonprintout,
11069: 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
11070: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11071: 
11072: At least the logic that drives this has been pulled out into loncommon.
11073: 
11074: 
11075: 
11076: ssi_with_retries - Does the server side include of a resource.
11077:                      if the ssi call returns an error we'll retry it up to
11078:                      the number of times requested by the caller.
11079:                      If we still have a problem, no text is appended to the
11080:                      output and we set some global variables.
11081:                      to indicate to the caller an SSI error occurred.  
11082:                      All of this is supposed to deal with the issues described
11083:                      in LON-CAPA BZ 5631 see:
11084:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11085:                      by informing the user that this happened.
11086: 
11087: Parameters:
11088:   resource   - The resource to include.  This is passed directly, without
11089:                interpretation to lonnet::ssi.
11090:   form       - The form hash parameters that guide the interpretation of the resource
11091:                
11092:   retries    - Number of retries allowed before giving up completely.
11093: Returns:
11094:   On success, returns the rendered resource identified by the resource parameter.
11095: Side Effects:
11096:   The following global variables can be set:
11097:    ssi_error                - If an unrecoverable error occurred this becomes true.
11098:                               It is up to the caller to initialize this to false
11099:                               if desired.
11100:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11101:                               of the resource that could not be rendered by the ssi
11102:                               call.
11103:    ssi_error_message   - The error string fetched from the ssi response
11104:                               in the event of an error.
11105: 
11106: 
11107: =head1 HANDLER SUBROUTINE
11108: 
11109: ssi_with_retries()
11110: 
11111: =head1 SUBROUTINES
11112: 
11113: =over
11114: 
11115: =item scantron_get_correction() : 
11116: 
11117:    Builds the interface screen to interact with the operator to fix a
11118:    specific error condition in a specific scanline
11119: 
11120:  Arguments:
11121:     $r           - Apache request object
11122:     $i           - number of the current scanline
11123:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11124:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11125:     $line        - full contents of the current scanline
11126:     $error       - error condition, valid values are
11127:                    'incorrectCODE', 'duplicateCODE',
11128:                    'doublebubble', 'missingbubble',
11129:                    'duplicateID', 'incorrectID'
11130:     $arg         - extra information needed
11131:        For errors:
11132:          - duplicateID   - paper number that this studentID was seen before on
11133:          - duplicateCODE - array ref of the paper numbers this CODE was
11134:                            seen on before
11135:          - incorrectCODE - current incorrect CODE 
11136:          - doublebubble  - array ref of the bubble lines that have double
11137:                            bubble errors
11138:          - missingbubble - array ref of the bubble lines that have missing
11139:                            bubble errors
11140: 
11141:    $randomorder - True if exam folder has randomorder set
11142:    $randompick  - True if exam folder has randompick set
11143:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11144:                      for current line to question number used for same question
11145:                      in "Master Seqence" (as seen by Course Coordinator).
11146:    $startline   - Reference to hash where key is question number (0 is first)
11147:                   and value is number of first bubble line for current student
11148:                   or code-based randompick and/or randomorder.
11149: 
11150: 
11151: =item  scantron_get_maxbubble() : 
11152: 
11153:    Arguments:
11154:        $nav_error  - Reference to scalar which is a flag to indicate a
11155:                       failure to retrieve a navmap object.
11156:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11157:        calling routine should trap the error condition and display the warning
11158:        found in &navmap_errormsg().
11159: 
11160:        $scantron_config - Reference to bubblesheet format configuration hash.
11161: 
11162:    Returns the maximum number of bubble lines that are expected to
11163:    occur. Does this by walking the selected sequence rendering the
11164:    resource and then checking &Apache::lonxml::get_problem_counter()
11165:    for what the current value of the problem counter is.
11166: 
11167:    Caches the results to $env{'form.scantron_maxbubble'},
11168:    $env{'form.scantron.bubble_lines.n'}, 
11169:    $env{'form.scantron.first_bubble_line.n'} and
11170:    $env{"form.scantron.sub_bubblelines.n"}
11171:    which are the total number of bubble lines, the number of bubble
11172:    lines for response n and number of the first bubble line for response n,
11173:    and a comma separated list of numbers of bubble lines for sub-questions
11174:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11175: 
11176: 
11177: =item  scantron_validate_missingbubbles() : 
11178: 
11179:    Validates all scanlines in the selected file to not have any
11180:     answers that don't have bubbles that have not been verified
11181:     to be bubble free.
11182: 
11183: =item  scantron_process_students() : 
11184: 
11185:    Routine that does the actual grading of the bubblesheet information.
11186: 
11187:    The parsed scanline hash is added to %env 
11188: 
11189:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11190:    foreach resource , with the form data of
11191: 
11192: 	'submitted'     =>'scantron' 
11193: 	'grade_target'  =>'grade',
11194: 	'grade_username'=> username of student
11195: 	'grade_domain'  => domain of student
11196: 	'grade_courseid'=> of course
11197: 	'grade_symb'    => symb of resource to grade
11198: 
11199:     This triggers a grading pass. The problem grading code takes care
11200:     of converting the bubbled letter information (now in %env) into a
11201:     valid submission.
11202: 
11203: =item  scantron_upload_scantron_data() :
11204: 
11205:     Creates the screen for adding a new bubblesheet data file to a course.
11206: 
11207: =item  scantron_upload_scantron_data_save() : 
11208: 
11209:    Adds a provided bubble information data file to the course if user
11210:    has the correct privileges to do so. 
11211: 
11212: =item  valid_file() :
11213: 
11214:    Validates that the requested bubble data file exists in the course.
11215: 
11216: =item  scantron_download_scantron_data() : 
11217: 
11218:    Shows a list of the three internal files (original, corrected,
11219:    skipped) for a specific bubblesheet data file that exists in the
11220:    course.
11221: 
11222: =item  scantron_validate_ID() : 
11223: 
11224:    Validates all scanlines in the selected file to not have any
11225:    invalid or underspecified student/employee IDs
11226: 
11227: =item navmap_errormsg() :
11228: 
11229:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11230:    Should be called whenever the request to instantiate a navmap object fails.  
11231: 
11232: =back
11233: 
11234: =cut

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