File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.56: download - view: text, annotated - select for diffs
Tue Jan 5 22:01:28 2021 UTC (3 years, 3 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  Backport 1.780, 1.781

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.56 2021/01/05 22:01:28 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::bridgetask();
   48: use Apache::lontexconvert();
   49: use HTML::Parser();
   50: use File::MMagic;
   51: use String::Similarity;
   52: use LONCAPA;
   53: 
   54: use POSIX qw(floor);
   55: 
   56: 
   57: 
   58: my %perm=();
   59: my %old_essays=();
   60: 
   61: #  These variables are used to recover from ssi errors
   62: 
   63: my $ssi_retries = 5;
   64: my $ssi_error;
   65: my $ssi_error_resource;
   66: my $ssi_error_message;
   67: 
   68: 
   69: sub ssi_with_retries {
   70:     my ($resource, $retries, %form) = @_;
   71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   72:     if ($response->is_error) {
   73: 	$ssi_error          = 1;
   74: 	$ssi_error_resource = $resource;
   75: 	$ssi_error_message  = $response->code . " " . $response->message;
   76:     }
   77: 
   78:     return $content;
   79: 
   80: }
   81: #
   82: #  Prodcuces an ssi retry failure error message to the user:
   83: #
   84: 
   85: sub ssi_print_error {
   86:     my ($r) = @_;
   87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   88:     $r->print('
   89: <br />
   90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   91: <p>
   92: '.&mt('Unable to retrieve a resource from a server:').'<br />
   93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   94: '.&mt('Error:').' '.$ssi_error_message.'
   95: </p>
   96: <p>'.
   97: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   99: '</p>');
  100:     return;
  101: }
  102: 
  103: #
  104: # --- Retrieve the parts from the metadata file.---
  105: # Returns an array of everything that the resources stores away
  106: #
  107: 
  108: sub getpartlist {
  109:     my ($symb,$errorref) = @_;
  110: 
  111:     my $navmap   = Apache::lonnavmaps::navmap->new();
  112:     unless (ref($navmap)) {
  113:         if (ref($errorref)) { 
  114:             $$errorref = 'navmap';
  115:             return;
  116:         }
  117:     }
  118:     my $res      = $navmap->getBySymb($symb);
  119:     my $partlist = $res->parts();
  120:     my $url      = $res->src();
  121:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  122: 
  123:     my @stores;
  124:     foreach my $part (@{ $partlist }) {
  125: 	foreach my $key (@metakeys) {
  126: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  127: 	}
  128:     }
  129:     return @stores;
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: #--- Count responseIDs, essayresponse items, and dropbox items ---
  147: #--- Sets response_error pointer to "1" if navmaps object broken ---
  148: sub response_type {
  149:     my ($symb,$response_error) = @_;
  150: 
  151:     my $navmap = Apache::lonnavmaps::navmap->new();
  152:     unless (ref($navmap)) {
  153:         if (ref($response_error)) {
  154:             $$response_error = 1;
  155:         }
  156:         return;
  157:     }
  158:     my $res = $navmap->getBySymb($symb);
  159:     unless (ref($res)) {
  160:         $$response_error = 1;
  161:         return;
  162:     }
  163:     my $partlist = $res->parts();
  164:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  165:     my %vPart = 
  166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  167:     my (%response_types,%handgrade);
  168:     foreach my $part (@{ $partlist }) {
  169: 	next if (%vPart && !exists($vPart{$part}));
  170: 
  171: 	my @types = $res->responseType($part);
  172: 	my @ids = $res->responseIds($part);
  173: 	for (my $i=0; $i < scalar(@ids); $i++) {
  174:             $numresp ++;
  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  176:             if ($types[$i] eq 'essay') {
  177:                 $numessay ++;
  178:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  179:                     $numdropbox ++;
  180:                 }
  181:             }
  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
  183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  184: 				     '.handgrade',$symb);
  185: 	}
  186:     }
  187:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  188: }
  189: 
  190: sub flatten_responseType {
  191:     my ($responseType) = @_;
  192:     my @part_response_id =
  193: 	map { 
  194: 	    my $part = $_;
  195: 	    map {
  196: 		[$part,$_]
  197: 		} sort(keys(%{ $responseType->{$part} }));
  198: 	} sort(keys(%$responseType));
  199:     return @part_response_id;
  200: }
  201: 
  202: sub get_display_part {
  203:     my ($partID,$symb)=@_;
  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  205:     if (defined($display) and $display ne '') {
  206:         $display.= ' (<span class="LC_internal_info">'
  207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  208:     } else {
  209: 	$display=$partID;
  210:     }
  211:     return $display;
  212: }
  213: 
  214: #--- Show parts and response type
  215: sub showResourceInfo {
  216:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  217:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  218:         return '<br clear="all">';
  219:     }
  220:     my $coltitle = &mt('Problem Part Shown');
  221:     if ($checkboxes) {
  222:         $coltitle = &mt('Problem Part');
  223:     } else {
  224:         my $checkedparts = 0;
  225:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  226:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  227:                 $checkedparts ++;
  228:             }
  229:         }
  230:         if ($checkedparts == scalar(@{$partlist})) {
  231:             return '<br clear="all">';
  232:         }
  233:         if ($uploads) {
  234:             $coltitle = &mt('Problem Part Selected');
  235:         }
  236:     }
  237:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  238:     if ($checkboxes) {
  239:         my $legend = &mt('Parts to display');
  240:         if ($uploads) {
  241:             $legend = &mt('Part(s) with dropbox');
  242:         }
  243:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  244:                    '<span class="LC_nobreak">'.
  245:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  246:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  247:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  248:                    &mt('Selected parts').'</label></span>'.
  249:                    '<div id="LC_partselector" style="display:none">';
  250:     }
  251:     $result .= &Apache::loncommon::start_data_table()
  252:               .&Apache::loncommon::start_data_table_header_row();
  253:     if ($checkboxes) {
  254:         $result .= '<th>'.&mt('Display?').'</th>';
  255:     }
  256:     $result .= '<th>'.$coltitle.'</th>'
  257:               .'<th>'.&mt('Res. ID').'</th>'
  258:               .'<th>'.&mt('Type').'</th>'
  259:               .&Apache::loncommon::end_data_table_header_row();
  260:     my %partsseen;
  261:     foreach my $partID (sort(keys(%$responseType))) {
  262:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  263:             my $responsetype = $responseType->{$partID}->{$resID};
  264:             if ($uploads) {
  265:                 next unless ($responsetype eq 'essay');
  266:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  267:             }
  268:             my $display_part=&get_display_part($partID,$symb);
  269:             if (exists($partsseen{$partID})) {
  270:                 $result.=&Apache::loncommon::continue_data_table_row();
  271:             } else {
  272:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  273:                 $result.=&Apache::loncommon::start_data_table_row().
  274:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  275:                 if ($checkboxes) {
  276:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  277:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  278:                 } else {
  279:                     $result.=$display_part.'</td>';
  280:                 }
  281:             }
  282:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  283:                     .'<td>'.&mt($responsetype).'</td>'
  284:                     .&Apache::loncommon::end_data_table_row();
  285:         }
  286:     }
  287:     $result.=&Apache::loncommon::end_data_table();
  288:     if ($checkboxes) {
  289:         $result .= '</div></fieldset>';
  290:     }
  291:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  292:     if (!keys(%partsseen)) {
  293:         $result = '';
  294:         if ($uploads) {
  295:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  296:                    '<p class="LC_info">'.
  297:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  298:                    '</p>';
  299:         } else {
  300:             return '<br clear="all" />';
  301:         }
  302:     }  
  303:     return $result;
  304: }
  305: 
  306: sub part_selector_js {
  307:     my $js = <<"END";
  308: function toggleParts(formname) {
  309:     if (document.getElementById('LC_partselector')) {
  310:         var index = '';
  311:         if (document.forms.length) {
  312:             for (var i=0; i<document.forms.length; i++) {
  313:                 if (document.forms[i].name == formname) {
  314:                     index = i;
  315:                     break;
  316:                 }
  317:             }
  318:         }
  319:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  320:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  321:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  322:                    var val = document.forms[index].elements['chooseparts'][i].value;
  323:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  324:                         document.getElementById('LC_partselector').style.display = 'block';
  325:                     } else {
  326:                         document.getElementById('LC_partselector').style.display = 'none';
  327:                     }
  328:                 }
  329:             }
  330:         }
  331:     }
  332: }
  333: END
  334:     return &Apache::lonhtmlcommon::scripttag($js);
  335: }
  336: 
  337: sub reset_caches {
  338:     &reset_analyze_cache();
  339:     &reset_perm();
  340:     &reset_old_essays();
  341: }
  342: 
  343: {
  344:     my %analyze_cache;
  345:     my %analyze_cache_formkeys;
  346: 
  347:     sub reset_analyze_cache {
  348: 	undef(%analyze_cache);
  349:         undef(%analyze_cache_formkeys);
  350:     }
  351: 
  352:     sub get_analyze {
  353: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  354: 	my $key = "$symb\0$uname\0$udom";
  355:         if ($type eq 'randomizetry') {
  356:             if ($trial ne '') {
  357:                 $key .= "\0".$trial;
  358:             }
  359:         }
  360: 	if (exists($analyze_cache{$key})) {
  361:             my $getupdate = 0;
  362:             if (ref($add_to_hash) eq 'HASH') {
  363:                 foreach my $item (keys(%{$add_to_hash})) {
  364:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  365:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  366:                             $getupdate = 1;
  367:                             last;
  368:                         }
  369:                     } else {
  370:                         $getupdate = 1;
  371:                     }
  372:                 }
  373:             }
  374:             if (!$getupdate) {
  375:                 return $analyze_cache{$key};
  376:             }
  377:         }
  378: 
  379: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  380: 	$url=&Apache::lonnet::clutter($url);
  381:         my %form = ('grade_target'      => 'analyze',
  382:                     'grade_domain'      => $udom,
  383:                     'grade_symb'        => $symb,
  384:                     'grade_courseid'    =>  $env{'request.course.id'},
  385:                     'grade_username'    => $uname,
  386:                     'grade_noincrement' => $no_increment);
  387:         if ($bubbles_per_row ne '') {
  388:             $form{'bubbles_per_row'} = $bubbles_per_row;
  389:         }
  390:         if ($type eq 'randomizetry') {
  391:             $form{'grade_questiontype'} = $type;
  392:             if ($rndseed ne '') {
  393:                 $form{'grade_rndseed'} = $rndseed;
  394:             }
  395:         }
  396:         if (ref($add_to_hash)) {
  397:             %form = (%form,%{$add_to_hash});
  398:         }
  399: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  400: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  401: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  402:         if (ref($add_to_hash) eq 'HASH') {
  403:             $analyze_cache_formkeys{$key} = $add_to_hash;
  404:         } else {
  405:             $analyze_cache_formkeys{$key} = {};
  406:         }
  407: 	return $analyze_cache{$key} = \%analyze;
  408:     }
  409: 
  410:     sub get_order {
  411: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  412: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  413: 	return $analyze->{"$partid.$respid.shown"};
  414:     }
  415: 
  416:     sub get_radiobutton_correct_foil {
  417: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  418: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  419:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  420:         if (ref($foils) eq 'ARRAY') {
  421: 	    foreach my $foil (@{$foils}) {
  422: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  423: 		    return $foil;
  424: 	        }
  425: 	    }
  426: 	}
  427:     }
  428: 
  429:     sub scantron_partids_tograde {
  430:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  431:         my (%analysis,@parts);
  432:         if (ref($resource)) {
  433:             my $symb = $resource->symb();
  434:             my $add_to_form;
  435:             if ($check_for_randomlist) {
  436:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  437:             }
  438:             if ($scancode) {
  439:                 if (ref($add_to_form) eq 'HASH') {
  440:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  441:                 } else {
  442:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  443:                 }
  444:             }
  445:             my $analyze =
  446:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  447:                              undef,undef,undef,$bubbles_per_row);
  448:             if (ref($analyze) eq 'HASH') {
  449:                 %analysis = %{$analyze};
  450:             }
  451:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  452:                 foreach my $part (@{$analysis{'parts'}}) {
  453:                     my ($id,$respid) = split(/\./,$part);
  454:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  455:                         push(@parts,$part);
  456:                     }
  457:                 }
  458:             }
  459:         }
  460:         return (\%analysis,\@parts);
  461:     }
  462: 
  463: }
  464: 
  465: #--- Clean response type for display
  466: #--- Currently filters option/rank/radiobutton/match/essay/Task
  467: #        response types only.
  468: sub cleanRecord {
  469:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  470: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  471:     my $grayFont = '<span class="LC_internal_info">';
  472:     if ($response =~ /^(option|rank)$/) {
  473: 	my %answer=&Apache::lonnet::str2hash($answer);
  474:         my @answer = %answer;
  475:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  476: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  477: 	my ($toprow,$bottomrow);
  478: 	foreach my $foil (@$order) {
  479: 	    if ($grading{$foil} == 1) {
  480: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  481: 	    } else {
  482: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  483: 	    }
  484: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  485: 	}
  486: 	return '<blockquote><table border="1">'.
  487: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  488: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  489: 	    $bottomrow.'</tr></table></blockquote>';
  490:     } elsif ($response eq 'match') {
  491: 	my %answer=&Apache::lonnet::str2hash($answer);
  492:         my @answer = %answer;
  493:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  494: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  495: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  496: 	my ($toprow,$middlerow,$bottomrow);
  497: 	foreach my $foil (@$order) {
  498: 	    my $item=shift(@items);
  499: 	    if ($grading{$foil} == 1) {
  500: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  501: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  502: 	    } else {
  503: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  504: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  505: 	    }
  506: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  507: 	}
  508: 	return '<blockquote><table border="1">'.
  509: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  510: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  511: 	    $middlerow.'</tr>'.
  512: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  513: 	    $bottomrow.'</tr></table></blockquote>';
  514:     } elsif ($response eq 'radiobutton') {
  515: 	my %answer=&Apache::lonnet::str2hash($answer);
  516:         my @answer = %answer;
  517:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  518: 	my ($toprow,$bottomrow);
  519: 	my $correct = 
  520: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  521: 	foreach my $foil (@$order) {
  522: 	    if (exists($answer{$foil})) {
  523: 		if ($foil eq $correct) {
  524: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  525: 		} else {
  526: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  527: 		}
  528: 	    } else {
  529: 		$toprow.='<td>'.&mt('false').'</td>';
  530: 	    }
  531: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  532: 	}
  533: 	return '<blockquote><table border="1">'.
  534: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  535: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  536: 	    $bottomrow.'</tr></table></blockquote>';
  537:     } elsif ($response eq 'essay') {
  538: 	if (! exists ($env{'form.'.$symb})) {
  539: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  540: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  541: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  542: 
  543: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  544: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  545: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  546: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  547: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  548: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  549: 	}
  550:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  551: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  552:     } elsif ( $response eq 'organic') {
  553:         my $result=&mt('Smile representation: [_1]',
  554:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  555: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  556: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  557: 	return $result;
  558:     } elsif ( $response eq 'Task') {
  559: 	if ( $answer eq 'SUBMITTED') {
  560: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  561: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  562: 	    return $result;
  563: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  564: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  565: 			       keys(%{$record}));
  566: 	    return join('<br />',($version,@matches));
  567: 			       
  568: 			       
  569: 	} else {
  570: 	    my $result =
  571: 		'<p>'
  572: 		.&mt('Overall result: [_1]',
  573: 		     $record->{$version."resource.$respid.$partid.status"})
  574: 		.'</p>';
  575: 	    
  576: 	    $result .= '<ul>';
  577: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  578: 			     keys(%{$record}));
  579: 	    foreach my $grade (sort(@grade)) {
  580: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  581: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  582: 				     $dim, $record->{$grade}).
  583: 			  '</li>';
  584: 	    }
  585: 	    $result.='</ul>';
  586: 	    return $result;
  587: 	}
  588:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  589:         # Respect multiple input fields, see Bug #5409 
  590: 	$answer = 
  591: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  592: 							      $answer);
  593: 	return $answer;
  594:     }
  595:     return &HTML::Entities::encode($answer, '"<>&');
  596: }
  597: 
  598: #-- A couple of common js functions
  599: sub commonJSfunctions {
  600:     my $request = shift;
  601:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  602:     function radioSelection(radioButton) {
  603: 	var selection=null;
  604: 	if (radioButton.length > 1) {
  605: 	    for (var i=0; i<radioButton.length; i++) {
  606: 		if (radioButton[i].checked) {
  607: 		    return radioButton[i].value;
  608: 		}
  609: 	    }
  610: 	} else {
  611: 	    if (radioButton.checked) return radioButton.value;
  612: 	}
  613: 	return selection;
  614:     }
  615: 
  616:     function pullDownSelection(selectOne) {
  617: 	var selection="";
  618: 	if (selectOne.length > 1) {
  619: 	    for (var i=0; i<selectOne.length; i++) {
  620: 		if (selectOne[i].selected) {
  621: 		    return selectOne[i].value;
  622: 		}
  623: 	    }
  624: 	} else {
  625:             // only one value it must be the selected one
  626: 	    return selectOne.value;
  627: 	}
  628:     }
  629: COMMONJSFUNCTIONS
  630: }
  631: 
  632: #--- Dumps the class list with usernames,list of sections,
  633: #--- section, ids and fullnames for each user.
  634: sub getclasslist {
  635:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  636:     my @getsec;
  637:     my @getgroup;
  638:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  639:     if (!ref($getsec)) {
  640: 	if ($getsec ne '' && $getsec ne 'all') {
  641: 	    @getsec=($getsec);
  642: 	}
  643:     } else {
  644: 	@getsec=@{$getsec};
  645:     }
  646:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  647:     if (!ref($getgroup)) {
  648: 	if ($getgroup ne '' && $getgroup ne 'all') {
  649: 	    @getgroup=($getgroup);
  650: 	}
  651:     } else {
  652: 	@getgroup=@{$getgroup};
  653:     }
  654:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  655: 
  656:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  657:     # Bail out if we were unable to get the classlist
  658:     return if (! defined($classlist));
  659:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  660:     #
  661:     my %sections;
  662:     my %fullnames;
  663:     my ($cdom,$cnum,$partlist);
  664:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  665:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  666:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  667:         my $res_error;
  668:         ($partlist) = &response_type($symb,\$res_error);
  669:     }
  670:     foreach my $student (keys(%$classlist)) {
  671:         my $end      = 
  672:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  673:         my $start    = 
  674:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  675:         my $id       = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  677:         my $section  = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  679:         my $fullname = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  681:         my $status   = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  683:         my $group   = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  685: 	# filter students according to status selected
  686: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  687: 	    if (!($stu_status =~ $status)) {
  688: 		delete($classlist->{$student});
  689: 		next;
  690: 	    }
  691: 	}
  692: 	# filter students according to groups selected
  693: 	my @stu_groups = split(/,/,$group);
  694: 	if (@getgroup) {
  695: 	    my $exclude = 1;
  696: 	    foreach my $grp (@getgroup) {
  697: 	        foreach my $stu_group (@stu_groups) {
  698: 	            if ($stu_group eq $grp) {
  699: 	                $exclude = 0;
  700:     	            } 
  701: 	        }
  702:     	        if (($grp eq 'none') && !$group) {
  703:         	    $exclude = 0;
  704:         	}
  705: 	    }
  706: 	    if ($exclude) {
  707: 	        delete($classlist->{$student});
  708: 		next;
  709: 	    }
  710: 	}
  711:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  712:             my $udom =
  713:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  714:             my $uname =
  715:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  716:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  717:                 if ($submitonly eq 'queued') {
  718:                     my %queue_status =
  719:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  720:                                                                 $udom,$uname);
  721:                     if (!defined($queue_status{'gradingqueue'})) {
  722:                         delete($classlist->{$student});
  723:                         next;
  724:                     }
  725:                 } else {
  726:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  727:                     my $submitted = 0;
  728:                     my $graded = 0;
  729:                     my $incorrect = 0;
  730:                     foreach (keys(%status)) {
  731:                         $submitted = 1 if ($status{$_} ne 'nothing');
  732:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  733:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  734: 
  735:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  736:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  737:                             $submitted = 0;
  738:                         }
  739:                     }
  740:                     if (!$submitted && ($submitonly eq 'yes' ||
  741:                                         $submitonly eq 'incorrect' ||
  742:                                         $submitonly eq 'graded')) {
  743:                         delete($classlist->{$student});
  744:                         next;
  745:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  746:                         delete($classlist->{$student});
  747:                         next;
  748:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  749:                         delete($classlist->{$student});
  750:                         next;
  751:                     }
  752:                 }
  753:             }
  754:         }
  755: 	$section = ($section ne '' ? $section : 'none');
  756: 	if (&canview($section)) {
  757: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  758: 		$sections{$section}++;
  759: 		if ($classlist->{$student}) {
  760: 		    $fullnames{$student}=$fullname;
  761: 		}
  762: 	    } else {
  763: 		delete($classlist->{$student});
  764: 	    }
  765: 	} else {
  766: 	    delete($classlist->{$student});
  767: 	}
  768:     }
  769:     my @sections = sort(keys(%sections));
  770:     return ($classlist,\@sections,\%fullnames);
  771: }
  772: 
  773: sub canmodify {
  774:     my ($sec)=@_;
  775:     if ($perm{'mgr'}) {
  776: 	if (!defined($perm{'mgr_section'})) {
  777: 	    # can modify whole class
  778: 	    return 1;
  779: 	} else {
  780: 	    if ($sec eq $perm{'mgr_section'}) {
  781: 		#can modify the requested section
  782: 		return 1;
  783: 	    } else {
  784: 		# can't modify the requested section
  785: 		return 0;
  786: 	    }
  787: 	}
  788:     }
  789:     #can't modify
  790:     return 0;
  791: }
  792: 
  793: sub canview {
  794:     my ($sec)=@_;
  795:     if ($perm{'vgr'}) {
  796: 	if (!defined($perm{'vgr_section'})) {
  797: 	    # can view whole class
  798: 	    return 1;
  799: 	} else {
  800: 	    if ($sec eq $perm{'vgr_section'}) {
  801: 		#can view the requested section
  802: 		return 1;
  803: 	    } else {
  804: 		# can't view the requested section
  805: 		return 0;
  806: 	    }
  807: 	}
  808:     }
  809:     #can't view
  810:     return 0;
  811: }
  812: 
  813: #--- Retrieve the grade status of a student for all the parts
  814: sub student_gradeStatus {
  815:     my ($symb,$udom,$uname,$partlist) = @_;
  816:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  817:     my %partstatus = ();
  818:     foreach (@$partlist) {
  819: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  820: 	$status              = 'nothing' if ($status eq '');
  821: 	$partstatus{$_}      = $status;
  822: 	my $subkey           = "resource.$_.submitted_by";
  823: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  824:     }
  825:     return %partstatus;
  826: }
  827: 
  828: # hidden form and javascript that calls the form
  829: # Use by verifyscript and viewgrades
  830: # Shows a student's view of problem and submission
  831: sub jscriptNform {
  832:     my ($symb) = @_;
  833:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  834:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  835: 	'    function viewOneStudent(user,domain) {'."\n".
  836: 	'	document.onestudent.student.value = user;'."\n".
  837: 	'	document.onestudent.userdom.value = domain;'."\n".
  838: 	'	document.onestudent.submit();'."\n".
  839: 	'    }'."\n".
  840: 	"\n");
  841:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  842: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  843: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  844: 	'<input type="hidden" name="command" value="submission" />'."\n".
  845: 	'<input type="hidden" name="student" value="" />'."\n".
  846: 	'<input type="hidden" name="userdom" value="" />'."\n".
  847: 	'</form>'."\n";
  848:     return $jscript;
  849: }
  850: 
  851: 
  852: 
  853: # Given the score (as a number [0-1] and the weight) what is the final
  854: # point value? This function will round to the nearest tenth, third,
  855: # or quarter if one of those is within the tolerance of .00001.
  856: sub compute_points {
  857:     my ($score, $weight) = @_;
  858:     
  859:     my $tolerance = .00001;
  860:     my $points = $score * $weight;
  861: 
  862:     # Check for nearness to 1/x.
  863:     my $check_for_nearness = sub {
  864:         my ($factor) = @_;
  865:         my $num = ($points * $factor) + $tolerance;
  866:         my $floored_num = floor($num);
  867:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  868:             return $floored_num / $factor;
  869:         }
  870:         return $points;
  871:     };
  872: 
  873:     $points = $check_for_nearness->(10);
  874:     $points = $check_for_nearness->(3);
  875:     $points = $check_for_nearness->(4);
  876:     
  877:     return $points;
  878: }
  879: 
  880: #------------------ End of general use routines --------------------
  881: 
  882: #
  883: # Find most similar essay
  884: #
  885: 
  886: sub most_similar {
  887:     my ($uname,$udom,$symb,$uessay)=@_;
  888: 
  889:     unless ($symb) { return ''; }
  890: 
  891:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  892: 
  893: # ignore spaces and punctuation
  894: 
  895:     $uessay=~s/\W+/ /gs;
  896: 
  897: # ignore empty submissions (occuring when only files are sent)
  898: 
  899:     unless ($uessay=~/\w+/s) { return ''; }
  900: 
  901: # these will be returned. Do not care if not at least 50 percent similar
  902:     my $limit=0.6;
  903:     my $sname='';
  904:     my $sdom='';
  905:     my $scrsid='';
  906:     my $sessay='';
  907: # go through all essays ...
  908:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  909: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  910: # ... except the same student
  911:         next if (($tname eq $uname) && ($tdom eq $udom));
  912: 	my $tessay=$old_essays{$symb}{$tkey};
  913: 	$tessay=~s/\W+/ /gs;
  914: # String similarity gives up if not even limit
  915: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  916: # Found one
  917: 	if ($tsimilar>$limit) {
  918: 	    $limit=$tsimilar;
  919: 	    $sname=$tname;
  920: 	    $sdom=$tdom;
  921: 	    $scrsid=$tcrsid;
  922: 	    $sessay=$old_essays{$symb}{$tkey};
  923: 	}
  924:     }
  925:     if ($limit>0.6) {
  926:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  927:     } else {
  928:        return ('','','','',0);
  929:     }
  930: }
  931: 
  932: #-------------------------------------------------------------------
  933: 
  934: #------------------------------------ Receipt Verification Routines
  935: #
  936: 
  937: sub initialverifyreceipt {
  938:    my ($request,$symb) = @_;
  939:    &commonJSfunctions($request);
  940:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  941:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  942:         '-<input type="text" name="receipt" size="4" />'.
  943:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  944:         '<input type="hidden" name="command" value="verify" />'.
  945:         "</form>\n";
  946: }
  947: 
  948: #--- Check whether a receipt number is valid.---
  949: sub verifyreceipt {
  950:     my ($request,$symb) = @_;
  951: 
  952:     my $courseid = $env{'request.course.id'};
  953:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  954: 	$env{'form.receipt'};
  955:     $receipt     =~ s/[^\-\d]//g;
  956: 
  957:     my $title =
  958: 	'<h3><span class="LC_info">'.
  959: 	&mt('Verifying Receipt Number [_1]',$receipt).
  960: 	'</span></h3>'."\n";
  961: 
  962:     my ($string,$contents,$matches) = ('','',0);
  963:     my (undef,undef,$fullname) = &getclasslist('all','0');
  964:     
  965:     my $receiptparts=0;
  966:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  967: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  968:     my $parts=['0'];
  969:     if ($receiptparts) {
  970:         my $res_error; 
  971:         ($parts)=&response_type($symb,\$res_error);
  972:         if ($res_error) {
  973:             return &navmap_errormsg();
  974:         } 
  975:     }
  976:     
  977:     my $header = 
  978: 	&Apache::loncommon::start_data_table().
  979: 	&Apache::loncommon::start_data_table_header_row().
  980: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  981: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  982: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  983:     if ($receiptparts) {
  984: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  985:     }
  986:     $header.=
  987: 	&Apache::loncommon::end_data_table_header_row();
  988: 
  989:     foreach (sort 
  990: 	     {
  991: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  992: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  993: 		 }
  994: 		 return $a cmp $b;
  995: 	     } (keys(%$fullname))) {
  996: 	my ($uname,$udom)=split(/\:/);
  997: 	foreach my $part (@$parts) {
  998: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  999: 		$contents.=
 1000: 		    &Apache::loncommon::start_data_table_row().
 1001: 		    '<td>&nbsp;'."\n".
 1002: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1003: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1004: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1005: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1006: 		if ($receiptparts) {
 1007: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1008: 		}
 1009: 		$contents.= 
 1010: 		    &Apache::loncommon::end_data_table_row()."\n";
 1011: 		
 1012: 		$matches++;
 1013: 	    }
 1014: 	}
 1015:     }
 1016:     if ($matches == 0) {
 1017:         $string = $title
 1018:                  .'<p class="LC_warning">'
 1019:                  .&mt('No match found for the above receipt number.')
 1020:                  .'</p>';
 1021:     } else {
 1022: 	$string = &jscriptNform($symb).$title.
 1023: 	    '<p>'.
 1024: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1025: 	    '</p>'.
 1026: 	    $header.
 1027: 	    $contents.
 1028: 	    &Apache::loncommon::end_data_table()."\n";
 1029:     }
 1030:     return $string;
 1031: }
 1032: 
 1033: #--- This is called by a number of programs.
 1034: #--- Called from the Grading Menu - View/Grade an individual student
 1035: #--- Also called directly when one clicks on the subm button 
 1036: #    on the problem page.
 1037: sub listStudents {
 1038:     my ($request,$symb,$submitonly,$divforres) = @_;
 1039: 
 1040:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1041:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1042:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1043:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1044:     unless ($submitonly) {
 1045:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1046:     }
 1047: 
 1048:     my $result='';
 1049:     my $res_error;
 1050:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1051: 
 1052:     my $table;
 1053:     if (ref($partlist) eq 'ARRAY') {
 1054:         if (scalar(@$partlist) > 1 ) {
 1055:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1056:         } elsif ($divforres) {
 1057:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1058:         } else {
 1059:             $table = '<br clear="all" />';
 1060:         }
 1061:     }
 1062: 
 1063:     my %js_lt = &Apache::lonlocal::texthash (
 1064: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1065: 		'single'   => 'Please select the student before clicking on the Next button.',
 1066: 	     );
 1067:     &js_escape(\%js_lt);
 1068:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1069:     function checkSelect(checkBox) {
 1070: 	var ctr=0;
 1071: 	var sense="";
 1072: 	if (checkBox.length > 1) {
 1073: 	    for (var i=0; i<checkBox.length; i++) {
 1074: 		if (checkBox[i].checked) {
 1075: 		    ctr++;
 1076: 		}
 1077: 	    }
 1078: 	    sense = '$js_lt{'multiple'}';
 1079: 	} else {
 1080: 	    if (checkBox.checked) {
 1081: 		ctr = 1;
 1082: 	    }
 1083: 	    sense = '$js_lt{'single'}';
 1084: 	}
 1085: 	if (ctr == 0) {
 1086: 	    alert(sense);
 1087: 	    return false;
 1088: 	}
 1089: 	document.gradesub.submit();
 1090:     }
 1091: 
 1092:     function reLoadList(formname) {
 1093: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1094: 	formname.command.value = 'submission';
 1095: 	formname.submit();
 1096:     }
 1097: LISTJAVASCRIPT
 1098: 
 1099:     &commonJSfunctions($request);
 1100:     $request->print($result);
 1101: 
 1102:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1103: 	"\n".$table;
 1104: 
 1105:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1106:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1107:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1108:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1109:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1110:                   .&Apache::lonhtmlcommon::row_closure();
 1111:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1112:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1113:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1114:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1115:                   .&Apache::lonhtmlcommon::row_closure();
 1116: 
 1117:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1118:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1119:     $env{'form.Status'} = $saveStatus;
 1120:     my %optiontext = &Apache::lonlocal::texthash (
 1121:                           lastonly => 'last submission',
 1122:                           last     => 'last submission with details',
 1123:                           datesub  => 'all submissions',
 1124:                           all      => 'all submissions with details',
 1125:                       );
 1126:     my $submission_options =
 1127:         '<span class="LC_nobreak">'.
 1128:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1129:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1130:         '<span class="LC_nobreak">'.
 1131:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1132:         $optiontext{'last'}.' </label></span>'."\n".
 1133:         '<span class="LC_nobreak">'.
 1134:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1135:         $optiontext{'datesub'}.'</label></span>'."\n".
 1136:         '<span class="LC_nobreak">'.
 1137:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1138:         $optiontext{'all'}.'</label></span>';
 1139:     my ($compmsg,$nocompmsg);
 1140:     $nocompmsg = ' checked="checked"';
 1141:     if ($numessay) {
 1142:         $compmsg = $nocompmsg;
 1143:         $nocompmsg = '';
 1144:     }
 1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
 1146:                   .$submission_options;
 1147: # Check if any gradable
 1148:     my $showmore;
 1149:     if ($perm{'mgr'}) {
 1150:         my @sections;
 1151:         if ($env{'request.course.sec'} ne '') {
 1152:             @sections = ($env{'request.course.sec'});
 1153:         } else {
 1154:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1155:         }
 1156:         if (grep(/^all$/,@sections)) {
 1157:             $showmore = 1;
 1158:         } else {
 1159:             foreach my $sec (@sections) {
 1160:                 if (&canmodify($sec)) {
 1161:                     $showmore = 1;
 1162:                     last;
 1163:                 }
 1164:             }
 1165:         }
 1166:     }
 1167: 
 1168:     if ($showmore) {
 1169:         $gradeTable .=
 1170:                    &Apache::lonhtmlcommon::row_closure()
 1171:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1172:                   .'<span class="LC_nobreak">'
 1173:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1174:                   .&mt('No').('&nbsp;'x2).'</label>'
 1175:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1176:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1177:                   .&Apache::lonhtmlcommon::row_closure();
 1178: 
 1179:         $gradeTable .= 
 1180:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1181:                   .'<select name="increment">'
 1182:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1183:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1184:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1185:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1186:                   .'</select>';
 1187:     }
 1188:     $gradeTable .= 
 1189:         &build_section_inputs().
 1190: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1191: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1192: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1193:     if (exists($env{'form.Status'})) {
 1194: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1195:     } else {
 1196:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1197:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1198:                       .&Apache::lonhtmlcommon::StatusOptions(
 1199:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1200:     }
 1201:     if ($numessay) {
 1202:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1203:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1204:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1205:     }
 1206:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1207:                   .&Apache::lonhtmlcommon::end_pick_box();
 1208: 
 1209:     $gradeTable .= '<p>'
 1210:                   .&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"
 1211:                   .'<input type="hidden" name="command" value="processGroup" />'
 1212:                   .'</p>';
 1213: 
 1214: # checkall buttons
 1215:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1216:     $gradeTable.='<input type="button" '."\n".
 1217:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1218:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1219:     $gradeTable.=&check_buttons();
 1220:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1221:     $gradeTable.= &Apache::loncommon::start_data_table().
 1222: 	&Apache::loncommon::start_data_table_header_row();
 1223:     my $loop = 0;
 1224:     while ($loop < 2) {
 1225: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1226: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1227: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1228: 	    foreach my $part (sort(@$partlist)) {
 1229: 		my $display_part=
 1230: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1231: 		$gradeTable.=
 1232: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1233: 	    }
 1234: 	} elsif ($submitonly eq 'queued') {
 1235: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1236: 	}
 1237: 	$loop++;
 1238: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1239:     }
 1240:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1241: 
 1242:     my $ctr = 0;
 1243:     foreach my $student (sort 
 1244: 			 {
 1245: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1246: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1247: 			     }
 1248: 			     return $a cmp $b;
 1249: 			 }
 1250: 			 (keys(%$fullname))) {
 1251: 	my ($uname,$udom) = split(/:/,$student);
 1252: 
 1253: 	my %status = ();
 1254: 
 1255: 	if ($submitonly eq 'queued') {
 1256: 	    my %queue_status = 
 1257: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1258: 							$udom,$uname);
 1259: 	    next if (!defined($queue_status{'gradingqueue'}));
 1260: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1261: 	}
 1262: 
 1263: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1264: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1265: 	    my $submitted = 0;
 1266: 	    my $graded = 0;
 1267: 	    my $incorrect = 0;
 1268: 	    foreach (keys(%status)) {
 1269: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1270: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1271: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1272: 		
 1273: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1274: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1275: 		    $submitted = 0;
 1276: 		    my ($part)=split(/\./,$partid);
 1277: 		    $gradeTable.='<input type="hidden" name="'.
 1278: 			$student.':'.$part.':submitted_by" value="'.
 1279: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1280: 		}
 1281: 	    }
 1282: 	    
 1283: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1284: 				     $submitonly eq 'incorrect' ||
 1285: 				     $submitonly eq 'graded'));
 1286: 	    next if (!$graded && ($submitonly eq 'graded'));
 1287: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1288: 	}
 1289: 
 1290: 	$ctr++;
 1291: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1292:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1293: 	if ( $perm{'vgr'} eq 'F' ) {
 1294: 	    if ($ctr%2 ==1) {
 1295: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1296: 	    }
 1297: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1298:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1299:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1300: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1301: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1302: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1303: 
 1304: 	    if ($submitonly ne 'all') {
 1305: 		foreach (sort(keys(%status))) {
 1306: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1307: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1308: 		}
 1309: 	    }
 1310: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1311: 	    if ($ctr%2 ==0) {
 1312: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1313: 	    }
 1314: 	}
 1315:     }
 1316:     if ($ctr%2 ==1) {
 1317: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1318: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1319: 		foreach (@$partlist) {
 1320: 		    $gradeTable.='<td>&nbsp;</td>';
 1321: 		}
 1322: 	    } elsif ($submitonly eq 'queued') {
 1323: 		$gradeTable.='<td>&nbsp;</td>';
 1324: 	    }
 1325: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1326:     }
 1327: 
 1328:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1329:         '<input type="button" '.
 1330:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1331:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1332:     if ($ctr == 0) {
 1333: 	my $num_students=(scalar(keys(%$fullname)));
 1334: 	if ($num_students eq 0) {
 1335: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1336: 	} else {
 1337: 	    my $submissions='submissions';
 1338: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1339: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1340: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1341: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1342: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1343: 		    $num_students).
 1344: 		'</span><br />';
 1345: 	}
 1346:     } elsif ($ctr == 1) {
 1347: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1348:     }
 1349:     $request->print($gradeTable);
 1350:     return '';
 1351: }
 1352: 
 1353: #---- Called from the listStudents routine
 1354: 
 1355: sub check_script {
 1356:     my ($form,$type) = @_;
 1357:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1358:     function checkall() {
 1359:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1360:             ele = document.forms.'.$form.'.elements[i];
 1361:             if (ele.name == "'.$type.'") {
 1362:             document.forms.'.$form.'.elements[i].checked=true;
 1363:                                        }
 1364:         }
 1365:     }
 1366: 
 1367:     function checksec() {
 1368:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1369:             ele = document.forms.'.$form.'.elements[i];
 1370:            string = document.forms.'.$form.'.chksec.value;
 1371:            if
 1372:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1373:               document.forms.'.$form.'.elements[i].checked=true;
 1374:             }
 1375:         }
 1376:     }
 1377: 
 1378: 
 1379:     function uncheckall() {
 1380:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1381:             ele = document.forms.'.$form.'.elements[i];
 1382:             if (ele.name == "'.$type.'") {
 1383:             document.forms.'.$form.'.elements[i].checked=false;
 1384:                                        }
 1385:         }
 1386:     }
 1387: 
 1388: '."\n");
 1389:     return $chkallscript;
 1390: }
 1391: 
 1392: sub check_buttons {
 1393:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1394:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1395:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1396:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1397:     return $buttons;
 1398: }
 1399: 
 1400: #     Displays the submissions for one student or a group of students
 1401: sub processGroup {
 1402:     my ($request,$symb) = @_;
 1403:     my $ctr        = 0;
 1404:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1405:     my $total      = scalar(@stuchecked)-1;
 1406: 
 1407:     foreach my $student (@stuchecked) {
 1408: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1409: 	$env{'form.student'}        = $uname;
 1410: 	$env{'form.userdom'}        = $udom;
 1411: 	$env{'form.fullname'}       = $fullname;
 1412: 	&submission($request,$ctr,$total,$symb);
 1413: 	$ctr++;
 1414:     }
 1415:     return '';
 1416: }
 1417: 
 1418: #------------------------------------------------------------------------------------
 1419: #
 1420: #-------------------------- Next few routines handles grading by student, essentially
 1421: #                           handles essay response type problem/part
 1422: #
 1423: #--- Javascript to handle the submission page functionality ---
 1424: sub sub_page_js {
 1425:     my $request = shift;
 1426:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1427:     &js_escape(\$alertmsg);
 1428:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1429:     function updateRadio(formname,id,weight) {
 1430: 	var gradeBox = formname["GD_BOX"+id];
 1431: 	var radioButton = formname["RADVAL"+id];
 1432: 	var oldpts = formname["oldpts"+id].value;
 1433: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1434: 	gradeBox.value = pts;
 1435: 	var resetbox = false;
 1436: 	if (isNaN(pts) || pts < 0) {
 1437: 	    alert("$alertmsg"+pts);
 1438: 	    for (var i=0; i<radioButton.length; i++) {
 1439: 		if (radioButton[i].checked) {
 1440: 		    gradeBox.value = i;
 1441: 		    resetbox = true;
 1442: 		}
 1443: 	    }
 1444: 	    if (!resetbox) {
 1445: 		formtextbox.value = "";
 1446: 	    }
 1447: 	    return;
 1448: 	}
 1449: 
 1450: 	if (pts > weight) {
 1451: 	    var resp = confirm("You entered a value ("+pts+
 1452: 			       ") greater than the weight for the part. Accept?");
 1453: 	    if (resp == false) {
 1454: 		gradeBox.value = oldpts;
 1455: 		return;
 1456: 	    }
 1457: 	}
 1458: 
 1459: 	for (var i=0; i<radioButton.length; i++) {
 1460: 	    radioButton[i].checked=false;
 1461: 	    if (pts == i && pts != "") {
 1462: 		radioButton[i].checked=true;
 1463: 	    }
 1464: 	}
 1465: 	updateSelect(formname,id);
 1466: 	formname["stores"+id].value = "0";
 1467:     }
 1468: 
 1469:     function writeBox(formname,id,pts) {
 1470: 	var gradeBox = formname["GD_BOX"+id];
 1471: 	if (checkSolved(formname,id) == 'update') {
 1472: 	    gradeBox.value = pts;
 1473: 	} else {
 1474: 	    var oldpts = formname["oldpts"+id].value;
 1475: 	    gradeBox.value = oldpts;
 1476: 	    var radioButton = formname["RADVAL"+id];
 1477: 	    for (var i=0; i<radioButton.length; i++) {
 1478: 		radioButton[i].checked=false;
 1479: 		if (i == oldpts) {
 1480: 		    radioButton[i].checked=true;
 1481: 		}
 1482: 	    }
 1483: 	}
 1484: 	formname["stores"+id].value = "0";
 1485: 	updateSelect(formname,id);
 1486: 	return;
 1487:     }
 1488: 
 1489:     function clearRadBox(formname,id) {
 1490: 	if (checkSolved(formname,id) == 'noupdate') {
 1491: 	    updateSelect(formname,id);
 1492: 	    return;
 1493: 	}
 1494: 	gradeSelect = formname["GD_SEL"+id];
 1495: 	for (var i=0; i<gradeSelect.length; i++) {
 1496: 	    if (gradeSelect[i].selected) {
 1497: 		var selectx=i;
 1498: 	    }
 1499: 	}
 1500: 	var stores = formname["stores"+id];
 1501: 	if (selectx == stores.value) { return };
 1502: 	var gradeBox = formname["GD_BOX"+id];
 1503: 	gradeBox.value = "";
 1504: 	var radioButton = formname["RADVAL"+id];
 1505: 	for (var i=0; i<radioButton.length; i++) {
 1506: 	    radioButton[i].checked=false;
 1507: 	}
 1508: 	stores.value = selectx;
 1509:     }
 1510: 
 1511:     function checkSolved(formname,id) {
 1512: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1513: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1514: 	    if (!reply) {return "noupdate";}
 1515: 	    formname.overRideScore.value = 'yes';
 1516: 	}
 1517: 	return "update";
 1518:     }
 1519: 
 1520:     function updateSelect(formname,id) {
 1521: 	formname["GD_SEL"+id][0].selected = true;
 1522: 	return;
 1523:     }
 1524: 
 1525: //=========== Check that a point is assigned for all the parts  ============
 1526:     function checksubmit(formname,val,total,parttot) {
 1527: 	formname.gradeOpt.value = val;
 1528: 	if (val == "Save & Next") {
 1529: 	    for (i=0;i<=total;i++) {
 1530: 		for (j=0;j<parttot;j++) {
 1531: 		    var partid = formname["partid"+i+"_"+j].value;
 1532: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1533: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1534: 			if (points == "") {
 1535: 			    var name = formname["name"+i].value;
 1536: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1537: 			    var resp = confirm("You did not assign a score for "+studentID+
 1538: 					       ", part "+partid+". Continue?");
 1539: 			    if (resp == false) {
 1540: 				formname["GD_BOX"+i+"_"+partid].focus();
 1541: 				return false;
 1542: 			    }
 1543: 			}
 1544: 		    }
 1545: 		}
 1546: 	    }
 1547: 	}
 1548: 	formname.submit();
 1549:     }
 1550: 
 1551: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1552:     function checkSubmitPage(formname,total) {
 1553: 	noscore = new Array(100);
 1554: 	var ptr = 0;
 1555: 	for (i=1;i<total;i++) {
 1556: 	    var partid = formname["q_"+i].value;
 1557: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1558: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1559: 		var status = formname["solved"+i+"_"+partid].value;
 1560: 		if (points == "" && status != "correct_by_student") {
 1561: 		    noscore[ptr] = i;
 1562: 		    ptr++;
 1563: 		}
 1564: 	    }
 1565: 	}
 1566: 	if (ptr != 0) {
 1567: 	    var sense = ptr == 1 ? ": " : "s: ";
 1568: 	    var prolist = "";
 1569: 	    if (ptr == 1) {
 1570: 		prolist = noscore[0];
 1571: 	    } else {
 1572: 		var i = 0;
 1573: 		while (i < ptr-1) {
 1574: 		    prolist += noscore[i]+", ";
 1575: 		    i++;
 1576: 		}
 1577: 		prolist += "and "+noscore[i];
 1578: 	    }
 1579: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1580: 	    if (resp == false) {
 1581: 		return false;
 1582: 	    }
 1583: 	}
 1584: 
 1585: 	formname.submit();
 1586:     }
 1587: SUBJAVASCRIPT
 1588: }
 1589: 
 1590: #--- javascript for grading message center
 1591: sub sub_grademessage_js {
 1592:     my $request = shift;
 1593:     my $iconpath = $request->dir_config('lonIconsURL');
 1594:     &commonJSfunctions($request);
 1595: 
 1596:     my $inner_js_msg_central= (<<INNERJS);
 1597: <script type="text/javascript">
 1598:     function checkInput() {
 1599:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1600:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1601:       var usrctr = document.msgcenter.usrctr.value;
 1602:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1603:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1604: 
 1605:       var msgchk = "";
 1606:       if (document.msgcenter.subchk.checked) {
 1607:          msgchk = "msgsub,";
 1608:       }
 1609:       var includemsg = 0;
 1610:       for (var i=1; i<=nmsg; i++) {
 1611:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1612:           var frmmsg = document.msgcenter["msg"+i];
 1613:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1614:           var showflg = opener.document.SCORE["shownOnce"+i];
 1615:           showflg.value = "1";
 1616:           var chkbox = document.msgcenter["msgn"+i];
 1617:           if (chkbox.checked) {
 1618:              msgchk += "savemsg"+i+",";
 1619:              includemsg = 1;
 1620:           }
 1621:       }
 1622:       if (document.msgcenter.newmsgchk.checked) {
 1623:          msgchk += "newmsg"+usrctr;
 1624:          includemsg = 1;
 1625:       }
 1626:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1627:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1628:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1629:       includemsg.value = msgchk;
 1630: 
 1631:       self.close()
 1632: 
 1633:     }
 1634: </script>
 1635: INNERJS
 1636: 
 1637:     my $start_page_msg_central =
 1638:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1639: 				       {'js_ready'  => 1,
 1640: 					'only_body' => 1,
 1641: 					'bgcolor'   =>'#FFFFFF',});
 1642:     my $end_page_msg_central =
 1643: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1644: 
 1645: 
 1646:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1647:     $docopen=~s/^document\.//;
 1648: 
 1649:     my %html_js_lt = &Apache::lonlocal::texthash(
 1650:                 comp => 'Compose Message for: ',
 1651:                 incl => 'Include',
 1652:                 type => 'Type',
 1653:                 subj => 'Subject',
 1654:                 mesa => 'Message',
 1655:                 new  => 'New',
 1656:                 save => 'Save',
 1657:                 canc => 'Cancel',
 1658:              );
 1659:     &html_escape(\%html_js_lt);
 1660:     &js_escape(\%html_js_lt);
 1661:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1662: 
 1663: //===================== Script to view submitted by ==================
 1664:   function viewSubmitter(submitter) {
 1665:     document.SCORE.refresh.value = "on";
 1666:     document.SCORE.NCT.value = "1";
 1667:     document.SCORE.unamedom0.value = submitter;
 1668:     document.SCORE.submit();
 1669:     return;
 1670:   }
 1671: 
 1672: //====================== Script for composing message ==============
 1673:    // preload images
 1674:    img1 = new Image();
 1675:    img1.src = "$iconpath/mailbkgrd.gif";
 1676:    img2 = new Image();
 1677:    img2.src = "$iconpath/mailto.gif";
 1678: 
 1679:   function msgCenter(msgform,usrctr,fullname) {
 1680:     var Nmsg  = msgform.savemsgN.value;
 1681:     savedMsgHeader(Nmsg,usrctr,fullname);
 1682:     var subject = msgform.msgsub.value;
 1683:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1684:     re = /msgsub/;
 1685:     var shwsel = "";
 1686:     if (re.test(msgchk)) { shwsel = "checked" }
 1687:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1688:     displaySubject(checkEntities(subject),shwsel);
 1689:     for (var i=1; i<=Nmsg; i++) {
 1690: 	var testmsg = "savemsg"+i+",";
 1691: 	re = new RegExp(testmsg,"g");
 1692: 	shwsel = "";
 1693: 	if (re.test(msgchk)) { shwsel = "checked" }
 1694: 	var message = document.SCORE["savemsg"+i].value;
 1695: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1696: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1697: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1698:     }
 1699:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1700:     shwsel = "";
 1701:     re = /newmsg/;
 1702:     if (re.test(msgchk)) { shwsel = "checked" }
 1703:     newMsg(newmsg,shwsel);
 1704:     msgTail(); 
 1705:     return;
 1706:   }
 1707: 
 1708:   function checkEntities(strx) {
 1709:     if (strx.length == 0) return strx;
 1710:     var orgStr = ["&", "<", ">", '"']; 
 1711:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1712:     var counter = 0;
 1713:     while (counter < 4) {
 1714: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1715: 	counter++;
 1716:     }
 1717:     return strx;
 1718:   }
 1719: 
 1720:   function strReplace(strx, orgStr, newStr) {
 1721:     return strx.split(orgStr).join(newStr);
 1722:   }
 1723: 
 1724:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1725:     var height = 70*Nmsg+250;
 1726:     if (height > 600) {
 1727: 	height = 600;
 1728:     }
 1729:     var xpos = (screen.width-600)/2;
 1730:     xpos = (xpos < 0) ? '0' : xpos;
 1731:     var ypos = (screen.height-height)/2-30;
 1732:     ypos = (ypos < 0) ? '0' : ypos;
 1733: 
 1734:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1735:     pWin.focus();
 1736:     pDoc = pWin.document;
 1737:     pDoc.$docopen;
 1738:     pDoc.write('$start_page_msg_central');
 1739: 
 1740:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1741:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1742:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1743: 
 1744:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1745:     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>");
 1746: }
 1747:     function displaySubject(msg,shwsel) {
 1748:     pDoc = pWin.document;
 1749:     pDoc.write("<tr>");
 1750:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1751:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1752:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1753: }
 1754: 
 1755:   function displaySavedMsg(ctr,msg,shwsel) {
 1756:     pDoc = pWin.document;
 1757:     pDoc.write("<tr>");
 1758:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1759:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1760:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1761: }
 1762: 
 1763:   function newMsg(newmsg,shwsel) {
 1764:     pDoc = pWin.document;
 1765:     pDoc.write("<tr>");
 1766:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1767:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1768:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1769: }
 1770: 
 1771:   function msgTail() {
 1772:     pDoc = pWin.document;
 1773:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1774:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1775:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1776:     pDoc.write("<\\/form>");
 1777:     pDoc.write('$end_page_msg_central');
 1778:     pDoc.close();
 1779: }
 1780: 
 1781: SUBJAVASCRIPT
 1782: }
 1783: 
 1784: #--- javascript for essay type problem --
 1785: sub sub_page_kw_js {
 1786:     my $request = shift;
 1787: 
 1788:     unless ($env{'form.compmsg'}) {
 1789:         &commonJSfunctions($request);
 1790:     }
 1791: 
 1792:     my $inner_js_highlight_central= (<<INNERJS);
 1793: <script type="text/javascript">
 1794:     function updateChoice(flag) {
 1795:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1796:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1797:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1798:       opener.document.SCORE.refresh.value = "on";
 1799:       if (opener.document.SCORE.keywords.value!=""){
 1800:          opener.document.SCORE.submit();
 1801:       }
 1802:       self.close()
 1803:     }
 1804: </script>
 1805: INNERJS
 1806: 
 1807:     my $start_page_highlight_central =
 1808:         &Apache::loncommon::start_page('Highlight Central',
 1809:                                        $inner_js_highlight_central,
 1810:                                        {'js_ready'  => 1,
 1811:                                         'only_body' => 1,
 1812:                                         'bgcolor'   =>'#FFFFFF',});
 1813:     my $end_page_highlight_central =
 1814:         &Apache::loncommon::end_page({'js_ready' => 1});
 1815: 
 1816:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1817:     $docopen=~s/^document\.//;
 1818: 
 1819:     my %js_lt = &Apache::lonlocal::texthash(
 1820:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1821:                 plse => 'Please select a word or group of words from document and then click this link.',
 1822:                 adds => 'Add selection to keyword list? Edit if desired.',
 1823:                 col1 => 'red',
 1824:                 col2 => 'green',
 1825:                 col3 => 'blue',
 1826:                 siz1 => 'normal',
 1827:                 siz2 => '+1',
 1828:                 siz3 => '+2',
 1829:                 sty1 => 'normal',
 1830:                 sty2 => 'italic',
 1831:                 sty3 => 'bold',
 1832:              );
 1833:     my %html_js_lt = &Apache::lonlocal::texthash(
 1834:                 save => 'Save',
 1835:                 canc => 'Cancel',
 1836:                 kehi => 'Keyword Highlight Options',
 1837:                 txtc => 'Text Color',
 1838:                 font => 'Font Size',
 1839:                 fnst => 'Font Style',
 1840:              );
 1841:     &js_escape(\%js_lt);
 1842:     &html_escape(\%html_js_lt);
 1843:     &js_escape(\%html_js_lt);
 1844:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1845: 
 1846: //===================== Show list of keywords ====================
 1847:   function keywords(formname) {
 1848:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1849:     if (nret==null) return;
 1850:     formname.keywords.value = nret;
 1851: 
 1852:     if (formname.keywords.value != "") {
 1853:         formname.refresh.value = "on";
 1854:         formname.submit();
 1855:     }
 1856:     return;
 1857:   }
 1858: 
 1859: //===================== Script to add keyword(s) ==================
 1860:   function getSel() {
 1861:     if (document.getSelection) txt = document.getSelection();
 1862:     else if (document.selection) txt = document.selection.createRange().text;
 1863:     else return;
 1864:     if (typeof(txt) != 'string') {
 1865:         txt = String(txt);
 1866:     }
 1867:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1868:     if (cleantxt=="") {
 1869:         alert("$js_lt{'plse'}");
 1870:         return;
 1871:     }
 1872:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1873:     if (nret==null) return;
 1874:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1875:     if (document.SCORE.keywords.value != "") {
 1876:         document.SCORE.refresh.value = "on";
 1877:         document.SCORE.submit();
 1878:     }
 1879:     return;
 1880:   }
 1881: 
 1882: //====================== Script for keyword highlight options ==============
 1883:   function kwhighlight() {
 1884:     var kwclr    = document.SCORE.kwclr.value;
 1885:     var kwsize   = document.SCORE.kwsize.value;
 1886:     var kwstyle  = document.SCORE.kwstyle.value;
 1887:     var redsel = "";
 1888:     var grnsel = "";
 1889:     var blusel = "";
 1890:     var txtcol1 = "$js_lt{'col1'}";
 1891:     var txtcol2 = "$js_lt{'col2'}";
 1892:     var txtcol3 = "$js_lt{'col3'}";
 1893:     var txtsiz1 = "$js_lt{'siz1'}";
 1894:     var txtsiz2 = "$js_lt{'siz2'}";
 1895:     var txtsiz3 = "$js_lt{'siz3'}";
 1896:     var txtsty1 = "$js_lt{'sty1'}";
 1897:     var txtsty2 = "$js_lt{'sty2'}";
 1898:     var txtsty3 = "$js_lt{'sty3'}";
 1899:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1900:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1901:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1902:     var sznsel = "";
 1903:     var sz1sel = "";
 1904:     var sz2sel = "";
 1905:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1906:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1907:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1908:     var synsel = "";
 1909:     var syisel = "";
 1910:     var sybsel = "";
 1911:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1912:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1913:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1914:     highlightCentral();
 1915:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1916:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1917:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1918:     highlightend();
 1919:     return;
 1920:   }
 1921: 
 1922:   function highlightCentral() {
 1923: //    if (window.hwdWin) window.hwdWin.close();
 1924:     var xpos = (screen.width-400)/2;
 1925:     xpos = (xpos < 0) ? '0' : xpos;
 1926:     var ypos = (screen.height-330)/2-30;
 1927:     ypos = (ypos < 0) ? '0' : ypos;
 1928: 
 1929:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1930:     hwdWin.focus();
 1931:     var hDoc = hwdWin.document;
 1932:     hDoc.$docopen;
 1933:     hDoc.write('$start_page_highlight_central');
 1934:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1935:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1936: 
 1937:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1938:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1939:   }
 1940: 
 1941:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1942:     var hDoc = hwdWin.document;
 1943:     hDoc.write("<tr>");
 1944:     hDoc.write("<td align=\\"left\\">");
 1945:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1946:     hDoc.write("<td align=\\"left\\">");
 1947:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1948:     hDoc.write("<td align=\\"left\\">");
 1949:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1950:     hDoc.write("<\\/tr>");
 1951:   }
 1952: 
 1953:   function highlightend() { 
 1954:     var hDoc = hwdWin.document;
 1955:     hDoc.write("<\\/table><br \\/>");
 1956:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1957:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1958:     hDoc.write("<\\/form>");
 1959:     hDoc.write('$end_page_highlight_central');
 1960:     hDoc.close();
 1961:   }
 1962: 
 1963: SUBJAVASCRIPT
 1964: }
 1965: 
 1966: sub get_increment {
 1967:     my $increment = $env{'form.increment'};
 1968:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1969:         $increment != .1) {
 1970:         $increment = 1;
 1971:     }
 1972:     return $increment;
 1973: }
 1974: 
 1975: sub gradeBox_start {
 1976:     return (
 1977:         &Apache::loncommon::start_data_table()
 1978:        .&Apache::loncommon::start_data_table_header_row()
 1979:        .'<th>'.&mt('Part').'</th>'
 1980:        .'<th>'.&mt('Points').'</th>'
 1981:        .'<th>&nbsp;</th>'
 1982:        .'<th>'.&mt('Assign Grade').'</th>'
 1983:        .'<th>'.&mt('Weight').'</th>'
 1984:        .'<th>'.&mt('Grade Status').'</th>'
 1985:        .&Apache::loncommon::end_data_table_header_row()
 1986:     );
 1987: }
 1988: 
 1989: sub gradeBox_end {
 1990:     return (
 1991:         &Apache::loncommon::end_data_table()
 1992:     );
 1993: }
 1994: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1995: sub gradeBox {
 1996:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1997:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1998: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1999:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2000:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2001:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2002:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2003:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2004: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2005:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2006:     my $display_part= &get_display_part($partid,$symb);
 2007:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2008: 				       [$partid]);
 2009:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2010:     if ($last_resets{$partid}) {
 2011:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2012:     }
 2013:     my $result=&Apache::loncommon::start_data_table_row();
 2014:     my $ctr = 0;
 2015:     my $thisweight = 0;
 2016:     my $increment = &get_increment();
 2017: 
 2018:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2019:     while ($thisweight<=$wgt) {
 2020: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2021:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2022: 	    $thisweight.')" value="'.$thisweight.'" '.
 2023: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2024: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2025:         $thisweight += $increment;
 2026: 	$ctr++;
 2027:     }
 2028:     $radio.='</tr></table>';
 2029: 
 2030:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2031: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2032: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2033: 	$wgt.')" /></td>'."\n";
 2034:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2035: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2036: 	' </td>'."\n";
 2037:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2038: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2039:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2040: 	$line.='<option></option>'.
 2041: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2042:     } else {
 2043: 	$line.='<option selected="selected"></option>'.
 2044: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2045:     }
 2046:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2047: 
 2048: 
 2049:     $result .= 
 2050: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2051:     $result.=&Apache::loncommon::end_data_table_row();
 2052:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2053:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2054: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2055: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2056: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2057:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2058:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2059:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2060:         $aggtries.'" />'."\n";
 2061:     my $res_error;
 2062:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2063:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2064:     if ($res_error) {
 2065:         return &navmap_errormsg();
 2066:     }
 2067:     return $result;
 2068: }
 2069: 
 2070: sub handback_box {
 2071:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2072:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2073:     return unless ($numessay);
 2074:     my (@respids);
 2075:     my @part_response_id = &flatten_responseType($responseType);
 2076:     foreach my $part_response_id (@part_response_id) {
 2077:     	my ($part,$resp) = @{ $part_response_id };
 2078:         if ($part eq $partid) {
 2079:             push(@respids,$resp);
 2080:         }
 2081:     }
 2082:     my $result;
 2083:     foreach my $respid (@respids) {
 2084: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2085: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2086: 	next if (!@$files);
 2087: 	my $file_counter = 0;
 2088: 	foreach my $file (@$files) {
 2089: 	    if ($file =~ /\/portfolio\//) {
 2090:                 $file_counter++;
 2091:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2092:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 2093:     	        $file_disp = "$name.$ext";
 2094:     	        $file = $file_path.$file_disp;
 2095:     	        $result.=&mt('Return commented version of [_1] to student.',
 2096:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2097:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2098:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2099: 	    }
 2100: 	}
 2101:         if ($file_counter) {
 2102:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2103:                        '<span class="LC_info">'.
 2104:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2105:         }
 2106:     }
 2107:     return $result;    
 2108: }
 2109: 
 2110: sub show_problem {
 2111:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2112:     my $rendered;
 2113:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2114:     &Apache::lonxml::remember_problem_counter();
 2115:     if ($mode eq 'both' or $mode eq 'text') {
 2116: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2117: 						       $env{'request.course.id'},
 2118: 						       undef,\%form);
 2119:     }
 2120:     if ($removeform) {
 2121: 	$rendered=~s|<form(.*?)>||g;
 2122: 	$rendered=~s|</form>||g;
 2123: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2124:     }
 2125:     my $companswer;
 2126:     if ($mode eq 'both' or $mode eq 'answer') {
 2127: 	&Apache::lonxml::restore_problem_counter();
 2128: 	$companswer=
 2129: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2130: 						    $env{'request.course.id'},
 2131: 						    %form);
 2132:     }
 2133:     if ($removeform) {
 2134: 	$companswer=~s|<form(.*?)>||g;
 2135: 	$companswer=~s|</form>||g;
 2136: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2137:     }
 2138:     my $renderheading = &mt('View of the problem');
 2139:     my $answerheading = &mt('Correct answer');
 2140:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2141:         my $stu_fullname = $env{'form.fullname'};
 2142:         if ($stu_fullname eq '') {
 2143:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2144:         }
 2145:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2146:         if ($forwhom ne '') {
 2147:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2148:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2149:         }
 2150:     }
 2151:     $rendered=
 2152:         '<div class="LC_Box">'
 2153:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2154:        .$rendered
 2155:        .'</div>';
 2156:     $companswer=
 2157:         '<div class="LC_Box">'
 2158:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2159:        .$companswer
 2160:        .'</div>';
 2161:     my $result;
 2162:     if ($mode eq 'both') {
 2163:         $result=$rendered.$companswer;
 2164:     } elsif ($mode eq 'text') {
 2165:         $result=$rendered;
 2166:     } elsif ($mode eq 'answer') {
 2167:         $result=$companswer;
 2168:     }
 2169:     return $result;
 2170: }
 2171: 
 2172: sub files_exist {
 2173:     my ($r, $symb) = @_;
 2174:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2175:     foreach my $student (@students) {
 2176:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2177:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2178: 					      $udom,$uname);
 2179:         my ($string,$timestamp)= &get_last_submission(\%record);
 2180:         foreach my $submission (@$string) {
 2181:             my ($partid,$respid) =
 2182: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2183:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2184: 					   \%record);
 2185:             return 1 if (@$files);
 2186:         }
 2187:     }
 2188:     return 0;
 2189: }
 2190: 
 2191: sub download_all_link {
 2192:     my ($r,$symb) = @_;
 2193:     unless (&files_exist($r, $symb)) {
 2194:         $r->print(&mt('There are currently no submitted documents.'));
 2195:         return;
 2196:     }
 2197:     my $all_students = 
 2198: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2199: 
 2200:     my $parts =
 2201: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2202: 
 2203:     my $identifier = &Apache::loncommon::get_cgi_id();
 2204:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2205:                              'cgi.'.$identifier.'.symb' => $symb,
 2206:                              'cgi.'.$identifier.'.parts' => $parts,});
 2207:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2208: 	      &mt('Download All Submitted Documents').'</a>');
 2209:     return;
 2210: }
 2211: 
 2212: sub submit_download_link {
 2213:     my ($request,$symb) = @_;
 2214:     if (!$symb) { return ''; }
 2215:     my $res_error;
 2216:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2217:         &response_type($symb,\$res_error);
 2218:     if ($res_error) {
 2219:         $request->print(&mt('An error occurred retrieving response types'));
 2220:         return;
 2221:     }
 2222:     unless ($numessay) {
 2223:         $request->print(&mt('No essayresponse items found'));
 2224:         return;
 2225:     }
 2226:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2227:     if (@chosenparts) {
 2228:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2229:                                           undef,undef,1));
 2230:     }
 2231:     if ($numessay) {
 2232:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2233:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2234:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2235:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2236:         if (ref($fullname) eq 'HASH') {
 2237:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2238:             if (@students) {
 2239:                 @{$env{'form.stuinfo'}} = @students;
 2240:                 if ($numdropbox) {
 2241:                     &download_all_link($request,$symb);
 2242:                 } else {
 2243:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2244:                 }
 2245: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2246: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2247:             } else {
 2248:                 $request->print(&mt('No students match the criteria you selected'));
 2249:             }
 2250:         } else {
 2251:             $request->print(&mt('Could not retrieve student information'));
 2252:         }
 2253:     } else {
 2254:         $request->print(&mt('No essayresponse items found'));
 2255:     }
 2256:     return;
 2257: }
 2258: 
 2259: sub build_section_inputs {
 2260:     my $section_inputs;
 2261:     if ($env{'form.section'} eq '') {
 2262:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2263:     } else {
 2264:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2265:         foreach my $section (@sections) {
 2266:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2267:         }
 2268:     }
 2269:     return $section_inputs;
 2270: }
 2271: 
 2272: # --------------------------- show submissions of a student, option to grade 
 2273: sub submission {
 2274:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2275:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2276:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2277:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2278:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2279: 
 2280:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2281:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2282:     my ($essayurl,%coursedesc_by_cid);
 2283: 
 2284:     if (!&canview($usec)) {
 2285:         $request->print(
 2286:             '<span class="LC_warning">'.
 2287:             &mt('Unable to view requested student.').
 2288:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2289:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2290:             '</span>');
 2291: 	return;
 2292:     }
 2293: 
 2294:     my $res_error;
 2295:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2296:         &response_type($symb,\$res_error);
 2297:     if ($res_error) {
 2298:         $request->print(&navmap_errormsg());
 2299:         return;
 2300:     }
 2301: 
 2302:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2303:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2304:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2305:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2306:         $env{'form.compmsg'} = 1;
 2307:     }
 2308:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2309:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2310: 	'" src="'.$request->dir_config('lonIconsURL').
 2311: 	'/check.gif" height="16" border="0" />';
 2312: 
 2313:     # header info
 2314:     if ($counter == 0) {
 2315:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2316:         if (@chosenparts) {
 2317:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2318:         } elsif ($divforres) {
 2319:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2320:         } else {
 2321:             $request->print('<br clear="all" />');
 2322:         }
 2323: 	&sub_page_js($request);
 2324:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2325: 	&sub_page_kw_js($request) if ($numessay);
 2326: 
 2327: 	# option to display problem, only once else it cause problems 
 2328:         # with the form later since the problem has a form.
 2329: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2330: 	    my $mode;
 2331: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2332: 		$mode='both';
 2333: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2334: 		$mode='text';
 2335: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2336: 		$mode='answer';
 2337: 	    }
 2338: 	    &Apache::lonxml::clear_problem_counter();
 2339: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2340: 	}
 2341: 
 2342: 	my %keyhash = ();
 2343: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2344: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2345: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2346: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2347: 	}
 2348: 	# kwclr is the only variable that is guaranteed not to be blank
 2349: 	# if this subroutine has been called once.
 2350: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2351: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2352: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2353: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2354: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2355: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2356: 	}
 2357: 	if ($env{'form.compmsg'}) {
 2358: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2359: 		$keyhash{$symb.'_subject'} : $probtitle;
 2360: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2361: 	}
 2362: 
 2363: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2364: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2365: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2366: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2367: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2368: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2369: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2370: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2371: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2372: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2373: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2374: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2375: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2376: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2377: 			&build_section_inputs().
 2378: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2379: 			'<input type="hidden" name="NCT"'.
 2380: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2381: 	if ($env{'form.compmsg'}) {
 2382: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2383: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2384: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2385: 	}
 2386: 	if ($numessay) {
 2387: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2388: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2389: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2390: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2391: 	}
 2392: 
 2393: 	my ($cts,$prnmsg) = (1,'');
 2394: 	while ($cts <= $env{'form.savemsgN'}) {
 2395: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2396: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2397: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2398: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2399: 		'" />'."\n".
 2400: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2401: 	    $cts++;
 2402: 	}
 2403: 	$request->print($prnmsg);
 2404: 
 2405: 	if ($numessay) {
 2406: 
 2407:             my %lt = &Apache::lonlocal::texthash(
 2408:                           keyh => 'Keyword Highlighting for Essays',
 2409:                           keyw => 'Keyword Options',
 2410:                           list => 'List',
 2411:                           past => 'Paste Selection to List',
 2412:                           high => 'Highlight Attribute',
 2413:                      );
 2414: #
 2415: # Print out the keyword options line
 2416: #
 2417: 	    $request->print(
 2418:                 '<div class="LC_columnSection">'
 2419:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2420:                .&Apache::lonhtmlcommon::funclist_from_array(
 2421:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2422:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2423:  class="page">'.$lt{'past'}.'</a>',
 2424:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2425:                     {legend => $lt{'keyw'}})
 2426:                .'</fieldset></div>'
 2427:             );
 2428: 
 2429: #
 2430: # Load the other essays for similarity check
 2431: #
 2432:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2433:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2434:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2435:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2436:                 if ($cdom ne '' && $cnum ne '') {
 2437:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2438:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2439:                         my $apath = $1.'_'.$id;
 2440:                         $apath=~s/\W/\_/gs;
 2441:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2442:                     }
 2443:                 }
 2444:             } else {
 2445: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2446: 	        $apath=&escape($apath);
 2447: 	        $apath=~s/\W/\_/gs;
 2448:                 &init_old_essays($symb,$apath,$adom,$aname);
 2449:             }
 2450:         }
 2451:     }
 2452: 
 2453: # This is where output for one specific student would start
 2454:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2455:     $request->print(
 2456:         "\n\n"
 2457:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2458:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2459:        ."\n"
 2460:     );
 2461: 
 2462:     # Show additional functions if allowed
 2463:     if ($perm{'vgr'}) {
 2464:         $request->print(
 2465:             &Apache::loncommon::track_student_link(
 2466:                 'View recent activity',
 2467:                 $uname,$udom,'check')
 2468:            .' '
 2469:         );
 2470:     }
 2471:     if ($perm{'opa'}) {
 2472:         $request->print(
 2473:             &Apache::loncommon::pprmlink(
 2474:                 &mt('Set/Change parameters'),
 2475:                 $uname,$udom,$symb,'check'));
 2476:     }
 2477: 
 2478:     # Show Problem
 2479:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2480: 	my $mode;
 2481: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2482: 	    $mode='both';
 2483: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2484: 	    $mode='text';
 2485: 	} elsif ($env{'form.vAns'} eq 'all') {
 2486: 	    $mode='answer';
 2487: 	}
 2488: 	&Apache::lonxml::clear_problem_counter();
 2489: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2490:     }
 2491: 
 2492:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2493: 
 2494:     # Display student info
 2495:     $request->print(($counter == 0 ? '' : '<br />'));
 2496: 
 2497:     my $result='<div class="LC_Box">'
 2498:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2499:     $result.='<input type="hidden" name="name'.$counter.
 2500:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2501:     if ($numresp > $numessay) {
 2502:         $result.='<p class="LC_info">'
 2503:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2504:                 ."</p>\n";
 2505:     }
 2506: 
 2507:     # If any part of the problem is an essayresponse, then check for collaborators
 2508:     my $fullname;
 2509:     my $col_fullnames = [];
 2510:     if ($numessay) {
 2511: 	(my $sub_result,$fullname,$col_fullnames)=
 2512: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2513: 				 $counter);
 2514: 	$result.=$sub_result;
 2515:     }
 2516:     $request->print($result."\n");
 2517: 
 2518:     # print student answer/submission
 2519:     # Options are (1) Last submission only
 2520:     #             (2) Last submission (with detailed information for that submission)
 2521:     #             (3) All transactions (by date)
 2522:     #             (4) The whole record (with detailed information for all transactions)
 2523: 
 2524:     my ($string,$timestamp)= &get_last_submission(\%record);
 2525: 
 2526:     my $lastsubonly;
 2527: 
 2528:     if ($$timestamp eq '') {
 2529:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2530:     } else {
 2531:         $lastsubonly =
 2532:             '<div class="LC_grade_submissions_body">'
 2533:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2534: 
 2535: 	my %seenparts;
 2536: 	my @part_response_id = &flatten_responseType($responseType);
 2537: 	foreach my $part (@part_response_id) {
 2538: 	    my ($partid,$respid) = @{ $part };
 2539: 	    my $display_part=&get_display_part($partid,$symb);
 2540: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2541: 		if (exists($seenparts{$partid})) { next; }
 2542: 		$seenparts{$partid}=1;
 2543:                 $request->print(
 2544:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2545:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2546:                                '<a href="javascript:viewSubmitter(\''.
 2547:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2548:                                '\');" target="_self">'.
 2549:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2550:                     '<br />');
 2551: 		next;
 2552: 	    }
 2553: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2554: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2555:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2556:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2557:                     ' <span class="LC_internal_info">'.
 2558:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2559:                     '</span>&nbsp; &nbsp;'.
 2560: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2561: 		next;
 2562: 	    }
 2563: 	    foreach my $submission (@$string) {
 2564: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2565: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2566: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2567: 		# Similarity check
 2568:                 my $similar='';
 2569:                 my ($type,$trial,$rndseed);
 2570:                 if ($hide eq 'rand') {
 2571:                     $type = 'randomizetry';
 2572:                     $trial = $record{"resource.$partid.tries"};
 2573:                     $rndseed = $record{"resource.$partid.rndseed"};
 2574:                 }
 2575: 		if ($env{'form.checkPlag'}) {
 2576: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2577: 		        &most_similar($uname,$udom,$symb,$subval);
 2578: 		    if ($osim) {
 2579: 		        $osim=int($osim*100.0);
 2580:                         if ($hide eq 'anon') {
 2581:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2582:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2583:                         } else {
 2584: 			    $similar='<hr />';
 2585:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2586:                                 $similar .= '<h3><span class="LC_warning">'.
 2587:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2588:                                                 $osim,
 2589:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2590:                                             '</span></h3>';
 2591:                             } elsif ($ocrsid ne '') {
 2592:                                 my %old_course_desc;
 2593:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2594:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2595:                                 } else {
 2596:                                     my $args;
 2597:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2598:                                         $args = {'one_time' => 1};
 2599:                                     }
 2600:                                     %old_course_desc =
 2601:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2602:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2603:                                 }
 2604:                                 $similar .=
 2605:                                     '<h3><span class="LC_warning">'.
 2606: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2607: 				        $osim,
 2608: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2609: 				        $old_course_desc{'description'},
 2610: 				        $old_course_desc{'num'},
 2611: 				        $old_course_desc{'domain'}).
 2612: 				    '</span></h3>';
 2613:                             } else {
 2614:                                 $similar .=
 2615:                                     '<h3><span class="LC_warning">'.
 2616:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2617:                                         $osim,
 2618:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2619:                                     '</span></h3>';
 2620:                             }
 2621:                             $similar .= '<blockquote><i>'.
 2622:                                         &keywords_highlight($oessay).
 2623:                                         '</i></blockquote><hr />';
 2624: 		        }
 2625:                     }
 2626:                 }
 2627: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2628:                                      undef,$type,$trial,$rndseed);
 2629:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2630:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2631:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2632: 		    my $display_part=&get_display_part($partid,$symb);
 2633:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2634:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2635:                         ' <span class="LC_internal_info">'.
 2636:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2637:                         '</span>&nbsp; &nbsp;';
 2638: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2639: 		    if (@$files) {
 2640:                         if ($hide eq 'anon') {
 2641:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2642:                         } else {
 2643:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2644:                                          .'<br /><span class="LC_warning">';
 2645:                             if(@$files == 1) {
 2646:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2647:                             } else {
 2648:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2649:                             }
 2650:                             $lastsubonly .= '</span>';
 2651:                             foreach my $file (@$files) {
 2652:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2653:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2654:                             }
 2655:                         }
 2656: 			$lastsubonly.='<br />';
 2657: 		    }
 2658:                     if ($hide eq 'anon') {
 2659:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2660:                     } else {
 2661:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2662:                         if ($draft) {
 2663:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2664:                         }
 2665:                         $subval =
 2666: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2667: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2668:                         if ($responsetype eq 'essay') {
 2669:                             $subval =~ s{\n}{<br />}g;
 2670:                         }
 2671:                         $lastsubonly.=$subval."\n";
 2672:                     }
 2673:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2674: 		    $lastsubonly.='</div>';
 2675: 		}
 2676: 	    }
 2677: 	}
 2678: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2679:     }
 2680:     $request->print($lastsubonly);
 2681:     if ($env{'form.lastSub'} eq 'datesub') {
 2682:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2683: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2684:     }
 2685:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2686:         my $identifier = (&canmodify($usec)? $counter : '');
 2687: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2688: 								 $env{'request.course.id'},
 2689: 								 $last,'.submission',
 2690: 								 'Apache::grades::keywords_highlight',
 2691:                                                                  $usec,$identifier));
 2692:     }
 2693:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2694: 	.$udom.'" />'."\n");
 2695:     # return if view submission with no grading option
 2696:     if (!&canmodify($usec)) {
 2697:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2698:         return;
 2699:     } else {
 2700: 	$request->print('</div>'."\n");
 2701:     }
 2702: 
 2703:     # grading message center
 2704: 
 2705:     if ($env{'form.compmsg'}) {
 2706:         my $result='<div class="LC_Box">'.
 2707:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2708:                    '<div class="LC_grade_message_center_body">';
 2709:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2710:         my $msgfor = $givenn.' '.$lastname;
 2711:         if (scalar(@$col_fullnames) > 0) {
 2712:             my $lastone = pop(@$col_fullnames);
 2713:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2714:         }
 2715:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2716:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2717:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2718: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2719:                  ',\''.$msgfor.'\');" target="_self">'.
 2720:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2721:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2722:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2723:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2724:                  '<br />&nbsp;('.
 2725:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2726: 	         '</div></div>';
 2727:         $request->print($result);
 2728:     }
 2729: 
 2730:     my %seen = ();
 2731:     my @partlist;
 2732:     my @gradePartRespid;
 2733:     my @part_response_id = &flatten_responseType($responseType);
 2734:     $request->print(
 2735:         '<div class="LC_Box">'
 2736:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2737:     );
 2738:     $request->print(&gradeBox_start());
 2739:     foreach my $part_response_id (@part_response_id) {
 2740:     	my ($partid,$respid) = @{ $part_response_id };
 2741: 	my $part_resp = join('_',@{ $part_response_id });
 2742: 	next if ($seen{$partid} > 0);
 2743: 	$seen{$partid}++;
 2744: 	push(@partlist,$partid);
 2745: 	push(@gradePartRespid,$partid.'.'.$respid);
 2746: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2747:     }
 2748:     $request->print(&gradeBox_end()); # </div>
 2749:     $request->print('</div>');
 2750: 
 2751:     $request->print('<div class="LC_grade_info_links">');
 2752:     $request->print('</div>');
 2753: 
 2754:     $result='<input type="hidden" name="partlist'.$counter.
 2755: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2756:     $result.='<input type="hidden" name="gradePartRespid'.
 2757: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2758:     my $ctr = 0;
 2759:     while ($ctr < scalar(@partlist)) {
 2760: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2761: 	    $partlist[$ctr].'" />'."\n";
 2762: 	$ctr++;
 2763:     }
 2764:     $request->print($result.''."\n");
 2765: 
 2766: # Done with printing info for one student
 2767: 
 2768:     $request->print('</div>');#LC_grade_show_user
 2769: 
 2770: 
 2771:     # print end of form
 2772:     if ($counter == $total) {
 2773:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2774: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2775: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2776: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2777: 	my $ntstu ='<select name="NTSTU">'.
 2778: 	    '<option>1</option><option>2</option>'.
 2779: 	    '<option>3</option><option>5</option>'.
 2780: 	    '<option>7</option><option>10</option></select>'."\n";
 2781: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2782: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2783:         $endform.=&mt('[_1]student(s)',$ntstu);
 2784: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2785: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2786: 	    '<input type="button" value="'.&mt('Next').'" '.
 2787: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2788:         $endform.='<span class="LC_warning">'.
 2789:                   &mt('(Next and Previous (student) do not save the scores.)').
 2790:                   '</span>'."\n" ;
 2791:         $endform.="<input type='hidden' value='".&get_increment().
 2792:             "' name='increment' />";
 2793: 	$endform.='</td></tr></table></form>';
 2794: 	$request->print($endform);
 2795:     }
 2796:     return '';
 2797: }
 2798: 
 2799: sub check_collaborators {
 2800:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2801:     my ($result,@col_fullnames);
 2802:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2803:     foreach my $part (keys(%$handgrade)) {
 2804: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2805: 					'.maxcollaborators',
 2806: 					$symb,$udom,$uname);
 2807: 	next if ($ncol <= 0);
 2808: 	$part =~ s/\_/\./g;
 2809: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2810: 	my (@good_collaborators, @bad_collaborators);
 2811: 	foreach my $possible_collaborator
 2812: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2813: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2814: 	    next if ($possible_collaborator eq '');
 2815: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2816: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2817: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2818: 	    # Doing this grep allows 'fuzzy' specification
 2819: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2820: 			       keys(%$classlist));
 2821: 	    if (! scalar(@matches)) {
 2822: 		push(@bad_collaborators, $possible_collaborator);
 2823: 	    } else {
 2824: 		push(@good_collaborators, @matches);
 2825: 	    }
 2826: 	}
 2827: 	if (scalar(@good_collaborators) != 0) {
 2828: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2829: 	    foreach my $name (@good_collaborators) {
 2830: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2831: 		push(@col_fullnames, $givenn.' '.$lastname);
 2832: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2833: 	    }
 2834: 	    $result.='</ol><br />'."\n";
 2835: 	    my ($part)=split(/\./,$part);
 2836: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2837: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2838: 		"\n";
 2839: 	}
 2840: 	if (scalar(@bad_collaborators) > 0) {
 2841: 	    $result.='<div class="LC_warning">';
 2842: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2843: 	    $result .= '</div>';
 2844: 	}         
 2845: 	if (scalar(@bad_collaborators > $ncol)) {
 2846: 	    $result .= '<div class="LC_warning">';
 2847: 	    $result .= &mt('This student has submitted too many '.
 2848: 		'collaborators.  Maximum is [_1].',$ncol);
 2849: 	    $result .= '</div>';
 2850: 	}
 2851:     }
 2852:     return ($result,$fullname,\@col_fullnames);
 2853: }
 2854: 
 2855: #--- Retrieve the last submission for all the parts
 2856: sub get_last_submission {
 2857:     my ($returnhash)=@_;
 2858:     my (@string,$timestamp,%lasthidden);
 2859:     if ($$returnhash{'version'}) {
 2860: 	my %lasthash=();
 2861: 	my ($version);
 2862: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2863: 	    foreach my $key (sort(split(/\:/,
 2864: 					$$returnhash{$version.':keys'}))) {
 2865: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2866: 		$timestamp = 
 2867: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2868: 	    }
 2869: 	}
 2870:         my (%typeparts,%randombytry);
 2871:         my $showsurv = 
 2872:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2873:         foreach my $key (sort(keys(%lasthash))) {
 2874:             if ($key =~ /\.type$/) {
 2875:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2876:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2877:                     ($lasthash{$key} eq 'randomizetry')) {
 2878:                     my ($ign,@parts) = split(/\./,$key);
 2879:                     pop(@parts);
 2880:                     my $id = join('.',@parts);
 2881:                     if ($lasthash{$key} eq 'randomizetry') {
 2882:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2883:                     } else {
 2884:                         unless ($showsurv) {
 2885:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2886:                         }
 2887:                     }
 2888:                     delete($lasthash{$key});
 2889:                 }
 2890:             }
 2891:         }
 2892:         my @hidden = keys(%typeparts);
 2893:         my @randomize = keys(%randombytry);
 2894: 	foreach my $key (keys(%lasthash)) {
 2895: 	    next if ($key !~ /\.submission$/);
 2896:             my $hide;
 2897:             if (@hidden) {
 2898:                 foreach my $id (@hidden) {
 2899:                     if ($key =~ /^\Q$id\E/) {
 2900:                         $hide = 'anon';
 2901:                         last;
 2902:                     }
 2903:                 }
 2904:             }
 2905:             unless ($hide) {
 2906:                 if (@randomize) {
 2907:                     foreach my $id (@randomize) {
 2908:                         if ($key =~ /^\Q$id\E/) {
 2909:                             $hide = 'rand';
 2910:                             last;
 2911:                         }
 2912:                     }
 2913:                 }
 2914:             }
 2915: 	    my ($partid,$foo) = split(/submission$/,$key);
 2916: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2917:             push(@string, join(':', $key, $hide, $draft, (
 2918:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2919:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2920: 	}
 2921:     }
 2922:     if (!@string) {
 2923: 	$string[0] =
 2924: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2925:     }
 2926:     return (\@string,\$timestamp);
 2927: }
 2928: 
 2929: #--- High light keywords, with style choosen by user.
 2930: sub keywords_highlight {
 2931:     my $string    = shift;
 2932:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2933:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2934:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2935:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2936:     foreach my $keyword (@keylist) {
 2937: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2938:     }
 2939:     return $string;
 2940: }
 2941: 
 2942: # For Tasks provide a mechanism to display previous version for one specific student
 2943: 
 2944: sub show_previous_task_version {
 2945:     my ($request,$symb) = @_;
 2946:     if ($symb eq '') {
 2947:         $request->print(
 2948:             '<span class="LC_error">'.
 2949:             &mt('Unable to handle ambiguous references.').
 2950:             '</span>');
 2951:         return '';
 2952:     }
 2953:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2954:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2955:     if (!&canview($usec)) {
 2956:         $request->print('<span class="LC_warning">'.
 2957:                         &mt('Unable to view previous version for requested student.').
 2958:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2959:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2960:                         '</span>');
 2961:         return;
 2962:     }
 2963:     my $mode = 'both';
 2964:     my $isTask = ($symb =~/\.task$/);
 2965:     if ($isTask) {
 2966:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2967:             if ($env{'form.fullname'} eq '') {
 2968:                 $env{'form.fullname'} =
 2969:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2970:             }
 2971:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2972:             $request->print("\n\n".
 2973:                             '<div class="LC_grade_show_user">'.
 2974:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2975:                             '</h2>'."\n");
 2976:             &Apache::lonxml::clear_problem_counter();
 2977:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2978:                             {'previousversion' => $env{'form.previousversion'} }));
 2979:             $request->print("\n</div>");
 2980:         }
 2981:     }
 2982:     return;
 2983: }
 2984: 
 2985: sub choose_task_version_form {
 2986:     my ($symb,$uname,$udom,$nomenu) = @_;
 2987:     my $isTask = ($symb =~/\.task$/);
 2988:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2989:     if ($isTask) {
 2990:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2991:                                               $udom,$uname);
 2992:         if (($record{'resource.0.version'} eq '') ||
 2993:             ($record{'resource.0.version'} < 2)) {
 2994:             return ($record{'resource.0.version'},
 2995:                     $record{'resource.0.version'},$result,$js);
 2996:         } else {
 2997:             $current = $record{'resource.0.version'};
 2998:         }
 2999:         if ($env{'form.previousversion'}) {
 3000:             $displayed = $env{'form.previousversion'};
 3001:             $rowtitle = &mt('Choose another version:')
 3002:         } else {
 3003:             $displayed = $current;
 3004:             $rowtitle = &mt('Show earlier version:');
 3005:         }
 3006:         $result = '<div class="LC_left_float">';
 3007:         my $list;
 3008:         my $numversions = 0;
 3009:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3010:             if ($i == $current) {
 3011:                 if (!$env{'form.previousversion'} || $nomenu) {
 3012:                     next;
 3013:                 } else {
 3014:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3015:                     $numversions ++;
 3016:                 }
 3017:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3018:                 unless ($i == $env{'form.previousversion'}) {
 3019:                     $numversions ++;
 3020:                 }
 3021:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3022:             }
 3023:         }
 3024:         if ($numversions) {
 3025:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3026:             $result .=
 3027:                 '<form name="getprev" method="post" action=""'.
 3028:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3029:                 &Apache::loncommon::start_data_table().
 3030:                 &Apache::loncommon::start_data_table_row().
 3031:                 '<th align="left">'.$rowtitle.'</th>'.
 3032:                 '<td><select name="version">'.
 3033:                 '<option>'.&mt('Select').'</option>'.
 3034:                 $list.
 3035:                 '</select></td>'.
 3036:                 &Apache::loncommon::end_data_table_row();
 3037:             unless ($nomenu) {
 3038:                 $result .= &Apache::loncommon::start_data_table_row().
 3039:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3040:                 '<td><span class="LC_nobreak">'.
 3041:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3042:                 &mt('Yes').'</label>'.
 3043:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3044:                 '</span></td>'.
 3045:                 &Apache::loncommon::end_data_table_row();
 3046:             }
 3047:             $result .=
 3048:                 &Apache::loncommon::start_data_table_row().
 3049:                 '<th align="left">&nbsp;</th>'.
 3050:                 '<td>'.
 3051:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3052:                 '</td>'.
 3053:                 &Apache::loncommon::end_data_table_row().
 3054:                 &Apache::loncommon::end_data_table().
 3055:                 '</form>';
 3056:             $js = &previous_display_javascript($nomenu,$current);
 3057:         } elsif ($displayed && $nomenu) {
 3058:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3059:         } else {
 3060:             $result .= &mt('No previous versions to show for this student');
 3061:         }
 3062:         $result .= '</div>';
 3063:     }
 3064:     return ($current,$displayed,$result,$js);
 3065: }
 3066: 
 3067: sub previous_display_javascript {
 3068:     my ($nomenu,$current) = @_;
 3069:     my $js = <<"JSONE";
 3070: <script type="text/javascript">
 3071: // <![CDATA[
 3072: function previousVersion(uname,udom,symb) {
 3073:     var current = '$current';
 3074:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3075:     var prevstr = new RegExp("^\\\\d+\$");
 3076:     if (!prevstr.test(version)) {
 3077:         return false;
 3078:     }
 3079:     var url = '';
 3080:     if (version == current) {
 3081:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3082:     } else {
 3083:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3084:     }
 3085: JSONE
 3086:     if ($nomenu) {
 3087:         $js .= <<"JSTWO";
 3088:     document.location.href = url;
 3089: JSTWO
 3090:     } else {
 3091:         $js .= <<"JSTHREE";
 3092:     var newwin = 0;
 3093:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3094:         if (document.getprev.prevwin[i].checked == true) {
 3095:             newwin = document.getprev.prevwin[i].value;
 3096:         }
 3097:     }
 3098:     if (newwin == 1) {
 3099:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3100:         url = url+'&inhibitmenu=yes';
 3101:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3102:             previousWin = window.open(url,'',options,1);
 3103:         } else {
 3104:             previousWin.location.href = url;
 3105:         }
 3106:         previousWin.focus();
 3107:         return false;
 3108:     } else {
 3109:         document.location.href = url;
 3110:         return false;
 3111:     }
 3112: JSTHREE
 3113:     }
 3114:     $js .= <<"ENDJS";
 3115:     return false;
 3116: }
 3117: // ]]>
 3118: </script>
 3119: ENDJS
 3120: 
 3121: }
 3122: 
 3123: #--- Called from submission routine
 3124: sub processHandGrade {
 3125:     my ($request,$symb) = @_;
 3126:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3127:     my $button = $env{'form.gradeOpt'};
 3128:     my $ngrade = $env{'form.NCT'};
 3129:     my $ntstu  = $env{'form.NTSTU'};
 3130:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3131:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3132: 
 3133:     if ($button eq 'Save & Next') {
 3134: 	my $ctr = 0;
 3135: 	while ($ctr < $ngrade) {
 3136: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3137: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3138:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3139: 	    if ($errorflag eq 'no_score') {
 3140: 		$ctr++;
 3141: 		next;
 3142: 	    }
 3143: 	    if ($errorflag eq 'not_allowed') {
 3144:                 $request->print(
 3145:                     '<span class="LC_error">'
 3146:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3147:                    .'</span>');
 3148: 		$ctr++;
 3149: 		next;
 3150: 	    }
 3151:             if ($numhidden) {
 3152:                 $request->print(
 3153:                     '<span class="LC_info">'
 3154:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3155:                    .'</span><br />');
 3156:             }
 3157: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3158: 	    my ($subject,$message,$msgstatus) = ('','','');
 3159: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3160:             my ($feedurl,$showsymb) =
 3161: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3162: 	    my $messagetail;
 3163: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3164: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3165: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3166: 		$subject.=' ['.$restitle.']';
 3167: 		my (@msgnum) = split(/,/,$includemsg);
 3168: 		foreach (@msgnum) {
 3169: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3170: 		}
 3171: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3172: 		if ($env{'form.withgrades'.$ctr}) {
 3173: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3174: 		    $messagetail = " for <a href=\"".
 3175: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3176: 		}
 3177: 		$msgstatus = 
 3178:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3179: 						     $message.$messagetail,
 3180:                                                      undef,$feedurl,undef,
 3181:                                                      undef,undef,$showsymb,
 3182:                                                      $restitle);
 3183: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3184: 				$msgstatus.'<br />');
 3185: 	    }
 3186: 	    if ($env{'form.collaborator'.$ctr}) {
 3187: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3188: 		foreach my $collabstr (@collabstrs) {
 3189: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3190: 		    foreach my $collaborator (@collaborators) {
 3191: 			my ($errorflag,$pts,$wgt) = 
 3192: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3193: 					   $env{'form.unamedom'.$ctr},$part);
 3194: 			if ($errorflag eq 'not_allowed') {
 3195: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3196: 			    next;
 3197: 			} elsif ($message ne '') {
 3198: 			    my ($baseurl,$showsymb) = 
 3199: 				&get_feedurl_and_symb($symb,$collaborator,
 3200: 						      $udom);
 3201: 			    if ($env{'form.withgrades'.$ctr}) {
 3202: 				$messagetail = " for <a href=\"".
 3203:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3204: 			    }
 3205: 			    $msgstatus = 
 3206: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3207: 			}
 3208: 		    }
 3209: 		}
 3210: 	    }
 3211: 	    $ctr++;
 3212: 	}
 3213:     }
 3214: 
 3215:     my $res_error;
 3216:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3217:     if ($res_error) {
 3218:         $request->print(&navmap_errormsg());
 3219:         return;
 3220:     }
 3221: 
 3222:     my %keyhash = ();
 3223:     if ($numessay) {
 3224: 	# Keywords sorted in alphabatical order
 3225: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3226: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3227: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3228: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3229: 	$env{'form.keywords'} = join(' ',@keywords);
 3230: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3231: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3232: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3233: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3234: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3235:     }
 3236: 
 3237:     if ($env{'form.compmsg'}) {
 3238: 	# message center - Order of message gets changed. Blank line is eliminated.
 3239: 	# New messages are saved in env for the next student.
 3240: 	# All messages are saved in nohist_handgrade.db
 3241: 	my ($ctr,$idx) = (1,1);
 3242: 	while ($ctr <= $env{'form.savemsgN'}) {
 3243: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3244: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3245: 		$idx++;
 3246: 	    }
 3247: 	    $ctr++;
 3248: 	}
 3249: 	$ctr = 0;
 3250: 	while ($ctr < $ngrade) {
 3251: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3252: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3253: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3254: 		$idx++;
 3255: 	    }
 3256: 	    $ctr++;
 3257: 	}
 3258: 	$env{'form.savemsgN'} = --$idx;
 3259: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3260:     }
 3261:     if (($numessay) || ($env{'form.compmsg'})) {
 3262: 	my $putresult = &Apache::lonnet::put
 3263: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3264:     }
 3265: 
 3266:     # Called by Save & Refresh from Highlight Attribute Window
 3267:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3268:     if ($env{'form.refresh'} eq 'on') {
 3269: 	my ($ctr,$total) = (0,0);
 3270: 	while ($ctr < $ngrade) {
 3271: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3272: 	    $ctr++;
 3273: 	}
 3274: 	$env{'form.NTSTU'}=$ngrade;
 3275: 	$ctr = 0;
 3276: 	while ($ctr < $total) {
 3277: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3278: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3279: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3280: 	    &submission($request,$ctr,$total-1,$symb);
 3281: 	    $ctr++;
 3282: 	}
 3283: 	return '';
 3284:     }
 3285: 
 3286:     # Get the next/previous one or group of students
 3287:     my $firststu = $env{'form.unamedom0'};
 3288:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3289:     my $ctr = 2;
 3290:     while ($laststu eq '') {
 3291: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3292: 	$ctr++;
 3293: 	$laststu = $firststu if ($ctr > $ngrade);
 3294:     }
 3295: 
 3296:     my (@parsedlist,@nextlist);
 3297:     my ($nextflg) = 0;
 3298:     foreach my $item (sort 
 3299: 	     {
 3300: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3301: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3302: 		 }
 3303: 		 return $a cmp $b;
 3304: 	     } (keys(%$fullname))) {
 3305: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3306: 	    push(@parsedlist,$item);
 3307: 	}
 3308: 	$nextflg = 1 if ($item eq $laststu);
 3309: 	if ($button eq 'Previous') {
 3310: 	    last if ($item eq $firststu);
 3311: 	    push(@parsedlist,$item);
 3312: 	}
 3313:     }
 3314:     $ctr = 0;
 3315:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3316:     foreach my $student (@parsedlist) {
 3317: 	my $submitonly=$env{'form.submitonly'};
 3318: 	my ($uname,$udom) = split(/:/,$student);
 3319: 	
 3320: 	if ($submitonly eq 'queued') {
 3321: 	    my %queue_status = 
 3322: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3323: 							$udom,$uname);
 3324: 	    next if (!defined($queue_status{'gradingqueue'}));
 3325: 	}
 3326: 
 3327: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3328: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3329: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3330: 	    my $submitted = 0;
 3331: 	    my $ungraded = 0;
 3332: 	    my $incorrect = 0;
 3333: 	    foreach my $item (keys(%status)) {
 3334: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3335: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3336: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3337: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3338: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3339: 		    $submitted = 0;
 3340: 		}
 3341: 	    }
 3342: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3343: 				     $submitonly eq 'incorrect' ||
 3344: 				     $submitonly eq 'graded'));
 3345: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3346: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3347: 	}
 3348: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3349: 	last if ($ctr == $ntstu);
 3350: 	$ctr++;
 3351:     }
 3352: 
 3353:     $ctr = 0;
 3354:     my $total = scalar(@nextlist)-1;
 3355: 
 3356:     foreach (sort(@nextlist)) {
 3357: 	my ($uname,$udom,$submitter) = split(/:/);
 3358: 	$env{'form.student'}  = $uname;
 3359: 	$env{'form.userdom'}  = $udom;
 3360: 	$env{'form.fullname'} = $$fullname{$_};
 3361: 	&submission($request,$ctr,$total,$symb);
 3362: 	$ctr++;
 3363:     }
 3364:     if ($total < 0) {
 3365:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3366: 	$request->print($the_end);
 3367:     }
 3368:     return '';
 3369: }
 3370: 
 3371: #---- Save the score and award for each student, if changed
 3372: sub saveHandGrade {
 3373:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3374:     my @version_parts;
 3375:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3376: 					   $env{'request.course.id'});
 3377:     if (!&canmodify($usec)) { return('not_allowed'); }
 3378:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3379:     my @parts_graded;
 3380:     my %newrecord  = ();
 3381:     my ($pts,$wgt,$totchg) = ('','',0);
 3382:     my %aggregate = ();
 3383:     my $aggregateflag = 0;
 3384:     if ($env{'form.HIDE'.$newflg}) {
 3385:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3386:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3387:         $totchg += $numchgs;
 3388:     }
 3389:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3390:     foreach my $new_part (@parts) {
 3391: 	#collaborator ($submi may vary for different parts
 3392: 	if ($submitter && $new_part ne $part) { next; }
 3393: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3394: 	if ($dropMenu eq 'excused') {
 3395: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3396: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3397: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3398: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3399: 		}
 3400: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3401: 	    }
 3402: 	} elsif ($dropMenu eq 'reset status'
 3403: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3404: 	    foreach my $key (keys(%record)) {
 3405: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3406: 	    }
 3407: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3408: 		"$env{'user.name'}:$env{'user.domain'}";
 3409:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3410: 
 3411:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3412: 					       [$new_part]);
 3413:             my $aggtries =$totaltries;
 3414:             if ($last_resets{$new_part}) {
 3415:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3416: 					   $new_part);
 3417:             }
 3418: 
 3419:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3420:             if ($aggtries > 0) {
 3421:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3422:                 $aggregateflag = 1;
 3423:             }
 3424: 	} elsif ($dropMenu eq '') {
 3425: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3426: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3427: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3428: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3429: 		next;
 3430: 	    }
 3431: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3432: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3433: 	    my $partial= $pts/$wgt;
 3434: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3435: 		#do not update score for part if not changed.
 3436:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3437: 		next;
 3438: 	    } else {
 3439: 	        push(@parts_graded,$new_part);
 3440: 	    }
 3441: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3442: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3443: 	    }
 3444: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3445: 	    if ($partial == 0) {
 3446: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3447: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3448: 		}
 3449: 	    } else {
 3450: 		if ($record{$reckey} ne 'correct_by_override') {
 3451: 		    $newrecord{$reckey} = 'correct_by_override';
 3452: 		}
 3453: 	    }	    
 3454: 	    if ($submitter && 
 3455: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3456: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3457: 	    }
 3458: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3459: 		"$env{'user.name'}:$env{'user.domain'}";
 3460: 	}
 3461: 	# unless problem has been graded, set flag to version the submitted files
 3462: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3463: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3464: 	        $dropMenu eq 'reset status')
 3465: 	   {
 3466: 	    push(@version_parts,$new_part);
 3467: 	}
 3468:     }
 3469:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3470:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3471: 
 3472:     if (%newrecord) {
 3473:         if (@version_parts) {
 3474:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3475:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3476: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3477: 	    foreach my $new_part (@version_parts) {
 3478: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3479: 				$new_part,\%newrecord);
 3480: 	    }
 3481:         }
 3482: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3483: 				$env{'request.course.id'},$domain,$stuname);
 3484: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3485: 				     $cdom,$cnum,$domain,$stuname);
 3486:     }
 3487:     if ($aggregateflag) {
 3488:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3489: 			      $cdom,$cnum);
 3490:     }
 3491:     return ('',$pts,$wgt,$totchg);
 3492: }
 3493: 
 3494: sub makehidden {
 3495:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3496:     return unless (ref($record) eq 'HASH');
 3497:     my %modified;
 3498:     my $numchanged = 0;
 3499:     if (exists($record->{$version.':keys'})) {
 3500:         my $partsregexp = $parts;
 3501:         $partsregexp =~ s/,/|/g;
 3502:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3503:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3504:                  my $item = $1;
 3505:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3506:                      $modified{$key} = $record->{$version.':'.$key};
 3507:                  }
 3508:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3509:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3510:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3511:                 $modified{$key} = $record->{$version.':'.$key};
 3512:             }
 3513:         }
 3514:         if (keys(%modified)) {
 3515:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3516:                                           $domain,$stuname,$tolog) eq 'ok') {
 3517:                 $numchanged ++;
 3518:             }
 3519:         }
 3520:     }
 3521:     return $numchanged;
 3522: }
 3523: 
 3524: sub check_and_remove_from_queue {
 3525:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3526:     my @ungraded_parts;
 3527:     foreach my $part (@{$parts}) {
 3528: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3529: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3530: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3531: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3532: 		) {
 3533: 	    push(@ungraded_parts, $part);
 3534: 	}
 3535:     }
 3536:     if ( !@ungraded_parts ) {
 3537: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3538: 					       $cnum,$domain,$stuname);
 3539:     }
 3540: }
 3541: 
 3542: sub handback_files {
 3543:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3544:     my $portfolio_root = '/userfiles/portfolio';
 3545:     my $res_error;
 3546:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3547:     if ($res_error) {
 3548:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3549:         return;
 3550:     }
 3551:     my @handedback;
 3552:     my $file_msg;
 3553:     my @part_response_id = &flatten_responseType($responseType);
 3554:     foreach my $part_response_id (@part_response_id) {
 3555:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3556: 	my $part_resp = join('_',@{ $part_response_id });
 3557:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3558:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3559:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3560: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3561:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3562:                     my ($directory,$answer_file) = 
 3563:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3564:                     my ($answer_name,$answer_ver,$answer_ext) =
 3565: 		        &file_name_version_ext($answer_file);
 3566: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3567:                     my $getpropath = 1;
 3568:                     my ($dir_list,$listerror) =
 3569:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3570:                                                  $domain,$stuname,$getpropath);
 3571: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3572:                     # fix filename
 3573:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3574:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3575:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3576:             	                                $save_file_name);
 3577:                     if ($result !~ m|^/uploaded/|) {
 3578:                         $request->print('<br /><span class="LC_error">'.
 3579:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3580:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3581:                                         '</span>');
 3582:                     } else {
 3583:                         # mark the file as read only
 3584:                         push(@handedback,$save_file_name);
 3585: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3586: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3587: 			}
 3588:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3589: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3590: 
 3591:                     }
 3592:                     $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>'));
 3593:                 }
 3594:             }
 3595:         }
 3596:     }
 3597:     if (@handedback > 0) {
 3598:         $request->print('<br />');
 3599:         my @what = ($symb,$env{'request.course.id'},'handback');
 3600:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3601:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3602:         my ($subject,$message);
 3603:         if (scalar(@handedback) == 1) {
 3604:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3605:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3606:         } else {
 3607:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3608:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3609:         }
 3610:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3611:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3612:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3613:         my ($feedurl,$showsymb) =
 3614:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3615:         my $restitle = &Apache::lonnet::gettitle($symb);
 3616:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3617:         my $msgstatus =
 3618:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3619:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3620:                  $restitle);
 3621:         if ($msgstatus) {
 3622:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3623:         }
 3624:     }
 3625:     return;
 3626: }
 3627: 
 3628: sub get_feedurl_and_symb {
 3629:     my ($symb,$uname,$udom) = @_;
 3630:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3631:     $url = &Apache::lonnet::clutter($url);
 3632:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3633: 					$symb,$udom,$uname);
 3634:     if ($encrypturl =~ /^yes$/i) {
 3635: 	&Apache::lonenc::encrypted(\$url,1);
 3636: 	&Apache::lonenc::encrypted(\$symb,1);
 3637:     }
 3638:     return ($url,$symb);
 3639: }
 3640: 
 3641: sub get_submitted_files {
 3642:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3643:     my @files;
 3644:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3645:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3646:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3647:     	    push(@files,$file_url.$file);
 3648:         }
 3649:     }
 3650:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3651:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3652:     }
 3653:     return (\@files);
 3654: }
 3655: 
 3656: # ----------- Provides number of tries since last reset.
 3657: sub get_num_tries {
 3658:     my ($record,$last_reset,$part) = @_;
 3659:     my $timestamp = '';
 3660:     my $num_tries = 0;
 3661:     if ($$record{'version'}) {
 3662:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3663:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3664:                 $timestamp = $$record{$version.':timestamp'};
 3665:                 if ($timestamp > $last_reset) {
 3666:                     $num_tries ++;
 3667:                 } else {
 3668:                     last;
 3669:                 }
 3670:             }
 3671:         }
 3672:     }
 3673:     return $num_tries;
 3674: }
 3675: 
 3676: # ----------- Determine decrements required in aggregate totals 
 3677: sub decrement_aggs {
 3678:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3679:     my %decrement = (
 3680:                         attempts => 0,
 3681:                         users => 0,
 3682:                         correct => 0
 3683:                     );
 3684:     $decrement{'attempts'} = $aggtries;
 3685:     if ($solvedstatus =~ /^correct/) {
 3686:         $decrement{'correct'} = 1;
 3687:     }
 3688:     if ($aggtries == $totaltries) {
 3689:         $decrement{'users'} = 1;
 3690:     }
 3691:     foreach my $type (keys(%decrement)) {
 3692:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3693:     }
 3694:     return;
 3695: }
 3696: 
 3697: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3698: sub get_last_resets {
 3699:     my ($symb,$courseid,$partids) =@_;
 3700:     my %last_resets;
 3701:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3702:     my $cname = $env{'course.'.$courseid.'.num'};
 3703:     my @keys;
 3704:     foreach my $part (@{$partids}) {
 3705: 	push(@keys,"$symb\0$part\0resettime");
 3706:     }
 3707:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3708: 				     $cdom,$cname);
 3709:     foreach my $part (@{$partids}) {
 3710: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3711:     }
 3712:     return %last_resets;
 3713: }
 3714: 
 3715: # ----------- Handles creating versions for portfolio files as answers
 3716: sub version_portfiles {
 3717:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3718:     my $version_parts = join('|',@$v_flag);
 3719:     my @returned_keys;
 3720:     my $parts = join('|', @$parts_graded);
 3721:     my $portfolio_root = '/userfiles/portfolio';
 3722:     foreach my $key (keys(%$record)) {
 3723:         my $new_portfiles;
 3724:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3725:             my @versioned_portfiles;
 3726:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3727:             foreach my $file (@portfiles) {
 3728:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3729:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3730: 		my ($answer_name,$answer_ver,$answer_ext) =
 3731: 		    &file_name_version_ext($answer_file);
 3732:                 my $getpropath = 1;
 3733:                 my ($dir_list,$listerror) =
 3734:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3735:                                              $stu_name,$getpropath);
 3736:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3737:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3738:                 if ($new_answer ne 'problem getting file') {
 3739:                     push(@versioned_portfiles, $directory.$new_answer);
 3740:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3741:                         [$directory.$new_answer],
 3742:                         [$symb,$env{'request.course.id'},'graded']);
 3743:                 }
 3744:             }
 3745:             $$record{$key} = join(',',@versioned_portfiles);
 3746:             push(@returned_keys,$key);
 3747:         }
 3748:     } 
 3749:     return (@returned_keys);   
 3750: }
 3751: 
 3752: sub get_next_version {
 3753:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3754:     my $version;
 3755:     if (ref($dir_list) eq 'ARRAY') {
 3756:         foreach my $row (@{$dir_list}) {
 3757:             my ($file) = split(/\&/,$row,2);
 3758:             my ($file_name,$file_version,$file_ext) =
 3759: 	        &file_name_version_ext($file);
 3760:             if (($file_name eq $answer_name) && 
 3761: 	        ($file_ext eq $answer_ext)) {
 3762:                 # gets here if filename and extension match, 
 3763:                 # regardless of version
 3764:                 if ($file_version ne '') {
 3765:                     # a versioned file is found  so save it for later
 3766:                     if ($file_version > $version) {
 3767: 		        $version = $file_version;
 3768:                     }
 3769: 	        }
 3770:             }
 3771:         }
 3772:     }
 3773:     $version ++;
 3774:     return($version);
 3775: }
 3776: 
 3777: sub version_selected_portfile {
 3778:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3779:     my ($answer_name,$answer_ver,$answer_ext) =
 3780:         &file_name_version_ext($file_name);
 3781:     my $new_answer;
 3782:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3783:     if($env{'form.copy'} eq '-1') {
 3784:         $new_answer = 'problem getting file';
 3785:     } else {
 3786:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3787:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3788:                             $stu_name,$domain,'copy',
 3789: 		        '/portfolio'.$directory.$new_answer);
 3790:     }    
 3791:     return ($new_answer);
 3792: }
 3793: 
 3794: sub file_name_version_ext {
 3795:     my ($file)=@_;
 3796:     my @file_parts = split(/\./, $file);
 3797:     my ($name,$version,$ext);
 3798:     if (@file_parts > 1) {
 3799: 	$ext=pop(@file_parts);
 3800: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3801: 	    $version=pop(@file_parts);
 3802: 	}
 3803: 	$name=join('.',@file_parts);
 3804:     } else {
 3805: 	$name=join('.',@file_parts);
 3806:     }
 3807:     return($name,$version,$ext);
 3808: }
 3809: 
 3810: #--------------------------------------------------------------------------------------
 3811: #
 3812: #-------------------------- Next few routines handles grading by section or whole class
 3813: #
 3814: #--- Javascript to handle grading by section or whole class
 3815: sub viewgrades_js {
 3816:     my ($request) = shift;
 3817: 
 3818:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3819:     &js_escape(\$alertmsg);
 3820:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3821:    function writePoint(partid,weight,point) {
 3822: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3823: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3824: 	if (point == "textval") {
 3825: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3826: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3827: 		alert("$alertmsg"+parseFloat(point));
 3828: 		var resetbox = false;
 3829: 		for (var i=0; i<radioButton.length; i++) {
 3830: 		    if (radioButton[i].checked) {
 3831: 			textbox.value = i;
 3832: 			resetbox = true;
 3833: 		    }
 3834: 		}
 3835: 		if (!resetbox) {
 3836: 		    textbox.value = "";
 3837: 		}
 3838: 		return;
 3839: 	    }
 3840: 	    if (parseFloat(point) > parseFloat(weight)) {
 3841: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3842: 				   ") greater than the weight for the part. Accept?");
 3843: 		if (resp == false) {
 3844: 		    textbox.value = "";
 3845: 		    return;
 3846: 		}
 3847: 	    }
 3848: 	    for (var i=0; i<radioButton.length; i++) {
 3849: 		radioButton[i].checked=false;
 3850: 		if (parseFloat(point) == i) {
 3851: 		    radioButton[i].checked=true;
 3852: 		}
 3853: 	    }
 3854: 
 3855: 	} else {
 3856: 	    textbox.value = parseFloat(point);
 3857: 	}
 3858: 	for (i=0;i<document.classgrade.total.value;i++) {
 3859: 	    var user = document.classgrade["ctr"+i].value;
 3860: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3861: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3862: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3863: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3864: 	    if (saveval != "correct") {
 3865: 		scorename.value = point;
 3866: 		if (selname[0].selected != true) {
 3867: 		    selname[0].selected = true;
 3868: 		}
 3869: 	    }
 3870: 	}
 3871: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3872:     }
 3873: 
 3874:     function writeRadText(partid,weight) {
 3875: 	var selval   = document.classgrade["SELVAL_"+partid];
 3876: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3877:         var override = document.classgrade["FORCE_"+partid].checked;
 3878: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3879: 	if (selval[1].selected || selval[2].selected) {
 3880: 	    for (var i=0; i<radioButton.length; i++) {
 3881: 		radioButton[i].checked=false;
 3882: 
 3883: 	    }
 3884: 	    textbox.value = "";
 3885: 
 3886: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3887: 		var user = document.classgrade["ctr"+i].value;
 3888: 		user = user.replace(new RegExp(':', 'g'),"_");
 3889: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3890: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3891: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3892: 		if ((saveval != "correct") || override) {
 3893: 		    scorename.value = "";
 3894: 		    if (selval[1].selected) {
 3895: 			selname[1].selected = true;
 3896: 		    } else {
 3897: 			selname[2].selected = true;
 3898: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3899: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3900: 		    }
 3901: 		}
 3902: 	    }
 3903: 	} else {
 3904: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3905: 		var user = document.classgrade["ctr"+i].value;
 3906: 		user = user.replace(new RegExp(':', 'g'),"_");
 3907: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3908: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3909: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3910: 		if ((saveval != "correct") || override) {
 3911: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3912: 		    selname[0].selected = true;
 3913: 		}
 3914: 	    }
 3915: 	}	    
 3916:     }
 3917: 
 3918:     function changeSelect(partid,user) {
 3919: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3920: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3921: 	var point  = textbox.value;
 3922: 	var weight = document.classgrade["weight_"+partid].value;
 3923: 
 3924: 	if (isNaN(point) || parseFloat(point) < 0) {
 3925: 	    alert("$alertmsg"+parseFloat(point));
 3926: 	    textbox.value = "";
 3927: 	    return;
 3928: 	}
 3929: 	if (parseFloat(point) > parseFloat(weight)) {
 3930: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3931: 			       ") greater than the weight of the part. Accept?");
 3932: 	    if (resp == false) {
 3933: 		textbox.value = "";
 3934: 		return;
 3935: 	    }
 3936: 	}
 3937: 	selval[0].selected = true;
 3938:     }
 3939: 
 3940:     function changeOneScore(partid,user) {
 3941: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3942: 	if (selval[1].selected || selval[2].selected) {
 3943: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3944: 	    if (selval[2].selected) {
 3945: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3946: 	    }
 3947:         }
 3948:     }
 3949: 
 3950:     function resetEntry(numpart) {
 3951: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3952: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3953: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3954: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3955: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3956: 	    for (var i=0; i<radioButton.length; i++) {
 3957: 		radioButton[i].checked=false;
 3958: 
 3959: 	    }
 3960: 	    textbox.value = "";
 3961: 	    selval[0].selected = true;
 3962: 
 3963: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3964: 		var user = document.classgrade["ctr"+i].value;
 3965: 		user = user.replace(new RegExp(':', 'g'),"_");
 3966: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3967: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3968: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3969: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3970: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3971: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3972: 		if (saveselval == "excused") {
 3973: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3974: 		} else {
 3975: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3976: 		}
 3977: 	    }
 3978: 	}
 3979:     }
 3980: 
 3981: VIEWJAVASCRIPT
 3982: }
 3983: 
 3984: #--- show scores for a section or whole class w/ option to change/update a score
 3985: sub viewgrades {
 3986:     my ($request,$symb) = @_;
 3987:     &viewgrades_js($request);
 3988: 
 3989:     #need to make sure we have the correct data for later EXT calls, 
 3990:     #thus invalidate the cache
 3991:     &Apache::lonnet::devalidatecourseresdata(
 3992:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3993:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3994:     &Apache::lonnet::clear_EXT_cache_status();
 3995: 
 3996:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3997: 
 3998:     #view individual student submission form - called using Javascript viewOneStudent
 3999:     $result.=&jscriptNform($symb);
 4000: 
 4001:     #beginning of class grading form
 4002:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4003:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4004: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4005: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4006: 	&build_section_inputs().
 4007: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4008: 
 4009:     #retrieve selected groups
 4010:     my (@groups,$group_display);
 4011:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4012:     if (grep(/^all$/,@groups)) {
 4013:         @groups = ('all');
 4014:     } elsif (grep(/^none$/,@groups)) {
 4015:         @groups = ('none');
 4016:     } elsif (@groups > 0) {
 4017:         $group_display = join(', ',@groups);
 4018:     }
 4019: 
 4020:     my ($common_header,$specific_header,@sections,$section_display);
 4021:     if ($env{'request.course.sec'} ne '') {
 4022:         @sections = ($env{'request.course.sec'});
 4023:     } else {
 4024:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4025:     }
 4026: 
 4027: # Check if Save button should be usable
 4028:     my $disabled = ' disabled="disabled"';
 4029:     if ($perm{'mgr'}) {
 4030:         if (grep(/^all$/,@sections)) {
 4031:             undef($disabled);
 4032:         } else {
 4033:             foreach my $sec (@sections) {
 4034:                 if (&canmodify($sec)) {
 4035:                     undef($disabled);
 4036:                     last;
 4037:                 }
 4038:             }
 4039:         }
 4040:     }
 4041:     if (grep(/^all$/,@sections)) {
 4042:         @sections = ('all');
 4043:         if ($group_display) {
 4044:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4045:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4046:         } elsif (grep(/^none$/,@groups)) {
 4047:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4048:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4049:         } else {
 4050:             $common_header = &mt('Assign Common Grade to Class');
 4051:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4052:         }
 4053:     } elsif (grep(/^none$/,@sections)) {
 4054:         @sections = ('none');
 4055:         if ($group_display) {
 4056:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4057:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4058:         } elsif (grep(/^none$/,@groups)) {
 4059:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4060:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4061:         } else {
 4062:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4063:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4064:         }
 4065:     } else {
 4066:         $section_display = join (", ",@sections);
 4067:         if ($group_display) {
 4068:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4069:                                  $section_display,$group_display);
 4070:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4071:                                    $section_display,$group_display);
 4072:         } elsif (grep(/^none$/,@groups)) {
 4073:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4074:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4075:         } else {
 4076:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4077:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4078:         }
 4079:     }
 4080:     my %submit_types = &substatus_options();
 4081:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4082: 
 4083:     if ($env{'form.submitonly'} eq 'all') {
 4084:         $result.= '<h3>'.$common_header.'</h3>';
 4085:     } else {
 4086:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 4087:     }
 4088:     $result .= &Apache::loncommon::start_data_table();
 4089:     #radio buttons/text box for assigning points for a section or class.
 4090:     #handles different parts of a problem
 4091:     my $res_error;
 4092:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4093:     if ($res_error) {
 4094:         return &navmap_errormsg();
 4095:     }
 4096:     my %weight = ();
 4097:     my $ctsparts = 0;
 4098:     my %seen = ();
 4099:     my @part_response_id = &flatten_responseType($responseType);
 4100:     foreach my $part_response_id (@part_response_id) {
 4101:     	my ($partid,$respid) = @{ $part_response_id };
 4102: 	my $part_resp = join('_',@{ $part_response_id });
 4103: 	next if $seen{$partid};
 4104: 	$seen{$partid}++;
 4105: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4106: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4107: 
 4108: 	my $display_part=&get_display_part($partid,$symb);
 4109: 	my $radio.='<table border="0"><tr>';  
 4110: 	my $ctr = 0;
 4111: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4112: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4113: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4114: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4115: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4116: 	    $ctr++;
 4117: 	}
 4118: 	$radio.='</tr></table>';
 4119: 	my $line = '<input type="text" name="TEXTVAL_'.
 4120: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4121: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4122: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4123: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4124:                 '<select name="SELVAL_'.$partid.'" '.
 4125: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4126: 		$weight{$partid}.')"> '.
 4127: 	    '<option selected="selected"> </option>'.
 4128: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4129: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4130: 	    '</select></td>'.
 4131:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4132: 	$line.='<input type="hidden" name="partid_'.
 4133: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4134: 	$line.='<input type="hidden" name="weight_'.
 4135: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4136: 
 4137: 	$result.=
 4138: 	    &Apache::loncommon::start_data_table_row()."\n".
 4139: 	    '<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>'.
 4140: 	    &Apache::loncommon::end_data_table_row()."\n";
 4141: 	$ctsparts++;
 4142:     }
 4143:     $result.=&Apache::loncommon::end_data_table()."\n".
 4144: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4145:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4146: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4147: 
 4148:     #table listing all the students in a section/class
 4149:     #header of table
 4150:     if ($env{'form.submitonly'} eq 'all') { 
 4151:         $result.= '<h3>'.$specific_header.'</h3>';
 4152:     } else {
 4153:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 4154:     }
 4155:     $result.= &Apache::loncommon::start_data_table().
 4156: 	      &Apache::loncommon::start_data_table_header_row().
 4157: 	      '<th>'.&mt('No.').'</th>'.
 4158: 	      '<th>'.&nameUserString('header')."</th>\n";
 4159:     my $partserror;
 4160:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4161:     if ($partserror) {
 4162:         return &navmap_errormsg();
 4163:     }
 4164:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4165:     my @partids = ();
 4166:     foreach my $part (@parts) {
 4167: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4168:         my $narrowtext = &mt('Tries');
 4169: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4170: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 4171: 	my ($partid) = &split_part_type($part);
 4172:         push(@partids,$partid);
 4173: #
 4174: # FIXME: Looks like $display looks at English text
 4175: #
 4176: 	my $display_part=&get_display_part($partid,$symb);
 4177: 	if ($display =~ /^Partial Credit Factor/) {
 4178: 	    $result.='<th>'.
 4179:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4180:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4181: 	    next;
 4182: 	    
 4183: 	} else {
 4184: 	    if ($display =~ /Problem Status/) {
 4185: 		my $grade_status_mt = &mt('Grade Status');
 4186: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4187: 	    }
 4188: 	    my $part_mt = &mt('Part:');
 4189: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4190: 	}
 4191: 
 4192: 	$result.='<th>'.$display.'</th>'."\n";
 4193:     }
 4194:     $result.=&Apache::loncommon::end_data_table_header_row();
 4195: 
 4196:     my %last_resets = 
 4197: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4198: 
 4199:     #get info for each student
 4200:     #list all the students - with points and grade status
 4201:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4202:     my $ctr = 0;
 4203:     foreach (sort 
 4204: 	     {
 4205: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4206: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4207: 		 }
 4208: 		 return $a cmp $b;
 4209: 	     } (keys(%$fullname))) {
 4210: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4211: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 4212:     }
 4213:     $result.=&Apache::loncommon::end_data_table();
 4214:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4215:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4216: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4217:     if ($ctr == 0) {
 4218:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4219:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4220:                 '<span class="LC_warning">';
 4221:         if ($env{'form.submitonly'} eq 'all') {
 4222:             if (grep(/^all$/,@sections)) {
 4223:                 if (grep(/^all$/,@groups)) {
 4224:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4225:                                    $stu_status);
 4226:                 } elsif (grep(/^none$/,@groups)) {
 4227:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4228:                                    $stu_status);
 4229:                 } else {
 4230:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4231:                                    $group_display,$stu_status);
 4232:                 }
 4233:             } elsif (grep(/^none$/,@sections)) {
 4234:                 if (grep(/^all$/,@groups)) {
 4235:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4236:                                    $stu_status);
 4237:                 } elsif (grep(/^none$/,@groups)) {
 4238:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4239:                                    $stu_status);
 4240:                 } else {
 4241:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4242:                                    $group_display,$stu_status);
 4243:                 }
 4244:             } else {
 4245:                 if (grep(/^all$/,@groups)) {
 4246:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4247:                                    $section_display,$stu_status);
 4248:                 } elsif (grep(/^none$/,@groups)) {
 4249:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4250:                                    $section_display,$stu_status);
 4251:                 } else {
 4252:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4253:                                    $section_display,$group_display,$stu_status);
 4254:                 }
 4255:             }
 4256:         } else {
 4257:             if (grep(/^all$/,@sections)) {
 4258:                 if (grep(/^all$/,@groups)) {
 4259:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4260:                                    $stu_status,$submission_status);
 4261:                 } elsif (grep(/^none$/,@groups)) {
 4262:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4263:                                    $stu_status,$submission_status);
 4264:                 } else {
 4265:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4266:                                    $group_display,$stu_status,$submission_status);
 4267:                 }
 4268:             } elsif (grep(/^none$/,@sections)) {
 4269:                 if (grep(/^all$/,@groups)) {
 4270:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4271:                                    $stu_status,$submission_status);
 4272:                 } elsif (grep(/^none$/,@groups)) {
 4273:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4274:                                    $stu_status,$submission_status);
 4275:                 } else {
 4276:                     $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.',
 4277:                                    $group_display,$stu_status,$submission_status);
 4278:                 }
 4279:             } else {
 4280:                 if (grep(/^all$/,@groups)) {
 4281:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4282:                                    $section_display,$stu_status,$submission_status);
 4283:                 } elsif (grep(/^none$/,@groups)) {
 4284:                     $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.',
 4285:                                    $section_display,$stu_status,$submission_status);
 4286:                 } else {
 4287:                     $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.',
 4288:                                    $section_display,$group_display,$stu_status,$submission_status);
 4289:                 }
 4290:             }
 4291: 	}
 4292: 	$result .= '</span><br />';
 4293:     }
 4294:     return $result;
 4295: }
 4296: 
 4297: #--- call by previous routine to display each student who satisfies submission filter.
 4298: sub viewstudentgrade {
 4299:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4300:     my ($uname,$udom) = split(/:/,$student);
 4301:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4302:     my $submitonly = $env{'form.submitonly'};
 4303:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4304:         my %partstatus = ();
 4305:         if (ref($parts) eq 'ARRAY') {
 4306:             foreach my $apart (@{$parts}) {
 4307:                 my ($part,$type) = &split_part_type($apart);
 4308:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4309:                 $status = 'nothing' if ($status eq '');
 4310:                 $partstatus{$part}      = $status;
 4311:                 my $subkey = "resource.$part.submitted_by";
 4312:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4313:             }
 4314:             my $submitted = 0;
 4315:             my $graded = 0;
 4316:             my $incorrect = 0;
 4317:             foreach my $key (keys(%partstatus)) {
 4318:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4319:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4320:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4321: 
 4322:                 my $partid = (split(/\./,$key))[1];
 4323:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4324:                     $submitted = 0;
 4325:                 }
 4326:             }
 4327:             return if (!$submitted && ($submitonly eq 'yes' ||
 4328:                                        $submitonly eq 'incorrect' ||
 4329:                                        $submitonly eq 'graded'));
 4330:             return if (!$graded && ($submitonly eq 'graded'));
 4331:             return if (!$incorrect && $submitonly eq 'incorrect');
 4332:         }
 4333:     }
 4334:     if ($submitonly eq 'queued') {
 4335:         my ($cdom,$cnum) = split(/_/,$courseid);
 4336:         my %queue_status =
 4337:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4338:                                                     $udom,$uname);
 4339:         return if (!defined($queue_status{'gradingqueue'}));
 4340:     }
 4341:     $$ctr++;
 4342:     my %aggregates = ();
 4343:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4344: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4345: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4346: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4347: 	'\');" target="_self">'.$fullname.'</a> '.
 4348: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4349:     $student=~s/:/_/; # colon doen't work in javascript for names
 4350:     foreach my $apart (@$parts) {
 4351: 	my ($part,$type) = &split_part_type($apart);
 4352: 	my $score=$record{"resource.$part.$type"};
 4353:         $result.='<td align="center">';
 4354:         my ($aggtries,$totaltries);
 4355:         unless (exists($aggregates{$part})) {
 4356: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4357: 
 4358: 	    $aggtries = $totaltries;
 4359:             if ($$last_resets{$part}) {  
 4360:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4361: 					   $part);
 4362:             }
 4363:             $result.='<input type="hidden" name="'.
 4364:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4365:             $result.='<input type="hidden" name="'.
 4366:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4367:             $aggregates{$part} = 1;
 4368:         }
 4369: 	if ($type eq 'awarded') {
 4370: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4371: 	    $result.='<input type="hidden" name="'.
 4372: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4373: 	    $result.='<input type="text" name="'.
 4374: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4375:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4376: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4377: 	} elsif ($type eq 'solved') {
 4378: 	    my ($status,$foo)=split(/_/,$score,2);
 4379: 	    $status = 'nothing' if ($status eq '');
 4380: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4381: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4382: 	    $result.='&nbsp;<select name="'.
 4383: 		'GD_'.$student.'_'.$part.'_solved" '.
 4384:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4385: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4386: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4387: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4388: 	    $result.="</select>&nbsp;</td>\n";
 4389: 	} else {
 4390: 	    $result.='<input type="hidden" name="'.
 4391: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4392: 		    "\n";
 4393: 	    $result.='<input type="text" name="'.
 4394: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4395: 		'value="'.$score.'" size="4" /></td>'."\n";
 4396: 	}
 4397:     }
 4398:     $result.=&Apache::loncommon::end_data_table_row();
 4399:     return $result;
 4400: }
 4401: 
 4402: #--- change scores for all the students in a section/class
 4403: #    record does not get update if unchanged
 4404: sub editgrades {
 4405:     my ($request,$symb) = @_;
 4406: 
 4407:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4408:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4409:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4410: 
 4411:     my $result= &Apache::loncommon::start_data_table().
 4412: 	&Apache::loncommon::start_data_table_header_row().
 4413: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4414: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4415:     my %scoreptr = (
 4416: 		    'correct'  =>'correct_by_override',
 4417: 		    'incorrect'=>'incorrect_by_override',
 4418: 		    'excused'  =>'excused',
 4419: 		    'ungraded' =>'ungraded_attempted',
 4420:                     'credited' =>'credit_attempted',
 4421: 		    'nothing'  => '',
 4422: 		    );
 4423:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4424: 
 4425:     my (@partid);
 4426:     my %weight = ();
 4427:     my %columns = ();
 4428:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4429: 
 4430:     my $partserror;
 4431:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4432:     if ($partserror) {
 4433:         return &navmap_errormsg();
 4434:     }
 4435:     my $header;
 4436:     while ($ctr < $env{'form.totalparts'}) {
 4437: 	my $partid = $env{'form.partid_'.$ctr};
 4438: 	push(@partid,$partid);
 4439: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4440: 	$ctr++;
 4441:     }
 4442:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4443:     my $totcolspan = 0;
 4444:     foreach my $partid (@partid) {
 4445: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4446: 	    '<th align="center">'.&mt('New Score').'</th>';
 4447: 	$columns{$partid}=2;
 4448: 	foreach my $stores (@parts) {
 4449: 	    my ($part,$type) = &split_part_type($stores);
 4450: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4451: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4452: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4453: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4454:             my $narrowtext = &mt('Tries');
 4455: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4456: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4457: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4458: 	    $columns{$partid}+=2;
 4459: 	}
 4460:         $totcolspan += $columns{$partid};
 4461:     }
 4462:     foreach my $partid (@partid) {
 4463: 	my $display_part=&get_display_part($partid,$symb);
 4464: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4465: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4466: 	    '</th>';
 4467: 
 4468:     }
 4469:     $result .= &Apache::loncommon::end_data_table_header_row().
 4470: 	&Apache::loncommon::start_data_table_header_row().
 4471: 	$header.
 4472: 	&Apache::loncommon::end_data_table_header_row();
 4473:     my @noupdate;
 4474:     my ($updateCtr,$noupdateCtr) = (1,1);
 4475:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4476: 	my $user = $env{'form.ctr'.$i};
 4477: 	my ($uname,$udom)=split(/:/,$user);
 4478: 	my %newrecord;
 4479: 	my $updateflag = 0;
 4480:         my $usec=$classlist->{"$uname:$udom"}[5];
 4481:         my $canmodify = &canmodify($usec);
 4482:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4483:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4484:         if (!$canmodify) {
 4485:             push(@noupdate,
 4486:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4487:                  &mt('Not allowed to modify student')."</span></td>");
 4488:             next;
 4489:         }
 4490:         my %aggregate = ();
 4491:         my $aggregateflag = 0;
 4492: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4493: 	foreach (@partid) {
 4494: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4495: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4496: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4497: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4498: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4499: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4500: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4501: 	    my $score;
 4502: 	    if ($partial eq '') {
 4503: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4504: 	    } elsif ($partial > 0) {
 4505: 		$score = 'correct_by_override';
 4506: 	    } elsif ($partial == 0) {
 4507: 		$score = 'incorrect_by_override';
 4508: 	    }
 4509: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4510: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4511: 
 4512: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4513: 		"$env{'user.name'}:$env{'user.domain'}";
 4514: 	    if ($dropMenu eq 'reset status' &&
 4515: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4516: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4517: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4518: 		$newrecord{'resource.'.$_.'.award'} = '';
 4519: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4520: 		$updateflag = 1;
 4521:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4522:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4523:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4524:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4525:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4526:                     $aggregateflag = 1;
 4527:                 }
 4528: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4529: 		$updateflag = 1;
 4530: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4531: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4532: 		$rec_update++;
 4533: 	    }
 4534: 
 4535: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4536: 		'<td align="center">'.$awarded.
 4537: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4538: 
 4539: 
 4540: 	    my $partid=$_;
 4541: 	    foreach my $stores (@parts) {
 4542: 		my ($part,$type) = &split_part_type($stores);
 4543: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4544: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4545: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4546: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4547: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4548: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4549: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4550: 		    $updateflag=1;
 4551: 		}
 4552: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4553: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4554: 	    }
 4555: 	}
 4556: 	$line.="\n";
 4557: 
 4558: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4559: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4560: 
 4561: 	if ($updateflag) {
 4562: 	    $count++;
 4563: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4564: 				    $udom,$uname);
 4565: 
 4566: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4567: 					      $cnum,$udom,$uname)) {
 4568: 		# need to figure out if should be in queue.
 4569: 		my %record =  
 4570: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4571: 					     $udom,$uname);
 4572: 		my $all_graded = 1;
 4573: 		my $none_graded = 1;
 4574: 		foreach my $part (@parts) {
 4575: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4576: 			$all_graded = 0;
 4577: 		    } else {
 4578: 			$none_graded = 0;
 4579: 		    }
 4580: 		}
 4581: 
 4582: 		if ($all_graded || $none_graded) {
 4583: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4584: 							   $symb,$cdom,$cnum,
 4585: 							   $udom,$uname);
 4586: 		}
 4587: 	    }
 4588: 
 4589: 	    $result.=&Apache::loncommon::start_data_table_row().
 4590: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4591: 		&Apache::loncommon::end_data_table_row();
 4592: 	    $updateCtr++;
 4593: 	} else {
 4594: 	    push(@noupdate,
 4595: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4596: 	    $noupdateCtr++;
 4597: 	}
 4598:         if ($aggregateflag) {
 4599:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4600: 				  $cdom,$cnum);
 4601:         }
 4602:     }
 4603:     if (@noupdate) {
 4604:         my $numcols=$totcolspan+2;
 4605: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4606: 	    '<td align="center" colspan="'.$numcols.'">'.
 4607: 	    &mt('No Changes Occurred For the Students Below').
 4608: 	    '</td>'.
 4609: 	    &Apache::loncommon::end_data_table_row();
 4610: 	foreach my $line (@noupdate) {
 4611: 	    $result.=
 4612: 		&Apache::loncommon::start_data_table_row().
 4613: 		$line.
 4614: 		&Apache::loncommon::end_data_table_row();
 4615: 	}
 4616:     }
 4617:     $result .= &Apache::loncommon::end_data_table();
 4618:     my $msg = '<p><b>'.
 4619: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4620: 	    $rec_update,$count).'</b><br />'.
 4621: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4622: 	'</b></p>';
 4623:     return $title.$msg.$result;
 4624: }
 4625: 
 4626: sub split_part_type {
 4627:     my ($partstr) = @_;
 4628:     my ($temp,@allparts)=split(/_/,$partstr);
 4629:     my $type=pop(@allparts);
 4630:     my $part=join('_',@allparts);
 4631:     return ($part,$type);
 4632: }
 4633: 
 4634: #------------- end of section for handling grading by section/class ---------
 4635: #
 4636: #----------------------------------------------------------------------------
 4637: 
 4638: 
 4639: #----------------------------------------------------------------------------
 4640: #
 4641: #-------------------------- Next few routines handles grading by csv upload
 4642: #
 4643: #--- Javascript to handle csv upload
 4644: sub csvupload_javascript_reverse_associate {
 4645:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4646:     my $error2=&mt('You need to specify at least one grading field');
 4647:   &js_escape(\$error1);
 4648:   &js_escape(\$error2);
 4649:   return(<<ENDPICK);
 4650:   function verify(vf) {
 4651:     var foundsomething=0;
 4652:     var founduname=0;
 4653:     var foundID=0;
 4654:     for (i=0;i<=vf.nfields.value;i++) {
 4655:       tw=eval('vf.f'+i+'.selectedIndex');
 4656:       if (i==0 && tw!=0) { foundID=1; }
 4657:       if (i==1 && tw!=0) { founduname=1; }
 4658:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4659:     }
 4660:     if (founduname==0 && foundID==0) {
 4661: 	alert('$error1');
 4662: 	return;
 4663:     }
 4664:     if (foundsomething==0) {
 4665: 	alert('$error2');
 4666: 	return;
 4667:     }
 4668:     vf.submit();
 4669:   }
 4670:   function flip(vf,tf) {
 4671:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4672:     var i;
 4673:     for (i=0;i<=vf.nfields.value;i++) {
 4674:       //can not pick the same destination field for both name and domain
 4675:       if (((i ==0)||(i ==1)) && 
 4676:           ((tf==0)||(tf==1)) && 
 4677:           (i!=tf) &&
 4678:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4679:         eval('vf.f'+i+'.selectedIndex=0;')
 4680:       }
 4681:     }
 4682:   }
 4683: ENDPICK
 4684: }
 4685: 
 4686: sub csvupload_javascript_forward_associate {
 4687:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4688:     my $error2=&mt('You need to specify at least one grading field');
 4689:   &js_escape(\$error1);
 4690:   &js_escape(\$error2);
 4691:   return(<<ENDPICK);
 4692:   function verify(vf) {
 4693:     var foundsomething=0;
 4694:     var founduname=0;
 4695:     var foundID=0;
 4696:     for (i=0;i<=vf.nfields.value;i++) {
 4697:       tw=eval('vf.f'+i+'.selectedIndex');
 4698:       if (tw==1) { foundID=1; }
 4699:       if (tw==2) { founduname=1; }
 4700:       if (tw>3) { foundsomething=1; }
 4701:     }
 4702:     if (founduname==0 && foundID==0) {
 4703: 	alert('$error1');
 4704: 	return;
 4705:     }
 4706:     if (foundsomething==0) {
 4707: 	alert('$error2');
 4708: 	return;
 4709:     }
 4710:     vf.submit();
 4711:   }
 4712:   function flip(vf,tf) {
 4713:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4714:     var i;
 4715:     //can not pick the same destination field twice
 4716:     for (i=0;i<=vf.nfields.value;i++) {
 4717:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4718:         eval('vf.f'+i+'.selectedIndex=0;')
 4719:       }
 4720:     }
 4721:   }
 4722: ENDPICK
 4723: }
 4724: 
 4725: sub csvuploadmap_header {
 4726:     my ($request,$symb,$datatoken,$distotal)= @_;
 4727:     my $javascript;
 4728:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4729: 	$javascript=&csvupload_javascript_reverse_associate();
 4730:     } else {
 4731: 	$javascript=&csvupload_javascript_forward_associate();
 4732:     }
 4733: 
 4734:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4735:     my $ignore=&mt('Ignore First Line');
 4736:     $symb = &Apache::lonenc::check_encrypt($symb);
 4737:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4738:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4739:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4740:     my $reverse=&mt("Reverse Association");
 4741:     $request->print(<<ENDPICK);
 4742: <br />
 4743: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4744: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4745: <input type="hidden" name="associate"  value="" />
 4746: <input type="hidden" name="phase"      value="three" />
 4747: <input type="hidden" name="datatoken"  value="$datatoken" />
 4748: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4749: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4750: <input type="hidden" name="upfile_associate" 
 4751:                                        value="$env{'form.upfile_associate'}" />
 4752: <input type="hidden" name="symb"       value="$symb" />
 4753: <input type="hidden" name="command"    value="csvuploadoptions" />
 4754: <hr />
 4755: ENDPICK
 4756:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4757:     return '';
 4758: 
 4759: }
 4760: 
 4761: sub csvupload_fields {
 4762:     my ($symb,$errorref) = @_;
 4763:     my (@parts) = &getpartlist($symb,$errorref);
 4764:     if (ref($errorref)) {
 4765:         if ($$errorref) {
 4766:             return;
 4767:         }
 4768:     }
 4769: 
 4770:     my @fields=(['ID','Student/Employee ID'],
 4771: 		['username','Student Username'],
 4772: 		['domain','Student Domain']);
 4773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4774:     foreach my $part (sort(@parts)) {
 4775: 	my @datum;
 4776: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4777: 	my $name=$part;
 4778: 	if  (!$display) { $display = $name; }
 4779: 	@datum=($name,$display);
 4780: 	if ($name=~/^stores_(.*)_awarded/) {
 4781: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4782: 	}
 4783: 	push(@fields,\@datum);
 4784:     }
 4785:     return (@fields);
 4786: }
 4787: 
 4788: sub csvuploadmap_footer {
 4789:     my ($request,$i,$keyfields) =@_;
 4790:     my $buttontext = &mt('Assign Grades');
 4791:     $request->print(<<ENDPICK);
 4792: </table>
 4793: <input type="hidden" name="nfields" value="$i" />
 4794: <input type="hidden" name="keyfields" value="$keyfields" />
 4795: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4796: </form>
 4797: ENDPICK
 4798: }
 4799: 
 4800: sub checkforfile_js {
 4801:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4802:     &js_escape(\$alertmsg);
 4803:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4804:     function checkUpload(formname) {
 4805: 	if (formname.upfile.value == "") {
 4806: 	    alert("$alertmsg");
 4807: 	    return false;
 4808: 	}
 4809: 	formname.submit();
 4810:     }
 4811: CSVFORMJS
 4812:     return $result;
 4813: }
 4814: 
 4815: sub upcsvScores_form {
 4816:     my ($request,$symb) = @_;
 4817:     if (!$symb) {return '';}
 4818:     my $result=&checkforfile_js();
 4819:     $result.=&Apache::loncommon::start_data_table().
 4820:              &Apache::loncommon::start_data_table_header_row().
 4821:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4822:              &Apache::loncommon::end_data_table_header_row().
 4823:              &Apache::loncommon::start_data_table_row().'<td>';
 4824:     my $upload=&mt("Upload Scores");
 4825:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4826:     my $ignore=&mt('Ignore First Line');
 4827:     $symb = &Apache::lonenc::check_encrypt($symb);
 4828:     $result.=<<ENDUPFORM;
 4829: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4830: <input type="hidden" name="symb" value="$symb" />
 4831: <input type="hidden" name="command" value="csvuploadmap" />
 4832: $upfile_select
 4833: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4834: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4835: </form>
 4836: ENDUPFORM
 4837:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4838:                            &mt("How do I create a CSV file from a spreadsheet")).
 4839:             '</td>'.
 4840:             &Apache::loncommon::end_data_table_row().
 4841:             &Apache::loncommon::end_data_table();
 4842:     return $result;
 4843: }
 4844: 
 4845: 
 4846: sub csvuploadmap {
 4847:     my ($request,$symb) = @_;
 4848:     if (!$symb) {return '';}
 4849: 
 4850:     my $datatoken;
 4851:     if (!$env{'form.datatoken'}) {
 4852: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4853:     } else {
 4854:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4855:         if ($datatoken ne '') { 
 4856: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4857:         }
 4858:     }
 4859:     my @records=&Apache::loncommon::upfile_record_sep();
 4860:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4861:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4862:     my ($i,$keyfields);
 4863:     if (@records) {
 4864:         my $fieldserror;
 4865: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4866:         if ($fieldserror) {
 4867:             $request->print(&navmap_errormsg());
 4868:             return;
 4869:         }
 4870: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4871: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4872: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4873: 							  \@fields);
 4874: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4875: 	    chop($keyfields);
 4876: 	} else {
 4877: 	    unshift(@fields,['none','']);
 4878: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4879: 							    \@fields);
 4880:             foreach my $rec (@records) {
 4881:                 my %temp = &Apache::loncommon::record_sep($rec);
 4882:                 if (%temp) {
 4883:                     $keyfields=join(',',sort(keys(%temp)));
 4884:                     last;
 4885:                 }
 4886:             }
 4887: 	}
 4888:     }
 4889:     &csvuploadmap_footer($request,$i,$keyfields);
 4890: 
 4891:     return '';
 4892: }
 4893: 
 4894: sub csvuploadoptions {
 4895:     my ($request,$symb)= @_;
 4896:     my $overwrite=&mt('Overwrite any existing score');
 4897:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4898:     my $ignore=&mt('Ignore First Line');
 4899:     $request->print(<<ENDPICK);
 4900: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4901: <input type="hidden" name="command"    value="csvuploadassign" />
 4902: <p>
 4903: <label>
 4904:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4905:    $overwrite
 4906: </label>
 4907: </p>
 4908: ENDPICK
 4909:     my %fields=&get_fields();
 4910:     if (!defined($fields{'domain'})) {
 4911: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4912:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4913:     }
 4914:     foreach my $key (sort(keys(%env))) {
 4915: 	if ($key !~ /^form\.(.*)$/) { next; }
 4916: 	my $cleankey=$1;
 4917: 	if ($cleankey eq 'command') { next; }
 4918: 	$request->print('<input type="hidden" name="'.$cleankey.
 4919: 			'"  value="'.$env{$key}.'" />'."\n");
 4920:     }
 4921:     # FIXME do a check for any duplicated user ids...
 4922:     # FIXME do a check for any invalid user ids?...
 4923:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4924: <hr /></form>'."\n");
 4925:     return '';
 4926: }
 4927: 
 4928: sub get_fields {
 4929:     my %fields;
 4930:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4931:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4932: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4933: 	    if ($env{'form.f'.$i} ne 'none') {
 4934: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4935: 	    }
 4936: 	} else {
 4937: 	    if ($env{'form.f'.$i} ne 'none') {
 4938: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4939: 	    }
 4940: 	}
 4941:     }
 4942:     return %fields;
 4943: }
 4944: 
 4945: sub csvuploadassign {
 4946:     my ($request,$symb) = @_;
 4947:     if (!$symb) {return '';}
 4948:     my $error_msg = '';
 4949:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4950:     if ($datatoken ne '') {
 4951:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4952:     }
 4953:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4954:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4955:     my %fields=&get_fields();
 4956:     my $courseid=$env{'request.course.id'};
 4957:     my ($classlist) = &getclasslist('all',0);
 4958:     my @notallowed;
 4959:     my @skipped;
 4960:     my @warnings;
 4961:     my $countdone=0;
 4962:     foreach my $grade (@gradedata) {
 4963: 	my %entries=&Apache::loncommon::record_sep($grade);
 4964: 	my $domain;
 4965: 	if ($entries{$fields{'domain'}}) {
 4966: 	    $domain=$entries{$fields{'domain'}};
 4967: 	} else {
 4968: 	    $domain=$env{'form.default_domain'};
 4969: 	}
 4970: 	$domain=~s/\s//g;
 4971: 	my $username=$entries{$fields{'username'}};
 4972: 	$username=~s/\s//g;
 4973: 	if (!$username) {
 4974: 	    my $id=$entries{$fields{'ID'}};
 4975: 	    $id=~s/\s//g;
 4976: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4977: 	    $username=$ids{$id};
 4978: 	}
 4979: 	if (!exists($$classlist{"$username:$domain"})) {
 4980: 	    my $id=$entries{$fields{'ID'}};
 4981: 	    $id=~s/\s//g;
 4982: 	    if ($id) {
 4983: 		push(@skipped,"$id:$domain");
 4984: 	    } else {
 4985: 		push(@skipped,"$username:$domain");
 4986: 	    }
 4987: 	    next;
 4988: 	}
 4989: 	my $usec=$classlist->{"$username:$domain"}[5];
 4990: 	if (!&canmodify($usec)) {
 4991: 	    push(@notallowed,"$username:$domain");
 4992: 	    next;
 4993: 	}
 4994: 	my %points;
 4995: 	my %grades;
 4996: 	foreach my $dest (keys(%fields)) {
 4997: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4998: 		$dest eq 'domain') { next; }
 4999: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5000: 	    if ($dest=~/stores_(.*)_points/) {
 5001: 		my $part=$1;
 5002: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5003: 					      $symb,$domain,$username);
 5004:                 if ($wgt) {
 5005:                     $entries{$fields{$dest}}=~s/\s//g;
 5006:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5007:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5008:                                           : 'correct_by_override';
 5009:                     if ($pcr>1) {
 5010:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5011:                     }
 5012:                     $grades{"resource.$part.awarded"}=$pcr;
 5013:                     $grades{"resource.$part.solved"}=$award;
 5014:                     $points{$part}=1;
 5015:                 } else {
 5016:                     $error_msg = "<br />" .
 5017:                         &mt("Some point values were assigned"
 5018:                             ." for problems with a weight "
 5019:                             ."of zero. These values were "
 5020:                             ."ignored.");
 5021:                 }
 5022: 	    } else {
 5023: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5024: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5025: 		my $store_key=$dest;
 5026: 		$store_key=~s/^stores/resource/;
 5027: 		$store_key=~s/_/\./g;
 5028: 		$grades{$store_key}=$entries{$fields{$dest}};
 5029: 	    }
 5030: 	}
 5031: 	if (! %grades) {
 5032:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5033:         } else {
 5034: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5035: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5036: 					   $env{'request.course.id'},
 5037: 					   $domain,$username);
 5038: 	   if ($result eq 'ok') {
 5039: # Successfully stored
 5040: 	      $request->print('.');
 5041: # Remove from grading queue
 5042:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5043:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5044:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5045:                                              $domain,$username);
 5046: 	   } else {
 5047: 	      $request->print("<p><span class=\"LC_error\">".
 5048:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5049:                                   "$username:$domain",$result)."</span></p>");
 5050: 	   }
 5051: 	   $request->rflush();
 5052: 	   $countdone++;
 5053:         }
 5054:     }
 5055:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5056:     if (@warnings) {
 5057:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5058:         $request->print(join(', ',@warnings));
 5059:     }
 5060:     if (@skipped) {
 5061: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5062:         $request->print(join(', ',@skipped));
 5063:     }
 5064:     if (@notallowed) {
 5065: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5066: 	$request->print(join(', ',@notallowed));
 5067:     }
 5068:     $request->print("<br />\n");
 5069:     return $error_msg;
 5070: }
 5071: #------------- end of section for handling csv file upload ---------
 5072: #
 5073: #-------------------------------------------------------------------
 5074: #
 5075: #-------------- Next few routines handle grading by page/sequence
 5076: #
 5077: #--- Select a page/sequence and a student to grade
 5078: sub pickStudentPage {
 5079:     my ($request,$symb) = @_;
 5080: 
 5081:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5082:     &js_escape(\$alertmsg);
 5083:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5084: 
 5085: function checkPickOne(formname) {
 5086:     if (radioSelection(formname.student) == null) {
 5087: 	alert("$alertmsg");
 5088: 	return;
 5089:     }
 5090:     ptr = pullDownSelection(formname.selectpage);
 5091:     formname.page.value = formname["page"+ptr].value;
 5092:     formname.title.value = formname["title"+ptr].value;
 5093:     formname.submit();
 5094: }
 5095: 
 5096: LISTJAVASCRIPT
 5097:     &commonJSfunctions($request);
 5098: 
 5099:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5100:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5101:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5102:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5103: 
 5104:     my $result='<h3><span class="LC_info">&nbsp;'.
 5105: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5106: 
 5107:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5108:     my $map_error;
 5109:     my ($titles,$symbx) = &getSymbMap($map_error);
 5110:     if ($map_error) {
 5111:         $request->print(&navmap_errormsg());
 5112:         return; 
 5113:     }
 5114:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5115: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5116: #    my $type=($curpage =~ /\.(page|sequence)/);
 5117: 
 5118:     # Collection of hidden fields
 5119:     my $ctr=0;
 5120:     foreach (@$titles) {
 5121: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5122: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5123: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5124: 	$ctr++;
 5125:     }
 5126:     $result.='<input type="hidden" name="page" />'."\n".
 5127: 	'<input type="hidden" name="title" />'."\n";
 5128: 
 5129:     $result.=&build_section_inputs();
 5130:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5131:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5132:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5133:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5134: 
 5135:     # Show grading options
 5136:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5137:     my $select = '<select name="selectpage">'."\n";
 5138:     $ctr=0;
 5139:     foreach (@$titles) {
 5140:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5141:         $select.='<option value="'.$ctr.'"'.
 5142:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5143:             '>'.$showtitle.'</option>'."\n";
 5144:         $ctr++;
 5145:     }
 5146:     $select.= '</select>';
 5147: 
 5148:     $result.=
 5149:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5150:        .$select
 5151:        .&Apache::lonhtmlcommon::row_closure();
 5152: 
 5153:     $result.=
 5154:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5155:        .'<label><input type="radio" name="vProb" value="no"'
 5156:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5157:        .'<label><input type="radio" name="vProb" value="yes" />'
 5158:            .&mt('yes').'</label>'."\n"
 5159:        .&Apache::lonhtmlcommon::row_closure();
 5160: 
 5161:     $result.=
 5162:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5163:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5164:            .&mt('none').' </label>'."\n"
 5165:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5166:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5167:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5168:            .&mt('all submissions with details').' </label>'
 5169:        .&Apache::lonhtmlcommon::row_closure();
 5170: 
 5171:     $result.=
 5172:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5173:        .'<input type="text" name="CODE" value="" />'
 5174:        .&Apache::lonhtmlcommon::row_closure(1)
 5175:        .&Apache::lonhtmlcommon::end_pick_box();
 5176: 
 5177:     # Show list of students to select for grading
 5178:     $result.='<br /><input type="button" '.
 5179:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5180: 
 5181:     $request->print($result);
 5182: 
 5183:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5184: 	&Apache::loncommon::start_data_table().
 5185: 	&Apache::loncommon::start_data_table_header_row().
 5186: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5187: 	'<th>'.&nameUserString('header').'</th>'.
 5188: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5189: 	'<th>'.&nameUserString('header').'</th>'.
 5190: 	&Apache::loncommon::end_data_table_header_row();
 5191:  
 5192:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5193:     my $ptr = 1;
 5194:     foreach my $student (sort 
 5195: 			 {
 5196: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5197: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5198: 			     }
 5199: 			     return $a cmp $b;
 5200: 			 } (keys(%$fullname))) {
 5201: 	my ($uname,$udom) = split(/:/,$student);
 5202: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5203:                                   : '</td>');
 5204: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5205: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5206: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5207: 	$studentTable.=
 5208: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5209:                          : '');
 5210: 	$ptr++;
 5211:     }
 5212:     if ($ptr%2 == 0) {
 5213: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5214: 	    &Apache::loncommon::end_data_table_row();
 5215:     }
 5216:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5217:     $studentTable.='<input type="button" '.
 5218:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5219: 
 5220:     $request->print($studentTable);
 5221: 
 5222:     return '';
 5223: }
 5224: 
 5225: sub getSymbMap {
 5226:     my ($map_error) = @_;
 5227:     my $navmap = Apache::lonnavmaps::navmap->new();
 5228:     unless (ref($navmap)) {
 5229:         if (ref($map_error)) {
 5230:             $$map_error = 'navmap';
 5231:         }
 5232:         return;
 5233:     }
 5234:     my %symbx = ();
 5235:     my @titles = ();
 5236:     my $minder = 0;
 5237: 
 5238:     # Gather every sequence that has problems.
 5239:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5240: 					       1,0,1);
 5241:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5242: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5243: 	    my $title = $minder.'.'.
 5244: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5245: 	    push(@titles, $title); # minder in case two titles are identical
 5246: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5247: 	    $minder++;
 5248: 	}
 5249:     }
 5250:     return \@titles,\%symbx;
 5251: }
 5252: 
 5253: #
 5254: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5255: sub displayPage {
 5256:     my ($request,$symb) = @_;
 5257:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5258:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5259:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5260:     my $pageTitle = $env{'form.page'};
 5261:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5262:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5263:     my $usec=$classlist->{$env{'form.student'}}[5];
 5264: 
 5265:     #need to make sure we have the correct data for later EXT calls, 
 5266:     #thus invalidate the cache
 5267:     &Apache::lonnet::devalidatecourseresdata(
 5268:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5269:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5270:     &Apache::lonnet::clear_EXT_cache_status();
 5271: 
 5272:     if (!&canview($usec)) {
 5273: 	$request->print(
 5274:             '<span class="LC_warning">'.
 5275:             &mt('Unable to view requested student. ([_1])',
 5276:                 $env{'form.student'}).
 5277:             '</span>');
 5278:         return;
 5279:     }
 5280:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5281:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5282: 	'</h3>'."\n";
 5283:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5284:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5285: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5286:     } else {
 5287: 	delete($env{'form.CODE'});
 5288:     }
 5289:     &sub_page_js($request);
 5290:     $request->print($result);
 5291: 
 5292:     my $navmap = Apache::lonnavmaps::navmap->new();
 5293:     unless (ref($navmap)) {
 5294:         $request->print(&navmap_errormsg());
 5295:         return;
 5296:     }
 5297:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5298:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5299:     if (!$map) {
 5300: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5301: 	return; 
 5302:     }
 5303:     my $iterator = $navmap->getIterator($map->map_start(),
 5304: 					$map->map_finish());
 5305: 
 5306:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5307: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5308: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5309: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5310: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5311: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5312: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5313: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5314: 
 5315:     if (defined($env{'form.CODE'})) {
 5316: 	$studentTable.=
 5317: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5318:     }
 5319:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5320: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5321: 
 5322:     $studentTable.='&nbsp;<span class="LC_info">'.
 5323:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5324:         '</span>'."\n".
 5325: 	&Apache::loncommon::start_data_table().
 5326: 	&Apache::loncommon::start_data_table_header_row().
 5327: 	'<th>'.&mt('Prob.').'</th>'.
 5328: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5329: 	&Apache::loncommon::end_data_table_header_row();
 5330: 
 5331:     &Apache::lonxml::clear_problem_counter();
 5332:     my ($depth,$question,$prob) = (1,1,1);
 5333:     $iterator->next(); # skip the first BEGIN_MAP
 5334:     my $curRes = $iterator->next(); # for "current resource"
 5335:     while ($depth > 0) {
 5336:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5337:         if($curRes == $iterator->END_MAP) { $depth--; }
 5338: 
 5339:         if (ref($curRes) && $curRes->is_problem()) {
 5340: 	    my $parts = $curRes->parts();
 5341:             my $title = $curRes->compTitle();
 5342: 	    my $symbx = $curRes->symb();
 5343: 	    $studentTable.=
 5344: 		&Apache::loncommon::start_data_table_row().
 5345: 		'<td align="center" valign="top" >'.$prob.
 5346: 		(scalar(@{$parts}) == 1 ? '' 
 5347: 		                        : '<br />('.&mt('[_1]parts',
 5348: 							scalar(@{$parts}).'&nbsp;').')'
 5349: 		 ).
 5350: 		 '</td>';
 5351: 	    $studentTable.='<td valign="top">';
 5352: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5353: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5354: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5355: 					     undef,'both',\%form);
 5356: 	    } else {
 5357: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5358: 		$companswer =~ s|<form(.*?)>||g;
 5359: 		$companswer =~ s|</form>||g;
 5360: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5361: #		    $companswer =~ s/$1/ /ms;
 5362: #		    $request->print('match='.$1."<br />\n");
 5363: #		}
 5364: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5365: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5366: 	    }
 5367: 
 5368: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5369: 
 5370: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5371: 		if ($record{'version'} eq '') {
 5372: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5373: 		} else {
 5374: 		    my %responseType = ();
 5375: 		    foreach my $partid (@{$parts}) {
 5376: 			my @responseIds =$curRes->responseIds($partid);
 5377: 			my @responseType =$curRes->responseType($partid);
 5378: 			my %responseIds;
 5379: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5380: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5381: 			}
 5382: 			$responseType{$partid} = \%responseIds;
 5383: 		    }
 5384: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5385: 
 5386: 		}
 5387: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5388: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5389:                 my $identifier = (&canmodify($usec)? $prob : '');
 5390: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5391: 									$env{'request.course.id'},
 5392: 									'','.submission',undef,
 5393:                                                                         $usec,$identifier);
 5394:  
 5395: 	    }
 5396: 	    if (&canmodify($usec)) {
 5397:             $studentTable.=&gradeBox_start();
 5398: 		foreach my $partid (@{$parts}) {
 5399: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5400: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5401: 		    $question++;
 5402: 		}
 5403:             $studentTable.=&gradeBox_end();
 5404: 		$prob++;
 5405: 	    }
 5406: 	    $studentTable.='</td></tr>';
 5407: 
 5408: 	}
 5409:         $curRes = $iterator->next();
 5410:     }
 5411:     my $disabled;
 5412:     unless (&canmodify($usec)) {
 5413:         $disabled = ' disabled="disabled"';
 5414:     }
 5415: 
 5416:     $studentTable.=
 5417:         '</table>'."\n".
 5418:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5419:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5420:         '</form>'."\n";
 5421:     $request->print($studentTable);
 5422: 
 5423:     return '';
 5424: }
 5425: 
 5426: sub displaySubByDates {
 5427:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5428:     my $isCODE=0;
 5429:     my $isTask = ($symb =~/\.task$/);
 5430:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5431:     my $studentTable=&Apache::loncommon::start_data_table().
 5432: 	&Apache::loncommon::start_data_table_header_row().
 5433: 	'<th>'.&mt('Date/Time').'</th>'.
 5434: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5435:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5436: 	'<th>'.&mt('Submission').'</th>'.
 5437: 	'<th>'.&mt('Status').'</th>'.
 5438: 	&Apache::loncommon::end_data_table_header_row();
 5439:     my ($version);
 5440:     my %mark;
 5441:     my %orders;
 5442:     $mark{'correct_by_student'} = $checkIcon;
 5443:     if (!exists($$record{'1:timestamp'})) {
 5444: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5445:     }
 5446: 
 5447:     my $interaction;
 5448:     my $no_increment = 1;
 5449:     my (%lastrndseed,%lasttype);
 5450:     for ($version=1;$version<=$$record{'version'};$version++) {
 5451: 	my $timestamp = 
 5452: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5453: 	if (exists($$record{$version.':resource.0.version'})) {
 5454: 	    $interaction = $$record{$version.':resource.0.version'};
 5455: 	}
 5456:         if ($isTask && $env{'form.previousversion'}) {
 5457:             next unless ($interaction == $env{'form.previousversion'});
 5458:         }
 5459: 	my $where = ($isTask ? "$version:resource.$interaction"
 5460: 		             : "$version:resource");
 5461: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5462: 	    '<td>'.$timestamp.'</td>';
 5463: 	if ($isCODE) {
 5464: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5465: 	}
 5466:         if ($isTask) {
 5467:             $studentTable.='<td>'.$interaction.'</td>';
 5468:         }
 5469: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5470: 	my @displaySub = ();
 5471: 	foreach my $partid (@{$parts}) {
 5472:             my ($hidden,$type);
 5473:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5474:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5475:                 $hidden = 1;
 5476:             }
 5477: 	    my @matchKey;
 5478:             if ($isTask) {
 5479:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5480:             } else {
 5481: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5482:             }
 5483: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5484: 	    my $display_part=&get_display_part($partid,$symb);
 5485: 	    foreach my $matchKey (@matchKey) {
 5486: 		if (exists($$record{$version.':'.$matchKey}) &&
 5487: 		    $$record{$version.':'.$matchKey} ne '') {
 5488:                     
 5489: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5490: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5491:                     $displaySub[0].='<span class="LC_nobreak">';
 5492:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5493:                                    .' <span class="LC_internal_info">'
 5494:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5495:                                    .'</span>'
 5496:                                    .' <b>';
 5497:                     if ($hidden) {
 5498:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5499:                     } else {
 5500:                         my ($trial,$rndseed,$newvariation);
 5501:                         if ($type eq 'randomizetry') {
 5502:                             $trial = $$record{"$where.$partid.tries"};
 5503:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5504:                         }
 5505: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5506: 			    $displaySub[0].=&mt('Trial not counted');
 5507: 		        } else {
 5508: 			    $displaySub[0].=&mt('Trial: [_1]',
 5509: 					    $$record{"$where.$partid.tries"});
 5510:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5511:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5512:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5513:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5514:                                 }
 5515:                             }
 5516:                             $lastrndseed{$partid} = $rndseed;
 5517:                             $lasttype{$partid} = $type;
 5518: 		        }
 5519: 		        my $responseType=($isTask ? 'Task'
 5520:                                               : $responseType->{$partid}->{$responseId});
 5521: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5522: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5523: 			    $orders{$partid}->{$responseId}=
 5524: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5525:                                            $no_increment,$type,$trial,$rndseed);
 5526: 		        }
 5527: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5528: 		        $displaySub[0].='&nbsp; '.
 5529: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5530:                     }
 5531: 		}
 5532: 	    }
 5533: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5534: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5535: 				    $$record{"$where.$partid.checkedin"},
 5536: 				    $$record{"$where.$partid.checkedin.slot"}).
 5537: 					'<br />';
 5538: 	    }
 5539: 	    if (exists $$record{"$where.$partid.award"}) {
 5540: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5541: 		    lc($$record{"$where.$partid.award"}).' '.
 5542: 		    $mark{$$record{"$where.$partid.solved"}}.
 5543: 		    '<br />';
 5544: 	    }
 5545: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5546: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5547: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5548: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5549: 		$displaySub[2].=
 5550: 		    $$record{"$version:resource.$partid.regrader"}.
 5551: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5552: 	    }
 5553: 	}
 5554: 	# needed because old essay regrader has not parts info
 5555: 	if (exists $$record{"$version:resource.regrader"}) {
 5556: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5557: 	}
 5558: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5559: 	if ($displaySub[2]) {
 5560: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5561: 	}
 5562: 	$studentTable.='&nbsp;</td>'.
 5563: 	    &Apache::loncommon::end_data_table_row();
 5564:     }
 5565:     $studentTable.=&Apache::loncommon::end_data_table();
 5566:     return $studentTable;
 5567: }
 5568: 
 5569: sub updateGradeByPage {
 5570:     my ($request,$symb) = @_;
 5571: 
 5572:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5573:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5574:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5575:     my $pageTitle = $env{'form.page'};
 5576:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5577:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5578:     my $usec=$classlist->{$env{'form.student'}}[5];
 5579:     if (!&canmodify($usec)) {
 5580: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5581: 	return;
 5582:     }
 5583:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5584:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5585: 	'</h3>'."\n";
 5586: 
 5587:     $request->print($result);
 5588: 
 5589: 
 5590:     my $navmap = Apache::lonnavmaps::navmap->new();
 5591:     unless (ref($navmap)) {
 5592:         $request->print(&navmap_errormsg());
 5593:         return;
 5594:     }
 5595:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5596:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5597:     if (!$map) {
 5598: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5599: 	return; 
 5600:     }
 5601:     my $iterator = $navmap->getIterator($map->map_start(),
 5602: 					$map->map_finish());
 5603: 
 5604:     my $studentTable=
 5605: 	&Apache::loncommon::start_data_table().
 5606: 	&Apache::loncommon::start_data_table_header_row().
 5607: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5608: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5609: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5610: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5611: 	&Apache::loncommon::end_data_table_header_row();
 5612: 
 5613:     $iterator->next(); # skip the first BEGIN_MAP
 5614:     my $curRes = $iterator->next(); # for "current resource"
 5615:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5616:     while ($depth > 0) {
 5617:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5618:         if($curRes == $iterator->END_MAP) { $depth--; }
 5619: 
 5620:         if (ref($curRes) && $curRes->is_problem()) {
 5621: 	    my $parts = $curRes->parts();
 5622:             my $title = $curRes->compTitle();
 5623: 	    my $symbx = $curRes->symb();
 5624: 	    $studentTable.=
 5625: 		&Apache::loncommon::start_data_table_row().
 5626: 		'<td align="center" valign="top" >'.$prob.
 5627: 		(scalar(@{$parts}) == 1 ? '' 
 5628:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5629: 		.')').'</td>';
 5630: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5631: 
 5632: 	    my %newrecord=();
 5633: 	    my @displayPts=();
 5634:             my %aggregate = ();
 5635:             my $aggregateflag = 0;
 5636:             if ($env{'form.HIDE'.$prob}) {
 5637:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5638:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5639:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5640:                 $hideflag += $numchgs;
 5641:             }
 5642: 	    foreach my $partid (@{$parts}) {
 5643: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5644: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5645: 
 5646: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5647: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5648: 		my $partial = $newpts/$wgt;
 5649: 		my $score;
 5650: 		if ($partial > 0) {
 5651: 		    $score = 'correct_by_override';
 5652: 		} elsif ($newpts ne '') { #empty is taken as 0
 5653: 		    $score = 'incorrect_by_override';
 5654: 		}
 5655: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5656: 		if ($dropMenu eq 'excused') {
 5657: 		    $partial = '';
 5658: 		    $score = 'excused';
 5659: 		} elsif ($dropMenu eq 'reset status'
 5660: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5661: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5662: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5663: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5664: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5665: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5666: 		    $changeflag++;
 5667: 		    $newpts = '';
 5668:                     
 5669:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5670:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5671:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5672:                     if ($aggtries > 0) {
 5673:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5674:                         $aggregateflag = 1;
 5675:                     }
 5676: 		}
 5677: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5678: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5679: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5680: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5681: 		    '&nbsp;<br />';
 5682: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5683: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5684: 		    '&nbsp;<br />';
 5685: 		$question++;
 5686: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5687: 
 5688: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5689: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5690: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5691: 		    if (scalar(keys(%newrecord)) > 0);
 5692: 
 5693: 		$changeflag++;
 5694: 	    }
 5695: 	    if (scalar(keys(%newrecord)) > 0) {
 5696: 		my %record = 
 5697: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5698: 					     $udom,$uname);
 5699: 
 5700: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5701: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5702: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5703: 		    $newrecord{'resource.CODE'} = '';
 5704: 		}
 5705: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5706: 					$udom,$uname);
 5707: 		%record = &Apache::lonnet::restore($symbx,
 5708: 						   $env{'request.course.id'},
 5709: 						   $udom,$uname);
 5710: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5711: 					     $cdom,$cnum,$udom,$uname);
 5712: 	    }
 5713: 	    
 5714:             if ($aggregateflag) {
 5715:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5716:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5717:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5718:             }
 5719: 
 5720: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5721: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5722: 		&Apache::loncommon::end_data_table_row();
 5723: 
 5724: 	    $prob++;
 5725: 	}
 5726:         $curRes = $iterator->next();
 5727:     }
 5728: 
 5729:     $studentTable.=&Apache::loncommon::end_data_table();
 5730:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5731: 		  &mt('The scores were changed for [quant,_1,problem].',
 5732: 		  $changeflag).'<br />');
 5733:     my $hidemsg=($hideflag == 0 ? '' :
 5734:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5735:                      $hideflag).'<br />');
 5736:     $request->print($hidemsg.$grademsg.$studentTable);
 5737: 
 5738:     return '';
 5739: }
 5740: 
 5741: #-------- end of section for handling grading by page/sequence ---------
 5742: #
 5743: #-------------------------------------------------------------------
 5744: 
 5745: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5746: #
 5747: #------ start of section for handling grading by page/sequence ---------
 5748: 
 5749: =pod
 5750: 
 5751: =head1 Bubble sheet grading routines
 5752: 
 5753:   For this documentation:
 5754: 
 5755:    'scanline' refers to the full line of characters
 5756:    from the file that we are parsing that represents one entire sheet
 5757: 
 5758:    'bubble line' refers to the data
 5759:    representing the line of bubbles that are on the physical bubblesheet
 5760: 
 5761: 
 5762: The overall process is that a scanned in bubblesheet data is uploaded
 5763: into a course. When a user wants to grade, they select a
 5764: sequence/folder of resources, a file of bubblesheet info, and pick
 5765: one of the predefined configurations for what each scanline looks
 5766: like.
 5767: 
 5768: Next each scanline is checked for any errors of either 'missing
 5769: bubbles' (it's an error because it may have been mis-scanned
 5770: because too light bubbling), 'double bubble' (each bubble line should
 5771: have no more than one letter picked), invalid or duplicated CODE,
 5772: invalid student/employee ID
 5773: 
 5774: If the CODE option is used that determines the randomization of the
 5775: homework problems, either way the student/employee ID is looked up into a
 5776: username:domain.
 5777: 
 5778: During the validation phase the instructor can choose to skip scanlines. 
 5779: 
 5780: After the validation phase, there are now 3 bubblesheet files
 5781: 
 5782:   scantron_original_filename (unmodified original file)
 5783:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5784:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5785: 
 5786: Also there is a separate hash nohist_scantrondata that contains extra
 5787: correction information that isn't representable in the bubblesheet
 5788: file (see &scantron_getfile() for more information)
 5789: 
 5790: After all scanlines are either valid, marked as valid or skipped, then
 5791: foreach line foreach problem in the picked sequence, an ssi request is
 5792: made that simulates a user submitting their selected letter(s) against
 5793: the homework problem.
 5794: 
 5795: =over 4
 5796: 
 5797: 
 5798: 
 5799: =item defaultFormData
 5800: 
 5801:   Returns html hidden inputs used to hold context/default values.
 5802: 
 5803:  Arguments:
 5804:   $symb - $symb of the current resource 
 5805: 
 5806: =cut
 5807: 
 5808: sub defaultFormData {
 5809:     my ($symb)=@_;
 5810:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5811: }
 5812: 
 5813: 
 5814: =pod 
 5815: 
 5816: =item getSequenceDropDown
 5817: 
 5818:    Return html dropdown of possible sequences to grade
 5819:  
 5820:  Arguments:
 5821:    $symb - $symb of the current resource
 5822:    $map_error - ref to scalar which will container error if
 5823:                 $navmap object is unavailable in &getSymbMap().
 5824: 
 5825: =cut
 5826: 
 5827: sub getSequenceDropDown {
 5828:     my ($symb,$map_error)=@_;
 5829:     my $result='<select name="selectpage">'."\n";
 5830:     my ($titles,$symbx) = &getSymbMap($map_error);
 5831:     if (ref($map_error)) {
 5832:         return if ($$map_error);
 5833:     }
 5834:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5835:     my $ctr=0;
 5836:     foreach (@$titles) {
 5837: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5838: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5839: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5840: 	    '>'.$showtitle.'</option>'."\n";
 5841: 	$ctr++;
 5842:     }
 5843:     $result.= '</select>';
 5844:     return $result;
 5845: }
 5846: 
 5847: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5848:                                    # key is zero-based index - 0, 1, 2 ...
 5849: 
 5850: my %first_bubble_line;             # First bubble line no. for each bubble.
 5851: 
 5852: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5853:                                    # matchresponse or rankresponse, where 
 5854:                                    # an individual response can have multiple 
 5855:                                    # lines
 5856: 
 5857: my %responsetype_per_response;     # responsetype for each response
 5858: 
 5859: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5860:                                    # numbered response. Needed when randomorder
 5861:                                    # or randompick are in use. Key is ID, value 
 5862:                                    # is response number.
 5863: 
 5864: # Save and restore the bubble lines array to the form env.
 5865: 
 5866: 
 5867: sub save_bubble_lines {
 5868:     foreach my $line (keys(%bubble_lines_per_response)) {
 5869: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5870: 	$env{"form.scantron.first_bubble_line.$line"} =
 5871: 	    $first_bubble_line{$line};
 5872:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5873:             $subdivided_bubble_lines{$line};
 5874:         $env{"form.scantron.responsetype.$line"} =
 5875:             $responsetype_per_response{$line};
 5876:     }
 5877:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5878:         my $line = $masterseq_id_responsenum{$resid};
 5879:         $env{"form.scantron.residpart.$line"} = $resid;
 5880:     }
 5881: }
 5882: 
 5883: 
 5884: sub restore_bubble_lines {
 5885:     my $line = 0;
 5886:     %bubble_lines_per_response = ();
 5887:     %masterseq_id_responsenum = ();
 5888:     while ($env{"form.scantron.bubblelines.$line"}) {
 5889: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5890: 	$bubble_lines_per_response{$line} = $value;
 5891: 	$first_bubble_line{$line}  =
 5892: 	    $env{"form.scantron.first_bubble_line.$line"};
 5893:         $subdivided_bubble_lines{$line} =
 5894:             $env{"form.scantron.sub_bubblelines.$line"};
 5895:         $responsetype_per_response{$line} =
 5896:             $env{"form.scantron.responsetype.$line"};
 5897:         my $id = $env{"form.scantron.residpart.$line"};
 5898:         $masterseq_id_responsenum{$id} = $line;
 5899: 	$line++;
 5900:     }
 5901: }
 5902: 
 5903: =pod 
 5904: 
 5905: =item scantron_filenames
 5906: 
 5907:    Returns a list of the scantron files in the current course 
 5908: 
 5909: =cut
 5910: 
 5911: sub scantron_filenames {
 5912:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5913:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5914:     my $getpropath = 1;
 5915:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5916:                                                         $cname,$getpropath);
 5917:     my @possiblenames;
 5918:     if (ref($dirlist) eq 'ARRAY') {
 5919:         foreach my $filename (sort(@{$dirlist})) {
 5920: 	    ($filename)=split(/&/,$filename);
 5921: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5922: 	    $filename=~s/^scantron_orig_//;
 5923: 	    push(@possiblenames,$filename);
 5924:         }
 5925:     }
 5926:     return @possiblenames;
 5927: }
 5928: 
 5929: =pod 
 5930: 
 5931: =item scantron_uploads
 5932: 
 5933:    Returns  html drop-down list of scantron files in current course.
 5934: 
 5935:  Arguments:
 5936:    $file2grade - filename to set as selected in the dropdown
 5937: 
 5938: =cut
 5939: 
 5940: sub scantron_uploads {
 5941:     my ($file2grade) = @_;
 5942:     my $result=	'<select name="scantron_selectfile">';
 5943:     $result.="<option></option>";
 5944:     foreach my $filename (sort(&scantron_filenames())) {
 5945: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5946:     }
 5947:     $result.="</select>";
 5948:     return $result;
 5949: }
 5950: 
 5951: =pod 
 5952: 
 5953: =item scantron_scantab
 5954: 
 5955:   Returns html drop down of the scantron formats in the scantronformat.tab
 5956:   file.
 5957: 
 5958: =cut
 5959: 
 5960: sub scantron_scantab {
 5961:     my $result='<select name="scantron_format">'."\n";
 5962:     $result.='<option></option>'."\n";
 5963:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5964:     if (@lines > 0) {
 5965:         foreach my $line (@lines) {
 5966:             next if (($line =~ /^\#/) || ($line eq ''));
 5967: 	    my ($name,$descrip)=split(/:/,$line);
 5968: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5969:         }
 5970:     }
 5971:     $result.='</select>'."\n";
 5972:     return $result;
 5973: }
 5974: 
 5975: =pod 
 5976: 
 5977: =item scantron_CODElist
 5978: 
 5979:   Returns html drop down of the saved CODE lists from current course,
 5980:   generated from earlier printings.
 5981: 
 5982: =cut
 5983: 
 5984: sub scantron_CODElist {
 5985:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5986:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5987:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5988:     my $namechoice='<option></option>';
 5989:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5990: 	if ($name =~ /^error: 2 /) { next; }
 5991: 	if ($name =~ /^type\0/) { next; }
 5992: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5993:     }
 5994:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5995:     return $namechoice;
 5996: }
 5997: 
 5998: =pod 
 5999: 
 6000: =item scantron_CODEunique
 6001: 
 6002:   Returns the html for "Each CODE to be used once" radio.
 6003: 
 6004: =cut
 6005: 
 6006: sub scantron_CODEunique {
 6007:     my $result='<span class="LC_nobreak">
 6008:                  <label><input type="radio" name="scantron_CODEunique"
 6009:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6010:                 </span>
 6011:                 <span class="LC_nobreak">
 6012:                  <label><input type="radio" name="scantron_CODEunique"
 6013:                         value="no" />'.&mt('No').' </label>
 6014:                 </span>';
 6015:     return $result;
 6016: }
 6017: 
 6018: =pod 
 6019: 
 6020: =item scantron_selectphase
 6021: 
 6022:   Generates the initial screen to start the bubblesheet process.
 6023:   Allows for - starting a grading run.
 6024:              - downloading existing scan data (original, corrected
 6025:                                                 or skipped info)
 6026: 
 6027:              - uploading new scan data
 6028: 
 6029:  Arguments:
 6030:   $r          - The Apache request object
 6031:   $file2grade - name of the file that contain the scanned data to score
 6032: 
 6033: =cut
 6034: 
 6035: sub scantron_selectphase {
 6036:     my ($r,$file2grade,$symb) = @_;
 6037:     if (!$symb) {return '';}
 6038:     my $map_error;
 6039:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6040:     if ($map_error) {
 6041:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6042:         return;
 6043:     }
 6044:     my $default_form_data=&defaultFormData($symb);
 6045:     my $file_selector=&scantron_uploads($file2grade);
 6046:     my $format_selector=&scantron_scantab();
 6047:     my $CODE_selector=&scantron_CODElist();
 6048:     my $CODE_unique=&scantron_CODEunique();
 6049:     my $result;
 6050: 
 6051:     $ssi_error = 0;
 6052: 
 6053:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6054:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6055: 
 6056:         # Chunk of form to prompt for a scantron file upload.
 6057: 
 6058:         $r->print('
 6059:     <br />');
 6060:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6061:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6062:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6063:         &js_escape(\$alertmsg);
 6064:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6065:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6066:     function checkUpload(formname) {
 6067:         if (formname.upfile.value == "") {
 6068:             alert("'.$alertmsg.'");
 6069:             return false;
 6070:         }
 6071:         formname.submit();
 6072:     }'."\n".$formatjs));
 6073:         $r->print('
 6074:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6075:                 '.$default_form_data.'
 6076:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6077:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6078:                 <input name="command" value="scantronupload_save" type="hidden" />
 6079:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6080:               '.&Apache::loncommon::start_data_table_header_row().'
 6081:                 <th>
 6082:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6083:                 </th>
 6084:               '.&Apache::loncommon::end_data_table_header_row().'
 6085:               '.&Apache::loncommon::start_data_table_row().'
 6086:             <td>
 6087:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6088:         if ($formatoptions) {
 6089:             $r->print('</td>
 6090:                  '.&Apache::loncommon::end_data_table_row().'
 6091:                  '.&Apache::loncommon::start_data_table_row().'
 6092:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6093:                  </td>
 6094:                  '.&Apache::loncommon::end_data_table_row().'
 6095:                  '.&Apache::loncommon::start_data_table_row().'
 6096:                  <td>'
 6097:             );
 6098:         } else {
 6099:             $r->print(' <br />');
 6100:         }
 6101:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6102:               </td>
 6103:              '.&Apache::loncommon::end_data_table_row().'
 6104:              '.&Apache::loncommon::end_data_table().'
 6105:              </form>'
 6106:         );
 6107: 
 6108:     }
 6109: 
 6110:     # Chunk of form to prompt for a file to grade and how:
 6111: 
 6112:     $result.= '
 6113:     <br />
 6114:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6115:     <input type="hidden" name="command" value="scantron_warning" />
 6116:     '.$default_form_data.'
 6117:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6118:        '.&Apache::loncommon::start_data_table_header_row().'
 6119:             <th colspan="2">
 6120:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6121:             </th>
 6122:        '.&Apache::loncommon::end_data_table_header_row().'
 6123:        '.&Apache::loncommon::start_data_table_row().'
 6124:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6125:        '.&Apache::loncommon::end_data_table_row().'
 6126:        '.&Apache::loncommon::start_data_table_row().'
 6127:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6128:        '.&Apache::loncommon::end_data_table_row().'
 6129:        '.&Apache::loncommon::start_data_table_row().'
 6130:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6131:        '.&Apache::loncommon::end_data_table_row().'
 6132:        '.&Apache::loncommon::start_data_table_row().'
 6133:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6134:        '.&Apache::loncommon::end_data_table_row().'
 6135:        '.&Apache::loncommon::start_data_table_row().'
 6136:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6137:        '.&Apache::loncommon::end_data_table_row().'
 6138:        '.&Apache::loncommon::start_data_table_row().'
 6139: 	    <td> '.&mt('Options:').' </td>
 6140:             <td>
 6141: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6142:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6143:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6144: 	    </td>
 6145:        '.&Apache::loncommon::end_data_table_row().'
 6146:        '.&Apache::loncommon::start_data_table_row().'
 6147:             <td colspan="2">
 6148:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6149:             </td>
 6150:        '.&Apache::loncommon::end_data_table_row().'
 6151:     '.&Apache::loncommon::end_data_table().'
 6152:     </form>
 6153: ';
 6154:    
 6155:     $r->print($result);
 6156: 
 6157:     # Chunk of the form that prompts to view a scoring office file,
 6158:     # corrected file, skipped records in a file.
 6159: 
 6160:     $r->print('
 6161:    <br />
 6162:    <form action="/adm/grades" name="scantron_download">
 6163:      '.$default_form_data.'
 6164:      <input type="hidden" name="command" value="scantron_download" />
 6165:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6166:        '.&Apache::loncommon::start_data_table_header_row().'
 6167:               <th>
 6168:                 &nbsp;'.&mt('Download a scoring office file').'
 6169:               </th>
 6170:        '.&Apache::loncommon::end_data_table_header_row().'
 6171:        '.&Apache::loncommon::start_data_table_row().'
 6172:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6173:                 <br />
 6174:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6175:        '.&Apache::loncommon::end_data_table_row().'
 6176:      '.&Apache::loncommon::end_data_table().'
 6177:    </form>
 6178:    <br />
 6179: ');
 6180: 
 6181:     &Apache::lonpickcode::code_list($r,2);
 6182: 
 6183:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6184:              $default_form_data."\n".
 6185:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6186:              &Apache::loncommon::start_data_table_header_row()."\n".
 6187:              '<th colspan="2">
 6188:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6189:              '</th>'."\n".
 6190:               &Apache::loncommon::end_data_table_header_row()."\n".
 6191:               &Apache::loncommon::start_data_table_row()."\n".
 6192:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6193:               '<td> '.$sequence_selector.' </td>'.
 6194:               &Apache::loncommon::end_data_table_row()."\n".
 6195:               &Apache::loncommon::start_data_table_row()."\n".
 6196:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6197:               '<td> '.$file_selector.' </td>'."\n".
 6198:               &Apache::loncommon::end_data_table_row()."\n".
 6199:               &Apache::loncommon::start_data_table_row()."\n".
 6200:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6201:               '<td> '.$format_selector.' </td>'."\n".
 6202:               &Apache::loncommon::end_data_table_row()."\n".
 6203:               &Apache::loncommon::start_data_table_row()."\n".
 6204:               '<td> '.&mt('Options').' </td>'."\n".
 6205:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6206:               &Apache::loncommon::end_data_table_row()."\n".
 6207:               &Apache::loncommon::start_data_table_row()."\n".
 6208:               '<td colspan="2">'."\n".
 6209:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6210:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6211:               '</td>'."\n".
 6212:               &Apache::loncommon::end_data_table_row()."\n".
 6213:               &Apache::loncommon::end_data_table()."\n".
 6214:               '</form><br />');
 6215:     return;
 6216: }
 6217: 
 6218: =pod 
 6219: 
 6220: =item username_to_idmap
 6221: 
 6222:     creates a hash keyed by student/employee ID with values of the corresponding
 6223:     student username:domain.
 6224: 
 6225:   Arguments:
 6226: 
 6227:     $classlist - reference to the class list hash. This is a hash
 6228:                  keyed by student name:domain  whose elements are references
 6229:                  to arrays containing various chunks of information
 6230:                  about the student. (See loncoursedata for more info).
 6231: 
 6232:   Returns
 6233:     %idmap - the constructed hash
 6234: 
 6235: =cut
 6236: 
 6237: sub username_to_idmap {
 6238:     my ($classlist)= @_;
 6239:     my %idmap;
 6240:     foreach my $student (keys(%$classlist)) {
 6241:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6242:         unless ($id eq '') {
 6243:             if (!exists($idmap{$id})) {
 6244:                 $idmap{$id} = $student;
 6245:             } else {
 6246:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6247:                 if ($status eq 'Active') {
 6248:                     $idmap{$id} = $student;
 6249:                 }
 6250:             }
 6251:         }
 6252:     }
 6253:     return %idmap;
 6254: }
 6255: 
 6256: =pod
 6257: 
 6258: =item scantron_fixup_scanline
 6259: 
 6260:    Process a requested correction to a scanline.
 6261: 
 6262:   Arguments:
 6263:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6264:     $scan_data         - hash of correction information 
 6265:                           (see &scantron_getfile())
 6266:     $line              - existing scanline
 6267:     $whichline         - line number of the passed in scanline
 6268:     $field             - type of change to process 
 6269:                          (either 
 6270:                           'ID'     -> correct the student/employee ID
 6271:                           'CODE'   -> correct the CODE
 6272:                           'answer' -> fixup the submitted answers)
 6273:     
 6274:    $args               - hash of additional info,
 6275:                           - 'ID' 
 6276:                                'newid' -> studentID to use in replacement
 6277:                                           of existing one
 6278:                           - 'CODE' 
 6279:                                'CODE_ignore_dup' - set to true if duplicates
 6280:                                                    should be ignored.
 6281: 	                       'CODE' - is new code or 'use_unfound'
 6282:                                         if the existing unfound code should
 6283:                                         be used as is
 6284:                           - 'answer'
 6285:                                'response' - new answer or 'none' if blank
 6286:                                'question' - the bubble line to change
 6287:                                'questionnum' - the question identifier,
 6288:                                                may include subquestion. 
 6289: 
 6290:   Returns:
 6291:     $line - the modified scanline
 6292: 
 6293:   Side effects: 
 6294:     $scan_data - may be updated
 6295: 
 6296: =cut
 6297: 
 6298: 
 6299: sub scantron_fixup_scanline {
 6300:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6301:     if ($field eq 'ID') {
 6302: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6303: 	    return ($line,1,'New value too large');
 6304: 	}
 6305: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6306: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6307: 				     $args->{'newid'});
 6308: 	}
 6309: 	substr($line,$$scantron_config{'IDstart'}-1,
 6310: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6311: 	if ($args->{'newid'}=~/^\s*$/) {
 6312: 	    &scan_data($scan_data,"$whichline.user",
 6313: 		       $args->{'username'}.':'.$args->{'domain'});
 6314: 	}
 6315:     } elsif ($field eq 'CODE') {
 6316: 	if ($args->{'CODE_ignore_dup'}) {
 6317: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6318: 	}
 6319: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6320: 	if ($args->{'CODE'} ne 'use_unfound') {
 6321: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6322: 		return ($line,1,'New CODE value too large');
 6323: 	    }
 6324: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6325: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6326: 	    }
 6327: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6328: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6329: 	}
 6330:     } elsif ($field eq 'answer') {
 6331: 	my $length=$scantron_config->{'Qlength'};
 6332: 	my $off=$scantron_config->{'Qoff'};
 6333: 	my $on=$scantron_config->{'Qon'};
 6334: 	my $answer=${off}x$length;
 6335: 	if ($args->{'response'} eq 'none') {
 6336: 	    &scan_data($scan_data,
 6337: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6338: 	} else {
 6339: 	    if ($on eq 'letter') {
 6340: 		my @alphabet=('A'..'Z');
 6341: 		$answer=$alphabet[$args->{'response'}];
 6342: 	    } elsif ($on eq 'number') {
 6343: 		$answer=$args->{'response'}+1;
 6344: 		if ($answer == 10) { $answer = '0'; }
 6345: 	    } else {
 6346: 		substr($answer,$args->{'response'},1)=$on;
 6347: 	    }
 6348: 	    &scan_data($scan_data,
 6349: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6350: 	}
 6351: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6352: 	substr($line,$where-1,$length)=$answer;
 6353:     }
 6354:     return $line;
 6355: }
 6356: 
 6357: =pod
 6358: 
 6359: =item scan_data
 6360: 
 6361:     Edit or look up  an item in the scan_data hash.
 6362: 
 6363:   Arguments:
 6364:     $scan_data  - The hash (see scantron_getfile)
 6365:     $key        - shorthand of the key to edit (actual key is
 6366:                   scantronfilename_key).
 6367:     $data        - New value of the hash entry.
 6368:     $delete      - If true, the entry is removed from the hash.
 6369: 
 6370:   Returns:
 6371:     The new value of the hash table field (undefined if deleted).
 6372: 
 6373: =cut
 6374: 
 6375: 
 6376: sub scan_data {
 6377:     my ($scan_data,$key,$value,$delete)=@_;
 6378:     my $filename=$env{'form.scantron_selectfile'};
 6379:     if (defined($value)) {
 6380: 	$scan_data->{$filename.'_'.$key} = $value;
 6381:     }
 6382:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6383:     return $scan_data->{$filename.'_'.$key};
 6384: }
 6385: 
 6386: # ----- These first few routines are general use routines.----
 6387: 
 6388: # Return the number of occurences of a pattern in a string.
 6389: 
 6390: sub occurence_count {
 6391:     my ($string, $pattern) = @_;
 6392: 
 6393:     my @matches = ($string =~ /$pattern/g);
 6394: 
 6395:     return scalar(@matches);
 6396: }
 6397: 
 6398: 
 6399: # Take a string known to have digits and convert all the
 6400: # digits into letters in the range J,A..I.
 6401: 
 6402: sub digits_to_letters {
 6403:     my ($input) = @_;
 6404: 
 6405:     my @alphabet = ('J', 'A'..'I');
 6406: 
 6407:     my @input    = split(//, $input);
 6408:     my $output ='';
 6409:     for (my $i = 0; $i < scalar(@input); $i++) {
 6410: 	if ($input[$i] =~ /\d/) {
 6411: 	    $output .= $alphabet[$input[$i]];
 6412: 	} else {
 6413: 	    $output .= $input[$i];
 6414: 	}
 6415:     }
 6416:     return $output;
 6417: }
 6418: 
 6419: =pod 
 6420: 
 6421: =item scantron_parse_scanline
 6422: 
 6423:   Decodes a scanline from the selected scantron file
 6424: 
 6425:  Arguments:
 6426:     line             - The text of the scantron file line to process
 6427:     whichline        - Line number
 6428:     scantron_config  - Hash describing the format of the scantron lines.
 6429:     scan_data        - Hash of extra information about the scanline
 6430:                        (see scantron_getfile for more information)
 6431:     just_header      - True if should not process question answers but only
 6432:                        the stuff to the left of the answers.
 6433:     randomorder      - True if randomorder in use
 6434:     randompick       - True if randompick in use
 6435:     sequence         - Exam folder URL
 6436:     master_seq       - Ref to array containing symbs in exam folder
 6437:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6438:                        (corresponding values are resource objects)
 6439:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6440:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6441:                        are refs to an array of resource objects, ordered
 6442:                        according to order used for CODE, when randomorder
 6443:                        and or randompick are in use.
 6444:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6445:                        for current line to question number used for same question
 6446:                         in "Master Sequence" (as seen by Course Coordinator).
 6447:     startline        - Ref to hash where key is question number (0 is first)
 6448:                        and value is number of first bubble line for current 
 6449:                        student or code-based randompick and/or randomorder.
 6450:     totalref         - Ref of scalar used to score total number of bubble
 6451:                        lines needed for responses in a scan line (used when
 6452:                        randompick in use. 
 6453: 
 6454:  Returns:
 6455:    Hash containing the result of parsing the scanline
 6456: 
 6457:    Keys are all proceeded by the string 'scantron.'
 6458: 
 6459:        CODE    - the CODE in use for this scanline
 6460:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6461:                  by the operator
 6462:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6463:                             CODEs were selected, but the usage has been
 6464:                             forced by the operator
 6465:        ID  - student/employee ID
 6466:        PaperID - if used, the ID number printed on the sheet when the 
 6467:                  paper was scanned
 6468:        FirstName - first name from the sheet
 6469:        LastName  - last name from the sheet
 6470: 
 6471:      if just_header was not true these key may also exist
 6472: 
 6473:        missingerror - a list of bubble ranges that are considered to be answers
 6474:                       to a single question that don't have any bubbles filled in.
 6475:                       Of the form questionnumber:firstbubblenumber:count.
 6476:        doubleerror  - a list of bubble ranges that are considered to be answers
 6477:                       to a single question that have more than one bubble filled in.
 6478:                       Of the form questionnumber::firstbubblenumber:count
 6479:    
 6480:                 In the above, count is the number of bubble responses in the
 6481:                 input line needed to represent the possible answers to the question.
 6482:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6483:                 per line would have count = 2.
 6484: 
 6485:        maxquest     - the number of the last bubble line that was parsed
 6486: 
 6487:        (<number> starts at 1)
 6488:        <number>.answer - zero or more letters representing the selected
 6489:                          letters from the scanline for the bubble line 
 6490:                          <number>.
 6491:                          if blank there was either no bubble or there where
 6492:                          multiple bubbles, (consult the keys missingerror and
 6493:                          doubleerror if this is an error condition)
 6494: 
 6495: =cut
 6496: 
 6497: sub scantron_parse_scanline {
 6498:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6499:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6500:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6501: 
 6502:     my %record;
 6503:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6504:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6505: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6506: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6507: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6508: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6509: 	    $record{'scantron.CODE'}=substr($data,
 6510: 					    $$scantron_config{'CODEstart'}-1,
 6511: 					    $$scantron_config{'CODElength'});
 6512: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6513: 		$record{'scantron.useCODE'}=1;
 6514: 	    }
 6515: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6516: 		$record{'scantron.CODE_ignore_dup'}=1;
 6517: 	    }
 6518: 	} else {
 6519: 	    #FIXME interpret first N questions
 6520: 	}
 6521:     }
 6522:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6523: 				  $$scantron_config{'IDlength'});
 6524:     $record{'scantron.PaperID'}=
 6525: 	substr($data,$$scantron_config{'PaperID'}-1,
 6526: 	       $$scantron_config{'PaperIDlength'});
 6527:     $record{'scantron.FirstName'}=
 6528: 	substr($data,$$scantron_config{'FirstName'}-1,
 6529: 	       $$scantron_config{'FirstNamelength'});
 6530:     $record{'scantron.LastName'}=
 6531: 	substr($data,$$scantron_config{'LastName'}-1,
 6532: 	       $$scantron_config{'LastNamelength'});
 6533:     if ($just_header) { return \%record; }
 6534: 
 6535:     my @alphabet=('A'..'Z');
 6536:     my $questnum=0;
 6537:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6538: 
 6539:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6540:     if ($randompick || $randomorder) {
 6541:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6542:                                          $master_seq,$symb_to_resource,
 6543:                                          $partids_by_symb,$orderedforcode,
 6544:                                          $respnumlookup,$startline);
 6545:         if ($total) {
 6546:             $lastpos = $total*$$scantron_config{'Qlength'};
 6547:         }
 6548:         if (ref($totalref)) {
 6549:             $$totalref = $total;
 6550:         }
 6551:     }
 6552:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6553:     chomp($questions);		# Get rid of any trailing \n.
 6554:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6555:     while (length($questions)) {
 6556:         my $answers_needed;
 6557:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6558:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6559:         } else {
 6560:             $answers_needed = $bubble_lines_per_response{$questnum};
 6561:         }
 6562:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6563:                              || 1;
 6564:         $questnum++;
 6565:         my $quest_id = $questnum;
 6566:         my $currentquest = substr($questions,0,$answer_length);
 6567:         $questions       = substr($questions,$answer_length);
 6568:         if (length($currentquest) < $answer_length) { next; }
 6569: 
 6570:         my $subdivided;
 6571:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6572:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6573:         } else {
 6574:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6575:         }
 6576:         if ($subdivided =~ /,/) {
 6577:             my $subquestnum = 1;
 6578:             my $subquestions = $currentquest;
 6579:             my @subanswers_needed = split(/,/,$subdivided);
 6580:             foreach my $subans (@subanswers_needed) {
 6581:                 my $subans_length =
 6582:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6583:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6584:                 $subquestions   = substr($subquestions,$subans_length);
 6585:                 $quest_id = "$questnum.$subquestnum";
 6586:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6587:                     ($$scantron_config{'Qon'} eq 'number')) {
 6588:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6589:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6590:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6591:                         $randomorder,$randompick,$respnumlookup);
 6592:                 } else {
 6593:                     $ansnum = &scantron_validator_positional($ansnum,
 6594:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6595:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6596:                         $randomorder,$randompick,$respnumlookup);
 6597:                 }
 6598:                 $subquestnum ++;
 6599:             }
 6600:         } else {
 6601:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6602:                 ($$scantron_config{'Qon'} eq 'number')) {
 6603:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6604:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6605:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6606:                     $randomorder,$randompick,$respnumlookup);
 6607:             } else {
 6608:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6609:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6610:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6611:                     $randomorder,$randompick,$respnumlookup);
 6612:             }
 6613:         }
 6614:     }
 6615:     $record{'scantron.maxquest'}=$questnum;
 6616:     return \%record;
 6617: }
 6618: 
 6619: sub get_master_seq {
 6620:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6621:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6622:                    (ref($symb_to_resource) eq 'HASH'));
 6623:     my $resource_error;
 6624:     foreach my $resource (@{$resources}) {
 6625:         my $ressymb;
 6626:         if (ref($resource)) {
 6627:             $ressymb = $resource->symb();
 6628:             push(@{$master_seq},$ressymb);
 6629:             $symb_to_resource->{$ressymb} = $resource;
 6630:         } else {
 6631:             $resource_error = 1;
 6632:             last;
 6633:         }
 6634:     }
 6635:     return $resource_error;
 6636: }
 6637: 
 6638: sub get_respnum_lookups {
 6639:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6640:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6641:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6642:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6643:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6644:                    (ref($startline) eq 'HASH'));
 6645:     my ($user,$scancode);
 6646:     if ((exists($record->{'scantron.CODE'})) &&
 6647:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6648:         $scancode = $record->{'scantron.CODE'};
 6649:     } else {
 6650:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6651:     }
 6652:     my @mapresources =
 6653:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6654:                      $orderedforcode);
 6655:     my $total = 0;
 6656:     my $count = 0;
 6657:     foreach my $resource (@mapresources) {
 6658:         my $id = $resource->id();
 6659:         my $symb = $resource->symb();
 6660:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6661:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6662:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6663:                 if ($respnum ne '') {
 6664:                     $respnumlookup->{$count} = $respnum;
 6665:                     $startline->{$count} = $total;
 6666:                     $total += $bubble_lines_per_response{$respnum};
 6667:                     $count ++;
 6668:                 }
 6669:             }
 6670:         }
 6671:     }
 6672:     return $total;
 6673: }
 6674: 
 6675: sub scantron_validator_lettnum {
 6676:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6677:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6678:         $randompick,$respnumlookup) = @_;
 6679: 
 6680:     # Qon 'letter' implies for each slot in currquest we have:
 6681:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6682:     #    about anything else (esp. a value of Qoff) for missing
 6683:     #    bubbles.
 6684:     #
 6685:     # Qon 'number' implies each slot gives a digit that indexes the
 6686:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6687:     #    and * or ? for double bubbles on a single line.
 6688:     #
 6689: 
 6690:     my $matchon;
 6691:     if ($$scantron_config{'Qon'} eq 'letter') {
 6692:         $matchon = '[A-Z]';
 6693:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6694:         $matchon = '\d';
 6695:     }
 6696:     my $occurrences = 0;
 6697:     my $responsenum = $questnum-1;
 6698:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6699:        $responsenum = $respnumlookup->{$questnum-1}
 6700:     }
 6701:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6702:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6703:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6704:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6705:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6706:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6707:         my @singlelines = split('',$currquest);
 6708:         foreach my $entry (@singlelines) {
 6709:             $occurrences = &occurence_count($entry,$matchon);
 6710:             if ($occurrences > 1) {
 6711:                 last;
 6712:             }
 6713:         }
 6714:     } else {
 6715:         $occurrences = &occurence_count($currquest,$matchon); 
 6716:     }
 6717:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6718:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6719:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6720:             my $bubble = substr($currquest,$ans,1);
 6721:             if ($bubble =~ /$matchon/ ) {
 6722:                 if ($$scantron_config{'Qon'} eq 'number') {
 6723:                     if ($bubble == 0) {
 6724:                         $bubble = 10; 
 6725:                     }
 6726:                     $record->{"scantron.$ansnum.answer"} = 
 6727:                         $alphabet->[$bubble-1];
 6728:                 } else {
 6729:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6730:                 }
 6731:             } else {
 6732:                 $record->{"scantron.$ansnum.answer"}='';
 6733:             }
 6734:             $ansnum++;
 6735:         }
 6736:     } elsif (!defined($currquest)
 6737:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6738:             || (&occurence_count($currquest,$matchon) == 0)) {
 6739:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6740:             $record->{"scantron.$ansnum.answer"}='';
 6741:             $ansnum++;
 6742:         }
 6743:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6744:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6745:         }
 6746:     } else {
 6747:         if ($$scantron_config{'Qon'} eq 'number') {
 6748:             $currquest = &digits_to_letters($currquest);            
 6749:         }
 6750:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6751:             my $bubble = substr($currquest,$ans,1);
 6752:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6753:             $ansnum++;
 6754:         }
 6755:     }
 6756:     return $ansnum;
 6757: }
 6758: 
 6759: sub scantron_validator_positional {
 6760:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6761:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6762:         $randomorder,$randompick,$respnumlookup) = @_;
 6763: 
 6764:     # Otherwise there's a positional notation;
 6765:     # each bubble line requires Qlength items, and there are filled in
 6766:     # bubbles for each case where there 'Qon' characters.
 6767:     #
 6768: 
 6769:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6770: 
 6771:     # If the split only gives us one element.. the full length of the
 6772:     # answer string, no bubbles are filled in:
 6773: 
 6774:     if ($answers_needed eq '') {
 6775:         return;
 6776:     }
 6777: 
 6778:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6779:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6780:             $record->{"scantron.$ansnum.answer"}='';
 6781:             $ansnum++;
 6782:         }
 6783:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6784:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6785:         }
 6786:     } elsif (scalar(@array) == 2) {
 6787:         my $location = length($array[0]);
 6788:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6789:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6790:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6791:             if ($ans eq $line_num) {
 6792:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6793:             } else {
 6794:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6795:             }
 6796:             $ansnum++;
 6797:          }
 6798:     } else {
 6799:         #  If there's more than one instance of a bubble character
 6800:         #  That's a double bubble; with positional notation we can
 6801:         #  record all the bubbles filled in as well as the
 6802:         #  fact this response consists of multiple bubbles.
 6803:         #
 6804:         my $responsenum = $questnum-1;
 6805:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6806:             $responsenum = $respnumlookup->{$questnum-1}
 6807:         }
 6808:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6809:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6810:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6811:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6812:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6813:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6814:             my $doubleerror = 0;
 6815:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6816:                    (!$doubleerror)) {
 6817:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6818:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6819:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6820:                if (length(@currarray) > 2) {
 6821:                    $doubleerror = 1;
 6822:                } 
 6823:             }
 6824:             if ($doubleerror) {
 6825:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6826:             }
 6827:         } else {
 6828:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6829:         }
 6830:         my $item = $ansnum;
 6831:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6832:             $record->{"scantron.$item.answer"} = '';
 6833:             $item ++;
 6834:         }
 6835: 
 6836:         my @ans=@array;
 6837:         my $i=0;
 6838:         my $increment = 0;
 6839:         while ($#ans) {
 6840:             $i+=length($ans[0]) + $increment;
 6841:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6842:             my $bubble = $i%$$scantron_config{'Qlength'};
 6843:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6844:             shift(@ans);
 6845:             $increment = 1;
 6846:         }
 6847:         $ansnum += $answers_needed;
 6848:     }
 6849:     return $ansnum;
 6850: }
 6851: 
 6852: =pod
 6853: 
 6854: =item scantron_add_delay
 6855: 
 6856:    Adds an error message that occurred during the grading phase to a
 6857:    queue of messages to be shown after grading pass is complete
 6858: 
 6859:  Arguments:
 6860:    $delayqueue  - arrary ref of hash ref of error messages
 6861:    $scanline    - the scanline that caused the error
 6862:    $errormesage - the error message
 6863:    $errorcode   - a numeric code for the error
 6864: 
 6865:  Side Effects:
 6866:    updates the $delayqueue to have a new hash ref of the error
 6867: 
 6868: =cut
 6869: 
 6870: sub scantron_add_delay {
 6871:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6872:     push(@$delayqueue,
 6873: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6874: 	  'ecode' => $errorcode }
 6875: 	 );
 6876: }
 6877: 
 6878: =pod
 6879: 
 6880: =item scantron_find_student
 6881: 
 6882:    Finds the username for the current scanline
 6883: 
 6884:   Arguments:
 6885:    $scantron_record - hash result from scantron_parse_scanline
 6886:    $scan_data       - hash of correction information 
 6887:                       (see &scantron_getfile() form more information)
 6888:    $idmap           - hash from &username_to_idmap()
 6889:    $line            - number of current scanline
 6890:  
 6891:   Returns:
 6892:    Either 'username:domain' or undef if unknown
 6893: 
 6894: =cut
 6895: 
 6896: sub scantron_find_student {
 6897:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6898:     my $scanID=$$scantron_record{'scantron.ID'};
 6899:     if ($scanID =~ /^\s*$/) {
 6900:  	return &scan_data($scan_data,"$line.user");
 6901:     }
 6902:     foreach my $id (keys(%$idmap)) {
 6903:  	if (lc($id) eq lc($scanID)) {
 6904:  	    return $$idmap{$id};
 6905:  	}
 6906:     }
 6907:     return undef;
 6908: }
 6909: 
 6910: =pod
 6911: 
 6912: =item scantron_filter
 6913: 
 6914:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6915:    hidden resources was selected
 6916: 
 6917: =cut
 6918: 
 6919: sub scantron_filter {
 6920:     my ($curres)=@_;
 6921: 
 6922:     if (ref($curres) && $curres->is_problem()) {
 6923: 	# if the user has asked to not have either hidden
 6924: 	# or 'randomout' controlled resources to be graded
 6925: 	# don't include them
 6926: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6927: 	    && $curres->randomout) {
 6928: 	    return 0;
 6929: 	}
 6930: 	return 1;
 6931:     }
 6932:     return 0;
 6933: }
 6934: 
 6935: =pod
 6936: 
 6937: =item scantron_process_corrections
 6938: 
 6939:    Gets correction information out of submitted form data and corrects
 6940:    the scanline
 6941: 
 6942: =cut
 6943: 
 6944: sub scantron_process_corrections {
 6945:     my ($r) = @_;
 6946:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6947:     my ($scanlines,$scan_data)=&scantron_getfile();
 6948:     my $classlist=&Apache::loncoursedata::get_classlist();
 6949:     my $which=$env{'form.scantron_line'};
 6950:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6951:     my ($skip,$err,$errmsg);
 6952:     if ($env{'form.scantron_skip_record'}) {
 6953: 	$skip=1;
 6954:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6955: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6956: 	    $env{'form.scantron_domain'};
 6957: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6958: 	($line,$err,$errmsg)=
 6959: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6960: 				     'ID',{'newid'=>$newid,
 6961: 				    'username'=>$env{'form.scantron_username'},
 6962: 				    'domain'=>$env{'form.scantron_domain'}});
 6963:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6964: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6965: 	my $newCODE;
 6966: 	my %args;
 6967: 	if      ($resolution eq 'use_unfound') {
 6968: 	    $newCODE='use_unfound';
 6969: 	} elsif ($resolution eq 'use_found') {
 6970: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6971: 	} elsif ($resolution eq 'use_typed') {
 6972: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6973: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6974: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6975: 	}
 6976: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6977: 	    $args{'CODE_ignore_dup'}=1;
 6978: 	}
 6979: 	$args{'CODE'}=$newCODE;
 6980: 	($line,$err,$errmsg)=
 6981: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6982: 				     'CODE',\%args);
 6983:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6984: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6985: 	    ($line,$err,$errmsg)=
 6986: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6987: 					 $which,'answer',
 6988: 					 { 'question'=>$question,
 6989: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6990:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6991: 	    if ($err) { last; }
 6992: 	}
 6993:     }
 6994:     if ($err) {
 6995: 	$r->print(
 6996:             '<p class="LC_error">'
 6997:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6998:                 $errmsg)
 6999:            .'</p>');
 7000:     } else {
 7001: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7002: 	&scantron_putfile($scanlines,$scan_data);
 7003:     }
 7004: }
 7005: 
 7006: =pod
 7007: 
 7008: =item reset_skipping_status
 7009: 
 7010:    Forgets the current set of remember skipped scanlines (and thus
 7011:    reverts back to considering all lines in the
 7012:    scantron_skipped_<filename> file)
 7013: 
 7014: =cut
 7015: 
 7016: sub reset_skipping_status {
 7017:     my ($scanlines,$scan_data)=&scantron_getfile();
 7018:     &scan_data($scan_data,'remember_skipping',undef,1);
 7019:     &scantron_putfile(undef,$scan_data);
 7020: }
 7021: 
 7022: =pod
 7023: 
 7024: =item start_skipping
 7025: 
 7026:    Marks a scanline to be skipped. 
 7027: 
 7028: =cut
 7029: 
 7030: sub start_skipping {
 7031:     my ($scan_data,$i)=@_;
 7032:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7033:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7034: 	$remembered{$i}=2;
 7035:     } else {
 7036: 	$remembered{$i}=1;
 7037:     }
 7038:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7039: }
 7040: 
 7041: =pod
 7042: 
 7043: =item should_be_skipped
 7044: 
 7045:    Checks whether a scanline should be skipped.
 7046: 
 7047: =cut
 7048: 
 7049: sub should_be_skipped {
 7050:     my ($scanlines,$scan_data,$i)=@_;
 7051:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7052: 	# not redoing old skips
 7053: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7054: 	return 0;
 7055:     }
 7056:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7057: 
 7058:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7059: 	return 0;
 7060:     }
 7061:     return 1;
 7062: }
 7063: 
 7064: =pod
 7065: 
 7066: =item remember_current_skipped
 7067: 
 7068:    Discovers what scanlines are in the scantron_skipped_<filename>
 7069:    file and remembers them into scan_data for later use.
 7070: 
 7071: =cut
 7072: 
 7073: sub remember_current_skipped {
 7074:     my ($scanlines,$scan_data)=&scantron_getfile();
 7075:     my %to_remember;
 7076:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7077: 	if ($scanlines->{'skipped'}[$i]) {
 7078: 	    $to_remember{$i}=1;
 7079: 	}
 7080:     }
 7081: 
 7082:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7083:     &scantron_putfile(undef,$scan_data);
 7084: }
 7085: 
 7086: =pod
 7087: 
 7088: =item check_for_error
 7089: 
 7090:     Checks if there was an error when attempting to remove a specific
 7091:     scantron_.. bubblesheet data file. Prints out an error if
 7092:     something went wrong.
 7093: 
 7094: =cut
 7095: 
 7096: sub check_for_error {
 7097:     my ($r,$result)=@_;
 7098:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7099: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7100:     }
 7101: }
 7102: 
 7103: =pod
 7104: 
 7105: =item scantron_warning_screen
 7106: 
 7107:    Interstitial screen to make sure the operator has selected the
 7108:    correct options before we start the validation phase.
 7109: 
 7110: =cut
 7111: 
 7112: sub scantron_warning_screen {
 7113:     my ($button_text,$symb)=@_;
 7114:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7115:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7116:     my $CODElist;
 7117:     if ($scantron_config{'CODElocation'} &&
 7118: 	$scantron_config{'CODEstart'} &&
 7119: 	$scantron_config{'CODElength'}) {
 7120: 	$CODElist=$env{'form.scantron_CODElist'};
 7121: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7122: 	$CODElist=
 7123: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7124: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7125:     }
 7126:     my $lastbubblepoints;
 7127:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7128:         $lastbubblepoints =
 7129:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7130:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7131:     }
 7132:     return ('
 7133: <p>
 7134: <span class="LC_warning">
 7135: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7136: </p>
 7137: <table>
 7138: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7139: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7140: '.$CODElist.$lastbubblepoints.'
 7141: </table>
 7142: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7143: '.&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>
 7144: 
 7145: <br />
 7146: ');
 7147: }
 7148: 
 7149: =pod
 7150: 
 7151: =item scantron_do_warning
 7152: 
 7153:    Check if the operator has picked something for all required
 7154:    fields. Error out if something is missing.
 7155: 
 7156: =cut
 7157: 
 7158: sub scantron_do_warning {
 7159:     my ($r,$symb)=@_;
 7160:     if (!$symb) {return '';}
 7161:     my $default_form_data=&defaultFormData($symb);
 7162:     $r->print(&scantron_form_start().$default_form_data);
 7163:     if ( $env{'form.selectpage'} eq '' ||
 7164: 	 $env{'form.scantron_selectfile'} eq '' ||
 7165: 	 $env{'form.scantron_format'} eq '' ) {
 7166: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7167: 	if ( $env{'form.selectpage'} eq '') {
 7168: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7169: 	} 
 7170: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7171: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7172: 	} 
 7173: 	if ( $env{'form.scantron_format'} eq '') {
 7174: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7175: 	} 
 7176:     } else {
 7177: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7178:         my $bubbledbyhand=&hand_bubble_option();
 7179: 	$r->print('
 7180: '.$warning.$bubbledbyhand.'
 7181: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7182: <input type="hidden" name="command" value="scantron_validate" />
 7183: ');
 7184:     }
 7185:     $r->print("</form><br />");
 7186:     return '';
 7187: }
 7188: 
 7189: =pod
 7190: 
 7191: =item scantron_form_start
 7192: 
 7193:     html hidden input for remembering all selected grading options
 7194: 
 7195: =cut
 7196: 
 7197: sub scantron_form_start {
 7198:     my ($max_bubble)=@_;
 7199:     my $result= <<SCANTRONFORM;
 7200: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7201:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7202:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7203:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7204:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7205:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7206:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7207:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7208:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7209:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7210: SCANTRONFORM
 7211: 
 7212:   my $line = 0;
 7213:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7214:        my $chunk =
 7215: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7216:        $chunk .=
 7217: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7218:        $chunk .= 
 7219:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7220:        $chunk .=
 7221:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7222:        $chunk .=
 7223:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7224:        $result .= $chunk;
 7225:        $line++;
 7226:     }
 7227:     return $result;
 7228: }
 7229: 
 7230: =pod
 7231: 
 7232: =item scantron_validate_file
 7233: 
 7234:     Dispatch routine for doing validation of a bubblesheet data file.
 7235: 
 7236:     Also processes any necessary information resets that need to
 7237:     occur before validation begins (ignore previous corrections,
 7238:     restarting the skipped records processing)
 7239: 
 7240: =cut
 7241: 
 7242: sub scantron_validate_file {
 7243:     my ($r,$symb) = @_;
 7244:     if (!$symb) {return '';}
 7245:     my $default_form_data=&defaultFormData($symb);
 7246:     
 7247:     # do the detection of only doing skipped records first before we delete
 7248:     # them when doing the corrections reset
 7249:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7250: 	&reset_skipping_status();
 7251:     }
 7252:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7253: 	&remember_current_skipped();
 7254: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7255:     }
 7256: 
 7257:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7258: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7259: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7260: 	&check_for_error($r,&scantron_remove_scan_data());
 7261: 	$env{'form.scantron_options_ignore'}='done';
 7262:     }
 7263: 
 7264:     if ($env{'form.scantron_corrections'}) {
 7265: 	&scantron_process_corrections($r);
 7266:     }
 7267:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7268:     #get the student pick code ready
 7269:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7270:     my $nav_error;
 7271:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7272:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7273:     if ($nav_error) {
 7274:         $r->print(&navmap_errormsg());
 7275:         return '';
 7276:     }
 7277:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7278:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7279:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7280:     }
 7281:     $r->print($result);
 7282:     
 7283:     my @validate_phases=( 'sequence',
 7284: 			  'ID',
 7285: 			  'CODE',
 7286: 			  'doublebubble',
 7287: 			  'missingbubbles');
 7288:     if (!$env{'form.validatepass'}) {
 7289: 	$env{'form.validatepass'} = 0;
 7290:     }
 7291:     my $currentphase=$env{'form.validatepass'};
 7292: 
 7293: 
 7294:     my $stop=0;
 7295:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7296: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7297: 	$r->rflush();
 7298: 
 7299: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7300: 	{
 7301: 	    no strict 'refs';
 7302: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7303: 	}
 7304:     }
 7305:     if (!$stop) {
 7306: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7307: 	$r->print(&mt('Validation process complete.').'<br />'.
 7308:                   $warning.
 7309:                   &mt('Perform verification for each student after storage of submissions?').
 7310:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7311:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7312:                   ('&nbsp;'x3).'<label>'.
 7313:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7314:                   '</label></span><br />'.
 7315:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7316:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7317:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7318:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7319:     } else {
 7320: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7321: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7322:     }
 7323:     if ($stop) {
 7324: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7325: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7326: 	    $r->print(' '.&mt('this error').' <br />');
 7327: 
 7328:             $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>');
 7329: 	} else {
 7330:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7331: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7332:             } else {
 7333:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7334:             }
 7335: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7336: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7337: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7338: 	}
 7339:     }
 7340:     $r->print(" </form><br />");
 7341:     return '';
 7342: }
 7343: 
 7344: 
 7345: =pod
 7346: 
 7347: =item scantron_remove_file
 7348: 
 7349:    Removes the requested bubblesheet data file, makes sure that
 7350:    scantron_original_<filename> is never removed
 7351: 
 7352: 
 7353: =cut
 7354: 
 7355: sub scantron_remove_file {
 7356:     my ($which)=@_;
 7357:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7358:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7359:     my $file='scantron_';
 7360:     if ($which eq 'corrected' || $which eq 'skipped') {
 7361: 	$file.=$which.'_';
 7362:     } else {
 7363: 	return 'refused';
 7364:     }
 7365:     $file.=$env{'form.scantron_selectfile'};
 7366:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7367: }
 7368: 
 7369: 
 7370: =pod
 7371: 
 7372: =item scantron_remove_scan_data
 7373: 
 7374:    Removes all scan_data correction for the requested bubblesheet
 7375:    data file.  (In the case that both the are doing skipped records we need
 7376:    to remember the old skipped lines for the time being so that element
 7377:    persists for a while.)
 7378: 
 7379: =cut
 7380: 
 7381: sub scantron_remove_scan_data {
 7382:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7383:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7384:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7385:     my @todelete;
 7386:     my $filename=$env{'form.scantron_selectfile'};
 7387:     foreach my $key (@keys) {
 7388: 	if ($key=~/^\Q$filename\E_/) {
 7389: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7390: 		$key=~/remember_skipping/) {
 7391: 		next;
 7392: 	    }
 7393: 	    push(@todelete,$key);
 7394: 	}
 7395:     }
 7396:     my $result;
 7397:     if (@todelete) {
 7398: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7399: 				       \@todelete,$cdom,$cname);
 7400:     } else {
 7401: 	$result = 'ok';
 7402:     }
 7403:     return $result;
 7404: }
 7405: 
 7406: 
 7407: =pod
 7408: 
 7409: =item scantron_getfile
 7410: 
 7411:     Fetches the requested bubblesheet data file (all 3 versions), and
 7412:     the scan_data hash
 7413:   
 7414:   Arguments:
 7415:     None
 7416: 
 7417:   Returns:
 7418:     2 hash references
 7419: 
 7420:      - first one has 
 7421:          orig      -
 7422:          corrected -
 7423:          skipped   -  each of which points to an array ref of the specified
 7424:                       file broken up into individual lines
 7425:          count     - number of scanlines
 7426:  
 7427:      - second is the scan_data hash possible keys are
 7428:        ($number refers to scanline numbered $number and thus the key affects
 7429:         only that scanline
 7430:         $bubline refers to the specific bubble line element and the aspects
 7431:         refers to that specific bubble line element)
 7432: 
 7433:        $number.user - username:domain to use
 7434:        $number.CODE_ignore_dup 
 7435:                     - ignore the duplicate CODE error 
 7436:        $number.useCODE
 7437:                     - use the CODE in the scanline as is
 7438:        $number.no_bubble.$bubline
 7439:                     - it is valid that there is no bubbled in bubble
 7440:                       at $number $bubline
 7441:        remember_skipping
 7442:                     - a frozen hash containing keys of $number and values
 7443:                       of either 
 7444:                         1 - we are on a 'do skipped records pass' and plan
 7445:                             on processing this line
 7446:                         2 - we are on a 'do skipped records pass' and this
 7447:                             scanline has been marked to skip yet again
 7448: 
 7449: =cut
 7450: 
 7451: sub scantron_getfile {
 7452:     #FIXME really would prefer a scantron directory
 7453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7455:     my $lines;
 7456:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7457: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7458:     my %scanlines;
 7459:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7460:     my $temp=$scanlines{'orig'};
 7461:     $scanlines{'count'}=$#$temp;
 7462: 
 7463:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7464: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7465:     if ($lines eq '-1') {
 7466: 	$scanlines{'corrected'}=[];
 7467:     } else {
 7468: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7469:     }
 7470:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7471: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7472:     if ($lines eq '-1') {
 7473: 	$scanlines{'skipped'}=[];
 7474:     } else {
 7475: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7476:     }
 7477:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7478:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7479:     my %scan_data = @tmp;
 7480:     return (\%scanlines,\%scan_data);
 7481: }
 7482: 
 7483: =pod
 7484: 
 7485: =item lonnet_putfile
 7486: 
 7487:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7488: 
 7489:  Arguments:
 7490:    $contents - data to store
 7491:    $filename - filename to store $contents into
 7492: 
 7493:  Returns:
 7494:    result value from &Apache::lonnet::finishuserfileupload
 7495: 
 7496: =cut
 7497: 
 7498: sub lonnet_putfile {
 7499:     my ($contents,$filename)=@_;
 7500:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7501:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7502:     $env{'form.sillywaytopassafilearound'}=$contents;
 7503:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7504: 
 7505: }
 7506: 
 7507: =pod
 7508: 
 7509: =item scantron_putfile
 7510: 
 7511:     Stores the current version of the bubblesheet data files, and the
 7512:     scan_data hash. (Does not modify the original version only the
 7513:     corrected and skipped versions.
 7514: 
 7515:  Arguments:
 7516:     $scanlines - hash ref that looks like the first return value from
 7517:                  &scantron_getfile()
 7518:     $scan_data - hash ref that looks like the second return value from
 7519:                  &scantron_getfile()
 7520: 
 7521: =cut
 7522: 
 7523: sub scantron_putfile {
 7524:     my ($scanlines,$scan_data) = @_;
 7525:     #FIXME really would prefer a scantron directory
 7526:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7528:     if ($scanlines) {
 7529: 	my $prefix='scantron_';
 7530: # no need to update orig, shouldn't change
 7531: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7532: #		    $env{'form.scantron_selectfile'});
 7533: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7534: 			$prefix.'corrected_'.
 7535: 			$env{'form.scantron_selectfile'});
 7536: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7537: 			$prefix.'skipped_'.
 7538: 			$env{'form.scantron_selectfile'});
 7539:     }
 7540:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7541: }
 7542: 
 7543: =pod
 7544: 
 7545: =item scantron_get_line
 7546: 
 7547:    Returns the correct version of the scanline
 7548: 
 7549:  Arguments:
 7550:     $scanlines - hash ref that looks like the first return value from
 7551:                  &scantron_getfile()
 7552:     $scan_data - hash ref that looks like the second return value from
 7553:                  &scantron_getfile()
 7554:     $i         - number of the requested line (starts at 0)
 7555: 
 7556:  Returns:
 7557:    A scanline, (either the original or the corrected one if it
 7558:    exists), or undef if the requested scanline should be
 7559:    skipped. (Either because it's an skipped scanline, or it's an
 7560:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7561:    pass.
 7562: 
 7563: =cut
 7564: 
 7565: sub scantron_get_line {
 7566:     my ($scanlines,$scan_data,$i)=@_;
 7567:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7568:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7569:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7570:     return $scanlines->{'orig'}[$i]; 
 7571: }
 7572: 
 7573: =pod
 7574: 
 7575: =item scantron_todo_count
 7576: 
 7577:     Counts the number of scanlines that need processing.
 7578: 
 7579:  Arguments:
 7580:     $scanlines - hash ref that looks like the first return value from
 7581:                  &scantron_getfile()
 7582:     $scan_data - hash ref that looks like the second return value from
 7583:                  &scantron_getfile()
 7584: 
 7585:  Returns:
 7586:     $count - number of scanlines to process
 7587: 
 7588: =cut
 7589: 
 7590: sub get_todo_count {
 7591:     my ($scanlines,$scan_data)=@_;
 7592:     my $count=0;
 7593:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7594: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7595: 	if ($line=~/^[\s\cz]*$/) { next; }
 7596: 	$count++;
 7597:     }
 7598:     return $count;
 7599: }
 7600: 
 7601: =pod
 7602: 
 7603: =item scantron_put_line
 7604: 
 7605:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7606:     data file.
 7607: 
 7608:  Arguments:
 7609:     $scanlines - hash ref that looks like the first return value from
 7610:                  &scantron_getfile()
 7611:     $scan_data - hash ref that looks like the second return value from
 7612:                  &scantron_getfile()
 7613:     $i         - line number to update
 7614:     $newline   - contents of the updated scanline
 7615:     $skip      - if true make the line for skipping and update the
 7616:                  'skipped' file
 7617: 
 7618: =cut
 7619: 
 7620: sub scantron_put_line {
 7621:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7622:     if ($skip) {
 7623: 	$scanlines->{'skipped'}[$i]=$newline;
 7624: 	&start_skipping($scan_data,$i);
 7625: 	return;
 7626:     }
 7627:     $scanlines->{'corrected'}[$i]=$newline;
 7628: }
 7629: 
 7630: =pod
 7631: 
 7632: =item scantron_clear_skip
 7633: 
 7634:    Remove a line from the 'skipped' file
 7635: 
 7636:  Arguments:
 7637:     $scanlines - hash ref that looks like the first return value from
 7638:                  &scantron_getfile()
 7639:     $scan_data - hash ref that looks like the second return value from
 7640:                  &scantron_getfile()
 7641:     $i         - line number to update
 7642: 
 7643: =cut
 7644: 
 7645: sub scantron_clear_skip {
 7646:     my ($scanlines,$scan_data,$i)=@_;
 7647:     if (exists($scanlines->{'skipped'}[$i])) {
 7648: 	undef($scanlines->{'skipped'}[$i]);
 7649: 	return 1;
 7650:     }
 7651:     return 0;
 7652: }
 7653: 
 7654: =pod
 7655: 
 7656: =item scantron_filter_not_exam
 7657: 
 7658:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7659:    filter out resources that are not marked as 'exam' mode
 7660: 
 7661: =cut
 7662: 
 7663: sub scantron_filter_not_exam {
 7664:     my ($curres)=@_;
 7665:     
 7666:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7667: 	# if the user has asked to not have either hidden
 7668: 	# or 'randomout' controlled resources to be graded
 7669: 	# don't include them
 7670: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7671: 	    && $curres->randomout) {
 7672: 	    return 0;
 7673: 	}
 7674: 	return 1;
 7675:     }
 7676:     return 0;
 7677: }
 7678: 
 7679: =pod
 7680: 
 7681: =item scantron_validate_sequence
 7682: 
 7683:     Validates the selected sequence, checking for resource that are
 7684:     not set to exam mode.
 7685: 
 7686: =cut
 7687: 
 7688: sub scantron_validate_sequence {
 7689:     my ($r,$currentphase) = @_;
 7690: 
 7691:     my $navmap=Apache::lonnavmaps::navmap->new();
 7692:     unless (ref($navmap)) {
 7693:         $r->print(&navmap_errormsg());
 7694:         return (1,$currentphase);
 7695:     }
 7696:     my (undef,undef,$sequence)=
 7697: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7698: 
 7699:     my $map=$navmap->getResourceByUrl($sequence);
 7700: 
 7701:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7702:                                     value="ignore" />');
 7703:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7704: 	my @resources=
 7705: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7706: 	if (@resources) {
 7707: 	    $r->print('<p class="LC_warning">'
 7708:                .&mt('Some resources in the sequence currently are not set to'
 7709:                    .' exam mode. Grading these resources currently may not'
 7710:                    .' work correctly.')
 7711:                .'</p>'
 7712:             );
 7713: 	    return (1,$currentphase);
 7714: 	}
 7715:     }
 7716: 
 7717:     return (0,$currentphase+1);
 7718: }
 7719: 
 7720: 
 7721: 
 7722: sub scantron_validate_ID {
 7723:     my ($r,$currentphase) = @_;
 7724:     
 7725:     #get student info
 7726:     my $classlist=&Apache::loncoursedata::get_classlist();
 7727:     my %idmap=&username_to_idmap($classlist);
 7728: 
 7729:     #get scantron line setup
 7730:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7731:     my ($scanlines,$scan_data)=&scantron_getfile();
 7732: 
 7733:     my $nav_error;
 7734:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7735:     if ($nav_error) {
 7736:         $r->print(&navmap_errormsg());
 7737:         return(1,$currentphase);
 7738:     }
 7739: 
 7740:     my %found=('ids'=>{},'usernames'=>{});
 7741:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7742: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7743: 	if ($line=~/^[\s\cz]*$/) { next; }
 7744: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7745: 						 $scan_data);
 7746: 	my $id=$$scan_record{'scantron.ID'};
 7747: 	my $found;
 7748: 	foreach my $checkid (keys(%idmap)) {
 7749: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7750: 	}
 7751: 	if ($found) {
 7752: 	    my $username=$idmap{$found};
 7753: 	    if ($found{'ids'}{$found}) {
 7754: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7755: 					 $line,'duplicateID',$found);
 7756: 		return(1,$currentphase);
 7757: 	    } elsif ($found{'usernames'}{$username}) {
 7758: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7759: 					 $line,'duplicateID',$username);
 7760: 		return(1,$currentphase);
 7761: 	    }
 7762: 	    #FIXME store away line we previously saw the ID on to use above
 7763: 	    $found{'ids'}{$found}++;
 7764: 	    $found{'usernames'}{$username}++;
 7765: 	} else {
 7766: 	    if ($id =~ /^\s*$/) {
 7767: 		my $username=&scan_data($scan_data,"$i.user");
 7768: 		if (defined($username) && $found{'usernames'}{$username}) {
 7769: 		    &scantron_get_correction($r,$i,$scan_record,
 7770: 					     \%scantron_config,
 7771: 					     $line,'duplicateID',$username);
 7772: 		    return(1,$currentphase);
 7773: 		} elsif (!defined($username)) {
 7774: 		    &scantron_get_correction($r,$i,$scan_record,
 7775: 					     \%scantron_config,
 7776: 					     $line,'incorrectID');
 7777: 		    return(1,$currentphase);
 7778: 		}
 7779: 		$found{'usernames'}{$username}++;
 7780: 	    } else {
 7781: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7782: 					 $line,'incorrectID');
 7783: 		return(1,$currentphase);
 7784: 	    }
 7785: 	}
 7786:     }
 7787: 
 7788:     return (0,$currentphase+1);
 7789: }
 7790: 
 7791: 
 7792: sub scantron_get_correction {
 7793:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7794:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7795: #FIXME in the case of a duplicated ID the previous line, probably need
 7796: #to show both the current line and the previous one and allow skipping
 7797: #the previous one or the current one
 7798: 
 7799:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7800:         $r->print(
 7801:             '<p class="LC_warning">'
 7802:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7803:                 "<b>$error</b>",
 7804:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7805:            ."</p> \n");
 7806:     } else {
 7807:         $r->print(
 7808:             '<p class="LC_warning">'
 7809:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7810:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7811:            ."</p> \n");
 7812:     }
 7813:     my $message =
 7814:         '<p>'
 7815:        .&mt('The ID on the form is [_1]',
 7816:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7817:        .'<br />'
 7818:        .&mt('The name on the paper is [_1], [_2]',
 7819:             $$scan_record{'scantron.LastName'},
 7820:             $$scan_record{'scantron.FirstName'})
 7821:        .'</p>';
 7822: 
 7823:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7824:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7825:                            # Array populated for doublebubble or
 7826:     my @lines_to_correct;  # missingbubble errors to build javascript
 7827:                            # to validate radio button checking   
 7828: 
 7829:     if ($error =~ /ID$/) {
 7830: 	if ($error eq 'incorrectID') {
 7831: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7832: 		      "</p>\n");
 7833: 	} elsif ($error eq 'duplicateID') {
 7834: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7835: 	}
 7836: 	$r->print($message);
 7837: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7838: 	$r->print("\n<ul><li> ");
 7839: 	#FIXME it would be nice if this sent back the user ID and
 7840: 	#could do partial userID matches
 7841: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7842: 				       'scantron_username','scantron_domain'));
 7843: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7844: 	$r->print("\n:\n".
 7845: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7846: 
 7847: 	$r->print('</li>');
 7848:     } elsif ($error =~ /CODE$/) {
 7849: 	if ($error eq 'incorrectCODE') {
 7850: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7851: 	} elsif ($error eq 'duplicateCODE') {
 7852: 	    $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");
 7853: 	}
 7854:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7855:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7856:                  ."</p>\n");
 7857: 	$r->print($message);
 7858: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7859: 	$r->print("\n<br /> ");
 7860: 	my $i=0;
 7861: 	if ($error eq 'incorrectCODE' 
 7862: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7863: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7864: 	    if ($closest > 0) {
 7865: 		foreach my $testcode (@{$closest}) {
 7866: 		    my $checked='';
 7867: 		    if (!$i) { $checked=' checked="checked"'; }
 7868: 		    $r->print("
 7869:    <label>
 7870:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7871:        ".&mt("Use the similar CODE [_1] instead.",
 7872: 	    "<b><tt>".$testcode."</tt></b>")."
 7873:     </label>
 7874:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7875: 		    $r->print("\n<br />");
 7876: 		    $i++;
 7877: 		}
 7878: 	    }
 7879: 	}
 7880: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7881: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7882: 	    $r->print("
 7883:     <label>
 7884:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7885:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7886: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7887:     </label>");
 7888: 	    $r->print("\n<br />");
 7889: 	}
 7890: 
 7891: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7892: function change_radio(field) {
 7893:     var slct=document.scantronupload.scantron_CODE_resolution;
 7894:     var i;
 7895:     for (i=0;i<slct.length;i++) {
 7896:         if (slct[i].value==field) { slct[i].checked=true; }
 7897:     }
 7898: }
 7899: ENDSCRIPT
 7900: 	my $href="/adm/pickcode?".
 7901: 	   "form=".&escape("scantronupload").
 7902: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7903: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7904: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7905: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7906: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7907: 	    $r->print("
 7908:     <label>
 7909:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7910:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7911: 	     "<a target='_blank' href='$href'>","</a>")."
 7912:     </label> 
 7913:     ".&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\')" />'));
 7914: 	    $r->print("\n<br />");
 7915: 	}
 7916: 	$r->print("
 7917:     <label>
 7918:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7919:        ".&mt("Use [_1] as the CODE.",
 7920: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7921: 	$r->print("\n<br /><br />");
 7922:     } elsif ($error eq 'doublebubble') {
 7923: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7924: 
 7925: 	# The form field scantron_questions is acutally a list of line numbers.
 7926: 	# represented by this form so:
 7927: 
 7928: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7929:                                                 $respnumlookup,$startline);
 7930: 
 7931: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7932: 		  $line_list.'" />');
 7933: 	$r->print($message);
 7934: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7935: 	foreach my $question (@{$arg}) {
 7936: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7937:                                                    $scan_record, $error,
 7938:                                                    $randomorder,$randompick,
 7939:                                                    $respnumlookup,$startline);
 7940:             push(@lines_to_correct,@linenums);
 7941: 	}
 7942:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7943:     } elsif ($error eq 'missingbubble') {
 7944: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7945: 	$r->print($message);
 7946: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7947: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7948: 
 7949: 	# The form field scantron_questions is actually a list of line numbers not
 7950: 	# a list of question numbers. Therefore:
 7951: 	#
 7952: 	
 7953: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7954:                                                 $respnumlookup,$startline);
 7955: 
 7956: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7957: 		  $line_list.'" />');
 7958: 	foreach my $question (@{$arg}) {
 7959: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7960:                                                    $scan_record, $error,
 7961:                                                    $randomorder,$randompick,
 7962:                                                    $respnumlookup,$startline);
 7963:             push(@lines_to_correct,@linenums);
 7964: 	}
 7965:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7966:     } else {
 7967: 	$r->print("\n<ul>");
 7968:     }
 7969:     $r->print("\n</li></ul>");
 7970: }
 7971: 
 7972: sub verify_bubbles_checked {
 7973:     my (@ansnums) = @_;
 7974:     my $ansnumstr = join('","',@ansnums);
 7975:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7976:     &js_escape(\$warning);
 7977:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 7978: function verify_bubble_radio(form) {
 7979:     var ansnumArray = new Array ("$ansnumstr");
 7980:     var need_bubble_count = 0;
 7981:     for (var i=0; i<ansnumArray.length; i++) {
 7982:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7983:             var bubble_picked = 0; 
 7984:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7985:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7986:                     bubble_picked = 1;
 7987:                 }
 7988:             }
 7989:             if (bubble_picked == 0) {
 7990:                 need_bubble_count ++;
 7991:             }
 7992:         }
 7993:     }
 7994:     if (need_bubble_count) {
 7995:         alert("$warning");
 7996:         return;
 7997:     }
 7998:     form.submit(); 
 7999: }
 8000: ENDSCRIPT
 8001:     return $output;
 8002: }
 8003: 
 8004: =pod
 8005: 
 8006: =item  questions_to_line_list
 8007: 
 8008: Converts a list of questions into a string of comma separated
 8009: line numbers in the answer sheet used by the questions.  This is
 8010: used to fill in the scantron_questions form field.
 8011: 
 8012:   Arguments:
 8013:      questions    - Reference to an array of questions.
 8014:      randomorder  - True if randomorder in use.
 8015:      randompick   - True if randompick in use.
 8016:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8017:                      for current line to question number used for same question
 8018:                      in "Master Seqence" (as seen by Course Coordinator).
 8019:      startline    - Reference to hash where key is question number (0 is first)
 8020:                     and key is number of first bubble line for current student
 8021:                     or code-based randompick and/or randomorder.
 8022: 
 8023: =cut
 8024: 
 8025: 
 8026: sub questions_to_line_list {
 8027:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8028:     my @lines;
 8029: 
 8030:     foreach my $item (@{$questions}) {
 8031:         my $question = $item;
 8032:         my ($first,$count,$last);
 8033:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8034:             $question = $1;
 8035:             my $subquestion = $2;
 8036:             my $responsenum = $question-1;
 8037:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8038:                 $responsenum = $respnumlookup->{$question-1};
 8039:                 if (ref($startline) eq 'HASH') {
 8040:                     $first = $startline->{$question-1} + 1;
 8041:                 }
 8042:             } else {
 8043:                 $first = $first_bubble_line{$responsenum} + 1;
 8044:             }
 8045:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8046:             my $subcount = 1;
 8047:             while ($subcount<$subquestion) {
 8048:                 $first += $subans[$subcount-1];
 8049:                 $subcount ++;
 8050:             }
 8051:             $count = $subans[$subquestion-1];
 8052:         } else {
 8053:             my $responsenum = $question-1;
 8054:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8055:                 $responsenum = $respnumlookup->{$question-1};
 8056:                 if (ref($startline) eq 'HASH') {
 8057:                     $first = $startline->{$question-1} + 1;
 8058:                 }
 8059:             } else {
 8060:                 $first = $first_bubble_line{$responsenum} + 1;
 8061:             }
 8062:             $count   = $bubble_lines_per_response{$responsenum};
 8063:         }
 8064:         $last = $first+$count-1;
 8065:         push(@lines, ($first..$last));
 8066:     }
 8067:     return join(',', @lines);
 8068: }
 8069: 
 8070: =pod 
 8071: 
 8072: =item prompt_for_corrections
 8073: 
 8074: Prompts for a potentially multiline correction to the
 8075: user's bubbling (factors out common code from scantron_get_correction
 8076: for multi and missing bubble cases).
 8077: 
 8078:  Arguments:
 8079:    $r           - Apache request object.
 8080:    $question    - The question number to prompt for.
 8081:    $scan_config - The scantron file configuration hash.
 8082:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8083:    $error       - Type of error
 8084:    $randomorder - True if randomorder in use.
 8085:    $randompick  - True if randompick in use.
 8086:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8087:                     for current line to question number used for same question
 8088:                     in "Master Seqence" (as seen by Course Coordinator).
 8089:    $startline   - Reference to hash where key is question number (0 is first)
 8090:                   and value is number of first bubble line for current student
 8091:                   or code-based randompick and/or randomorder.
 8092: 
 8093:  Implicit inputs:
 8094:    %bubble_lines_per_response   - Starting line numbers for each question.
 8095:                                   Numbered from 0 (but question numbers are from
 8096:                                   1.
 8097:    %first_bubble_line           - Starting bubble line for each question.
 8098:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8099:                                   type problems render as separate sub-questions, 
 8100:                                   in exam mode. This hash contains a 
 8101:                                   comma-separated list of the lines per 
 8102:                                   sub-question.
 8103:    %responsetype_per_response   - essayresponse, formularesponse,
 8104:                                   stringresponse, imageresponse, reactionresponse,
 8105:                                   and organicresponse type problem parts can have
 8106:                                   multiple lines per response if the weight
 8107:                                   assigned exceeds 10.  In this case, only
 8108:                                   one bubble per line is permitted, but more 
 8109:                                   than one line might contain bubbles, e.g.
 8110:                                   bubbling of: line 1 - J, line 2 - J, 
 8111:                                   line 3 - B would assign 22 points.  
 8112: 
 8113: =cut
 8114: 
 8115: sub prompt_for_corrections {
 8116:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8117:         $randompick, $respnumlookup, $startline) = @_;
 8118:     my ($current_line,$lines);
 8119:     my @linenums;
 8120:     my $questionnum = $question;
 8121:     my ($first,$responsenum);
 8122:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8123:         $question = $1;
 8124:         my $subquestion = $2;
 8125:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8126:             $responsenum = $respnumlookup->{$question-1};
 8127:             if (ref($startline) eq 'HASH') {
 8128:                 $first = $startline->{$question-1};
 8129:             }
 8130:         } else {
 8131:             $responsenum = $question-1;
 8132:             $first = $first_bubble_line{$responsenum};
 8133:         }
 8134:         $current_line = $first + 1 ;
 8135:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8136:         my $subcount = 1;
 8137:         while ($subcount<$subquestion) {
 8138:             $current_line += $subans[$subcount-1];
 8139:             $subcount ++;
 8140:         }
 8141:         $lines = $subans[$subquestion-1];
 8142:     } else {
 8143:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8144:             $responsenum = $respnumlookup->{$question-1};
 8145:             if (ref($startline) eq 'HASH') {
 8146:                 $first = $startline->{$question-1};
 8147:             }
 8148:         } else {
 8149:             $responsenum = $question-1;
 8150:             $first = $first_bubble_line{$responsenum};
 8151:         }
 8152:         $current_line = $first + 1;
 8153:         $lines        = $bubble_lines_per_response{$responsenum};
 8154:     }
 8155:     if ($lines > 1) {
 8156:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8157:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8158:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8159:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8160:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8161:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8162:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8163:             $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 />');
 8164:         } else {
 8165:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8166:         }
 8167:     }
 8168:     for (my $i =0; $i < $lines; $i++) {
 8169:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8170: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8171: 	        		  $questionnum,$error,split('', $selected));
 8172:         push(@linenums,$current_line);
 8173: 	$current_line++;
 8174:     }
 8175:     if ($lines > 1) {
 8176: 	$r->print("<hr /><br />");
 8177:     }
 8178:     return @linenums;
 8179: }
 8180: 
 8181: =pod
 8182: 
 8183: =item scantron_bubble_selector
 8184:   
 8185:    Generates the html radiobuttons to correct a single bubble line
 8186:    possibly showing the existing the selected bubbles if known
 8187: 
 8188:  Arguments:
 8189:     $r           - Apache request object
 8190:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8191:     $line        - Number of the line being displayed.
 8192:     $questionnum - Question number (may include subquestion)
 8193:     $error       - Type of error.
 8194:     @selected    - Array of bubbles picked on this line.
 8195: 
 8196: =cut
 8197: 
 8198: sub scantron_bubble_selector {
 8199:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8200:     my $max=$$scan_config{'Qlength'};
 8201: 
 8202:     my $scmode=$$scan_config{'Qon'};
 8203:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8204:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8205:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8206:             $max=$$scan_config{'BubblesPerRow'};
 8207:             if (($scmode eq 'number') && ($max > 10)) {
 8208:                 $max = 10;
 8209:             } elsif (($scmode eq 'letter') && $max > 26) {
 8210:                 $max = 26;
 8211:             }
 8212:         } else {
 8213:             $max = 10;
 8214:         }
 8215:     }
 8216: 
 8217:     my @alphabet=('A'..'Z');
 8218:     $r->print(&Apache::loncommon::start_data_table().
 8219:               &Apache::loncommon::start_data_table_row());
 8220:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8221:     for (my $i=0;$i<$max+1;$i++) {
 8222: 	$r->print("\n".'<td align="center">');
 8223: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8224: 	else { $r->print('&nbsp;'); }
 8225: 	$r->print('</td>');
 8226:     }
 8227:     $r->print(&Apache::loncommon::end_data_table_row().
 8228:               &Apache::loncommon::start_data_table_row());
 8229:     for (my $i=0;$i<$max;$i++) {
 8230: 	$r->print("\n".
 8231: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8232: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8233:     }
 8234:     my $nobub_checked = ' ';
 8235:     if ($error eq 'missingbubble') {
 8236:         $nobub_checked = ' checked = "checked" ';
 8237:     }
 8238:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8239: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8240:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8241:               $line.'" value="'.$questionnum.'" /></td>');
 8242:     $r->print(&Apache::loncommon::end_data_table_row().
 8243:               &Apache::loncommon::end_data_table());
 8244: }
 8245: 
 8246: =pod
 8247: 
 8248: =item num_matches
 8249: 
 8250:    Counts the number of characters that are the same between the two arguments.
 8251: 
 8252:  Arguments:
 8253:    $orig - CODE from the scanline
 8254:    $code - CODE to match against
 8255: 
 8256:  Returns:
 8257:    $count - integer count of the number of same characters between the
 8258:             two arguments
 8259: 
 8260: =cut
 8261: 
 8262: sub num_matches {
 8263:     my ($orig,$code) = @_;
 8264:     my @code=split(//,$code);
 8265:     my @orig=split(//,$orig);
 8266:     my $same=0;
 8267:     for (my $i=0;$i<scalar(@code);$i++) {
 8268: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8269:     }
 8270:     return $same;
 8271: }
 8272: 
 8273: =pod
 8274: 
 8275: =item scantron_get_closely_matching_CODEs
 8276: 
 8277:    Cycles through all CODEs and finds the set that has the greatest
 8278:    number of same characters as the provided CODE
 8279: 
 8280:  Arguments:
 8281:    $allcodes - hash ref returned by &get_codes()
 8282:    $CODE     - CODE from the current scanline
 8283: 
 8284:  Returns:
 8285:    2 element list
 8286:     - first elements is number of how closely matching the best fit is 
 8287:       (5 means best set has 5 matching characters)
 8288:     - second element is an arrary ref containing the set of valid CODEs
 8289:       that best fit the passed in CODE
 8290: 
 8291: =cut
 8292: 
 8293: sub scantron_get_closely_matching_CODEs {
 8294:     my ($allcodes,$CODE)=@_;
 8295:     my @CODEs;
 8296:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8297: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8298:     }
 8299: 
 8300:     return ($#CODEs,$CODEs[-1]);
 8301: }
 8302: 
 8303: =pod
 8304: 
 8305: =item get_codes
 8306: 
 8307:    Builds a hash which has keys of all of the valid CODEs from the selected
 8308:    set of remembered CODEs.
 8309: 
 8310:  Arguments:
 8311:   $old_name - name of the set of remembered CODEs
 8312:   $cdom     - domain of the course
 8313:   $cnum     - internal course name
 8314: 
 8315:  Returns:
 8316:   %allcodes - keys are the valid CODEs, values are all 1
 8317: 
 8318: =cut
 8319: 
 8320: sub get_codes {
 8321:     my ($old_name, $cdom, $cnum) = @_;
 8322:     if (!$old_name) {
 8323: 	$old_name=$env{'form.scantron_CODElist'};
 8324:     }
 8325:     if (!$cdom) {
 8326: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8327:     }
 8328:     if (!$cnum) {
 8329: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8330:     }
 8331:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8332: 				    $cdom,$cnum);
 8333:     my %allcodes;
 8334:     if ($result{"type\0$old_name"} eq 'number') {
 8335: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8336:     } else {
 8337: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8338:     }
 8339:     return %allcodes;
 8340: }
 8341: 
 8342: =pod
 8343: 
 8344: =item scantron_validate_CODE
 8345: 
 8346:    Validates all scanlines in the selected file to not have any
 8347:    invalid or underspecified CODEs and that none of the codes are
 8348:    duplicated if this was requested.
 8349: 
 8350: =cut
 8351: 
 8352: sub scantron_validate_CODE {
 8353:     my ($r,$currentphase) = @_;
 8354:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8355:     if ($scantron_config{'CODElocation'} &&
 8356: 	$scantron_config{'CODEstart'} &&
 8357: 	$scantron_config{'CODElength'}) {
 8358: 	if (!defined($env{'form.scantron_CODElist'})) {
 8359: 	    &FIXME_blow_up()
 8360: 	}
 8361:     } else {
 8362: 	return (0,$currentphase+1);
 8363:     }
 8364:     
 8365:     my %usedCODEs;
 8366: 
 8367:     my %allcodes=&get_codes();
 8368: 
 8369:     my $nav_error;
 8370:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8371:     if ($nav_error) {
 8372:         $r->print(&navmap_errormsg());
 8373:         return(1,$currentphase);
 8374:     }
 8375: 
 8376:     my ($scanlines,$scan_data)=&scantron_getfile();
 8377:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8378: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8379: 	if ($line=~/^[\s\cz]*$/) { next; }
 8380: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8381: 						 $scan_data);
 8382: 	my $CODE=$$scan_record{'scantron.CODE'};
 8383: 	my $error=0;
 8384: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8385: 	    &scantron_get_correction($r,$i,$scan_record,
 8386: 				     \%scantron_config,
 8387: 				     $line,'incorrectCODE',\%allcodes);
 8388: 	    return(1,$currentphase);
 8389: 	}
 8390: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8391: 	    && !$$scan_record{'scantron.useCODE'}) {
 8392: 	    &scantron_get_correction($r,$i,$scan_record,
 8393: 				     \%scantron_config,
 8394: 				     $line,'incorrectCODE',\%allcodes);
 8395: 	    return(1,$currentphase);
 8396: 	}
 8397: 	if (exists($usedCODEs{$CODE}) 
 8398: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8399: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8400: 	    &scantron_get_correction($r,$i,$scan_record,
 8401: 				     \%scantron_config,
 8402: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8403: 	    return(1,$currentphase);
 8404: 	}
 8405: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8406:     }
 8407:     return (0,$currentphase+1);
 8408: }
 8409: 
 8410: =pod
 8411: 
 8412: =item scantron_validate_doublebubble
 8413: 
 8414:    Validates all scanlines in the selected file to not have any
 8415:    bubble lines with multiple bubbles marked.
 8416: 
 8417: =cut
 8418: 
 8419: sub scantron_validate_doublebubble {
 8420:     my ($r,$currentphase) = @_;
 8421:     #get student info
 8422:     my $classlist=&Apache::loncoursedata::get_classlist();
 8423:     my %idmap=&username_to_idmap($classlist);
 8424:     my (undef,undef,$sequence)=
 8425:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8426: 
 8427:     #get scantron line setup
 8428:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8429:     my ($scanlines,$scan_data)=&scantron_getfile();
 8430: 
 8431:     my $navmap = Apache::lonnavmaps::navmap->new();
 8432:     unless (ref($navmap)) {
 8433:         $r->print(&navmap_errormsg());
 8434:         return(1,$currentphase);
 8435:     }
 8436:     my $map=$navmap->getResourceByUrl($sequence);
 8437:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8438:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8439:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8440:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8441: 
 8442:     my $nav_error;
 8443:     if (ref($map)) {
 8444:         $randomorder = $map->randomorder();
 8445:         $randompick = $map->randompick();
 8446:         if ($randomorder || $randompick) {
 8447:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8448:             if ($nav_error) {
 8449:                 $r->print(&navmap_errormsg());
 8450:                 return(1,$currentphase);
 8451:             }
 8452:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8453:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8454:         }
 8455:     } else {
 8456:         $r->print(&navmap_errormsg());
 8457:         return(1,$currentphase);
 8458:     }
 8459: 
 8460:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8461:     if ($nav_error) {
 8462:         $r->print(&navmap_errormsg());
 8463:         return(1,$currentphase);
 8464:     }
 8465: 
 8466:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8467: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8468: 	if ($line=~/^[\s\cz]*$/) { next; }
 8469: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8470: 						 $scan_data,undef,\%idmap,$randomorder,
 8471:                                                  $randompick,$sequence,\@master_seq,
 8472:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8473:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8474: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8475: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8476: 				 'doublebubble',
 8477: 				 $$scan_record{'scantron.doubleerror'},
 8478:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8479:     	return (1,$currentphase);
 8480:     }
 8481:     return (0,$currentphase+1);
 8482: }
 8483: 
 8484: 
 8485: sub scantron_get_maxbubble {
 8486:     my ($nav_error,$scantron_config) = @_;
 8487:     if (defined($env{'form.scantron_maxbubble'}) &&
 8488: 	$env{'form.scantron_maxbubble'}) {
 8489: 	&restore_bubble_lines();
 8490: 	return $env{'form.scantron_maxbubble'};
 8491:     }
 8492: 
 8493:     my (undef, undef, $sequence) =
 8494: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8495: 
 8496:     my $navmap=Apache::lonnavmaps::navmap->new();
 8497:     unless (ref($navmap)) {
 8498:         if (ref($nav_error)) {
 8499:             $$nav_error = 1;
 8500:         }
 8501:         return;
 8502:     }
 8503:     my $map=$navmap->getResourceByUrl($sequence);
 8504:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8505:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8506: 
 8507:     &Apache::lonxml::clear_problem_counter();
 8508: 
 8509:     my $uname       = $env{'user.name'};
 8510:     my $udom        = $env{'user.domain'};
 8511:     my $cid         = $env{'request.course.id'};
 8512:     my $total_lines = 0;
 8513:     %bubble_lines_per_response = ();
 8514:     %first_bubble_line         = ();
 8515:     %subdivided_bubble_lines   = ();
 8516:     %responsetype_per_response = ();
 8517:     %masterseq_id_responsenum  = ();
 8518: 
 8519:     my $response_number = 0;
 8520:     my $bubble_line     = 0;
 8521:     foreach my $resource (@resources) {
 8522:         my $resid = $resource->id();
 8523:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8524:                                                           $udom,undef,$bubbles_per_row);
 8525:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8526: 	    foreach my $part_id (@{$parts}) {
 8527:                 my $lines;
 8528: 
 8529: 	        # TODO - make this a persistent hash not an array.
 8530: 
 8531:                 # optionresponse, matchresponse and rankresponse type items 
 8532:                 # render as separate sub-questions in exam mode.
 8533:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8534:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8535:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8536:                     my ($numbub,$numshown);
 8537:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8538:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8539:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8540:                         }
 8541:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8542:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8543:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8544:                         }
 8545:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8546:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8547:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8548:                         }
 8549:                     }
 8550:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8551:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8552:                     }
 8553:                     my $bubbles_per_row =
 8554:                         &bubblesheet_bubbles_per_row($scantron_config);
 8555:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8556:                     if (($numbub % $bubbles_per_row) != 0) {
 8557:                         $inner_bubble_lines++;
 8558:                     }
 8559:                     for (my $i=0; $i<$numshown; $i++) {
 8560:                         $subdivided_bubble_lines{$response_number} .= 
 8561:                             $inner_bubble_lines.',';
 8562:                     }
 8563:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8564:                     $lines = $numshown * $inner_bubble_lines;
 8565:                 } else {
 8566:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8567:                 }
 8568: 
 8569:                 $first_bubble_line{$response_number} = $bubble_line;
 8570: 	        $bubble_lines_per_response{$response_number} = $lines;
 8571:                 $responsetype_per_response{$response_number} = 
 8572:                     $analysis->{$part_id.'.type'};
 8573:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8574: 	        $response_number++;
 8575: 
 8576: 	        $bubble_line +=  $lines;
 8577: 	        $total_lines +=  $lines;
 8578: 	    }
 8579:         }
 8580:     }
 8581:     &Apache::lonnet::delenv('scantron.');
 8582: 
 8583:     &save_bubble_lines();
 8584:     $env{'form.scantron_maxbubble'} =
 8585: 	$total_lines;
 8586:     return $env{'form.scantron_maxbubble'};
 8587: }
 8588: 
 8589: sub bubblesheet_bubbles_per_row {
 8590:     my ($scantron_config) = @_;
 8591:     my $bubbles_per_row;
 8592:     if (ref($scantron_config) eq 'HASH') {
 8593:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8594:     }
 8595:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8596:         $bubbles_per_row = 10;
 8597:     }
 8598:     return $bubbles_per_row;
 8599: }
 8600: 
 8601: sub scantron_validate_missingbubbles {
 8602:     my ($r,$currentphase) = @_;
 8603:     #get student info
 8604:     my $classlist=&Apache::loncoursedata::get_classlist();
 8605:     my %idmap=&username_to_idmap($classlist);
 8606:     my (undef,undef,$sequence)=
 8607:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8608: 
 8609:     #get scantron line setup
 8610:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8611:     my ($scanlines,$scan_data)=&scantron_getfile();
 8612: 
 8613:     my $navmap = Apache::lonnavmaps::navmap->new();
 8614:     unless (ref($navmap)) {
 8615:         $r->print(&navmap_errormsg());
 8616:         return(1,$currentphase);
 8617:     }
 8618: 
 8619:     my $map=$navmap->getResourceByUrl($sequence);
 8620:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8621:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8622:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8623:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8624: 
 8625:     my $nav_error;
 8626:     if (ref($map)) {
 8627:         $randomorder = $map->randomorder();
 8628:         $randompick = $map->randompick();
 8629:         if ($randomorder || $randompick) {
 8630:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8631:             if ($nav_error) {
 8632:                 $r->print(&navmap_errormsg());
 8633:                 return(1,$currentphase);
 8634:             }
 8635:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8636:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8637:         }
 8638:     } else {
 8639:         $r->print(&navmap_errormsg());
 8640:         return(1,$currentphase);
 8641:     }
 8642: 
 8643: 
 8644:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8645:     if ($nav_error) {
 8646:         $r->print(&navmap_errormsg());
 8647:         return(1,$currentphase);
 8648:     }
 8649: 
 8650:     if (!$max_bubble) { $max_bubble=2**31; }
 8651:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8652: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8653: 	if ($line=~/^[\s\cz]*$/) { next; }
 8654:         my $scan_record =
 8655:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8656:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8657:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8658:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8659: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8660: 	my @to_correct;
 8661: 	
 8662: 	# Probably here's where the error is...
 8663: 
 8664: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8665:             my $lastbubble;
 8666:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8667:                 my $question = $1;
 8668:                 my $subquestion = $2;
 8669:                 my ($first,$responsenum);
 8670:                 if ($randomorder || $randompick) {
 8671:                     $responsenum = $respnumlookup{$question-1};
 8672:                     $first = $startline{$question-1};
 8673:                 } else {
 8674:                     $responsenum = $question-1;
 8675:                     $first = $first_bubble_line{$responsenum};
 8676:                 }
 8677:                 if (!defined($first)) { next; }
 8678:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8679:                 my $subcount = 1;
 8680:                 while ($subcount<$subquestion) {
 8681:                     $first += $subans[$subcount-1];
 8682:                     $subcount ++;
 8683:                 }
 8684:                 my $count = $subans[$subquestion-1];
 8685:                 $lastbubble = $first + $count;
 8686:             } else {
 8687:                 my ($first,$responsenum);
 8688:                 if ($randomorder || $randompick) {
 8689:                     $responsenum = $respnumlookup{$missing-1};
 8690:                     $first = $startline{$missing-1};
 8691:                 } else {
 8692:                     $responsenum = $missing-1;
 8693:                     $first = $first_bubble_line{$responsenum};
 8694:                 }
 8695:                 if (!defined($first)) { next; }
 8696:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8697:             }
 8698:             if ($lastbubble > $max_bubble) { next; }
 8699: 	    push(@to_correct,$missing);
 8700: 	}
 8701: 	if (@to_correct) {
 8702: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8703: 				     $line,'missingbubble',\@to_correct,
 8704:                                      $randomorder,$randompick,\%respnumlookup,
 8705:                                      \%startline);
 8706: 	    return (1,$currentphase);
 8707: 	}
 8708: 
 8709:     }
 8710:     return (0,$currentphase+1);
 8711: }
 8712: 
 8713: sub hand_bubble_option {
 8714:     my (undef, undef, $sequence) =
 8715:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8716:     return if ($sequence eq '');
 8717:     my $navmap = Apache::lonnavmaps::navmap->new();
 8718:     unless (ref($navmap)) {
 8719:         return;
 8720:     }
 8721:     my $needs_hand_bubbles;
 8722:     my $map=$navmap->getResourceByUrl($sequence);
 8723:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8724:     foreach my $res (@resources) {
 8725:         if (ref($res)) {
 8726:             if ($res->is_problem()) {
 8727:                 my $partlist = $res->parts();
 8728:                 foreach my $part (@{ $partlist }) {
 8729:                     my @types = $res->responseType($part);
 8730:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8731:                         $needs_hand_bubbles = 1;
 8732:                         last;
 8733:                     }
 8734:                 }
 8735:             }
 8736:         }
 8737:     }
 8738:     if ($needs_hand_bubbles) {
 8739:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8740:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8741:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8742:                &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 />').
 8743:                '<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;'.
 8744:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8745:     }
 8746:     return;
 8747: }
 8748: 
 8749: sub scantron_process_students {
 8750:     my ($r,$symb) = @_;
 8751: 
 8752:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8753:     if (!$symb) {
 8754: 	return '';
 8755:     }
 8756:     my $default_form_data=&defaultFormData($symb);
 8757: 
 8758:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8759:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8760:     my ($scanlines,$scan_data)=&scantron_getfile();
 8761:     my $classlist=&Apache::loncoursedata::get_classlist();
 8762:     my %idmap=&username_to_idmap($classlist);
 8763:     my $navmap=Apache::lonnavmaps::navmap->new();
 8764:     unless (ref($navmap)) {
 8765:         $r->print(&navmap_errormsg());
 8766:         return '';
 8767:     }
 8768:     my $map=$navmap->getResourceByUrl($sequence);
 8769:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8770:         %grader_randomlists_by_symb);
 8771:     if (ref($map)) {
 8772:         $randomorder = $map->randomorder();
 8773:         $randompick = $map->randompick();
 8774:     } else {
 8775:         $r->print(&navmap_errormsg());
 8776:         return '';
 8777:     }
 8778:     my $nav_error;
 8779:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8780:     if ($randomorder || $randompick) {
 8781:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8782:         if ($nav_error) {
 8783:             $r->print(&navmap_errormsg());
 8784:             return '';
 8785:         }
 8786:     }
 8787:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8788:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8789: 
 8790:     my ($uname,$udom);
 8791:     my $result= <<SCANTRONFORM;
 8792: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8793:   <input type="hidden" name="command" value="scantron_configphase" />
 8794:   $default_form_data
 8795: SCANTRONFORM
 8796:     $r->print($result);
 8797: 
 8798:     my @delayqueue;
 8799:     my (%completedstudents,%scandata);
 8800:     
 8801:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8802:     my $count=&get_todo_count($scanlines,$scan_data);
 8803:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8804:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8805:     $r->print('<br />');
 8806:     my $start=&Time::HiRes::time();
 8807:     my $i=-1;
 8808:     my $started;
 8809: 
 8810:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8811:     if ($nav_error) {
 8812:         $r->print(&navmap_errormsg());
 8813:         return '';
 8814:     }
 8815: 
 8816:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8817:     # the user and return.
 8818: 
 8819:     if ($ssi_error) {
 8820: 	$r->print("</form>");
 8821: 	&ssi_print_error($r);
 8822:         &Apache::lonnet::remove_lock($lock);
 8823: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8824:     }
 8825: 
 8826:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8827:     my $numletts = scalar(keys(%lettdig));
 8828:     my %orderedforcode;
 8829: 
 8830:     while ($i<$scanlines->{'count'}) {
 8831:  	($uname,$udom)=('','');
 8832:  	$i++;
 8833:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8834:  	if ($line=~/^[\s\cz]*$/) { next; }
 8835: 	if ($started) {
 8836: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8837: 	}
 8838: 	$started=1;
 8839:         my %respnumlookup = ();
 8840:         my %startline = ();
 8841:         my $total;
 8842:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8843:  						 $scan_data,undef,\%idmap,$randomorder,
 8844:                                                  $randompick,$sequence,\@master_seq,
 8845:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8846:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8847:                                                  \$total);
 8848:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8849:  					      \%idmap,$i)) {
 8850:   	    &scantron_add_delay(\@delayqueue,$line,
 8851:  				'Unable to find a student that matches',1);
 8852:  	    next;
 8853:   	}
 8854:  	if (exists $completedstudents{$uname}) {
 8855:  	    &scantron_add_delay(\@delayqueue,$line,
 8856:  				'Student '.$uname.' has multiple sheets',2);
 8857:  	    next;
 8858:  	}
 8859:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8860:         my $user = $uname.':'.$usec;
 8861:   	($uname,$udom)=split(/:/,$uname);
 8862: 
 8863:         my $scancode;
 8864:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8865:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8866:             $scancode = $scan_record->{'scantron.CODE'};
 8867:         } else {
 8868:             $scancode = '';
 8869:         }
 8870: 
 8871:         my @mapresources = @resources;
 8872:         if ($randomorder || $randompick) {
 8873:             @mapresources =
 8874:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8875:                              \%orderedforcode);
 8876:         }
 8877:         my (%partids_by_symb,$res_error);
 8878:         foreach my $resource (@mapresources) {
 8879:             my $ressymb;
 8880:             if (ref($resource)) {
 8881:                 $ressymb = $resource->symb();
 8882:             } else {
 8883:                 $res_error = 1;
 8884:                 last;
 8885:             }
 8886:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8887:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8888:                 my $currcode;
 8889:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8890:                     $currcode = $scancode;
 8891:                 }
 8892:                 my ($analysis,$parts) =
 8893:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8894:                                               $uname,$udom,undef,$bubbles_per_row,
 8895:                                               $currcode);
 8896:                 $partids_by_symb{$ressymb} = $parts;
 8897:             } else {
 8898:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8899:             }
 8900:         }
 8901: 
 8902:         if ($res_error) {
 8903:             &scantron_add_delay(\@delayqueue,$line,
 8904:                                 'An error occurred while grading student '.$uname,2);
 8905:             next;
 8906:         }
 8907: 
 8908: 	&Apache::lonxml::clear_problem_counter();
 8909:   	&Apache::lonnet::appenv($scan_record);
 8910: 
 8911: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8912: 	    &scantron_putfile($scanlines,$scan_data);
 8913: 	}
 8914: 	
 8915:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8916:                                    \@mapresources,\%partids_by_symb,
 8917:                                    $bubbles_per_row,$randomorder,$randompick,
 8918:                                    \%respnumlookup,\%startline) 
 8919:             eq 'ssi_error') {
 8920:             $ssi_error = 0; # So end of handler error message does not trigger.
 8921:             $r->print("</form>");
 8922:             &ssi_print_error($r);
 8923:             &Apache::lonnet::remove_lock($lock);
 8924:             return '';      # Why return ''?  Beats me.
 8925:         }
 8926: 
 8927:         if (($scancode) && ($randomorder || $randompick)) {
 8928:             my $parmresult =
 8929:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8930:                                                        '0_examcode',2,$scancode,
 8931:                                                        'string_examcode',$uname,
 8932:                                                        $udom);
 8933:         }
 8934: 	$completedstudents{$uname}={'line'=>$line};
 8935:         if ($env{'form.verifyrecord'}) {
 8936:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8937:             if ($randompick) {
 8938:                 if ($total) {
 8939:                     $lastpos = $total*$scantron_config{'Qlength'};
 8940:                 }
 8941:             }
 8942: 
 8943:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8944:             chomp($studentdata);
 8945:             $studentdata =~ s/\r$//;
 8946:             my $studentrecord = '';
 8947:             my $counter = -1;
 8948:             foreach my $resource (@mapresources) {
 8949:                 my $ressymb = $resource->symb();
 8950:                 ($counter,my $recording) =
 8951:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8952:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8953:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8954:                                              $randompick,\%respnumlookup,\%startline);
 8955:                 $studentrecord .= $recording;
 8956:             }
 8957:             if ($studentrecord ne $studentdata) {
 8958:                 &Apache::lonxml::clear_problem_counter();
 8959:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8960:                                            \@mapresources,\%partids_by_symb,
 8961:                                            $bubbles_per_row,$randomorder,$randompick,
 8962:                                            \%respnumlookup,\%startline)
 8963:                     eq 'ssi_error') {
 8964:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8965:                     $r->print("</form>");
 8966:                     &ssi_print_error($r);
 8967:                     &Apache::lonnet::remove_lock($lock);
 8968:                     delete($completedstudents{$uname});
 8969:                     return '';
 8970:                 }
 8971:                 $counter = -1;
 8972:                 $studentrecord = '';
 8973:                 foreach my $resource (@mapresources) {
 8974:                     my $ressymb = $resource->symb();
 8975:                     ($counter,my $recording) =
 8976:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8977:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8978:                                                  \%scantron_config,\%lettdig,$numletts,
 8979:                                                  $randomorder,$randompick,\%respnumlookup,
 8980:                                                  \%startline);
 8981:                     $studentrecord .= $recording;
 8982:                 }
 8983:                 if ($studentrecord ne $studentdata) {
 8984:                     $r->print('<p><span class="LC_warning">');
 8985:                     if ($scancode eq '') {
 8986:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8987:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8988:                     } else {
 8989:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8990:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8991:                     }
 8992:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8993:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8994:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8995:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8996:                               &Apache::loncommon::start_data_table_row().
 8997:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8998:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8999:                               &Apache::loncommon::end_data_table_row().
 9000:                               &Apache::loncommon::start_data_table_row().
 9001:                               '<td>'.&mt('Stored submissions').'</td>'.
 9002:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9003:                               &Apache::loncommon::end_data_table_row().
 9004:                               &Apache::loncommon::end_data_table().'</p>');
 9005:                 } else {
 9006:                     $r->print('<br /><span class="LC_warning">'.
 9007:                              &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 />'.
 9008:                              &mt("As a consequence, this user's submission history records two tries.").
 9009:                                  '</span><br />');
 9010:                 }
 9011:             }
 9012:         }
 9013:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9014:     } continue {
 9015: 	&Apache::lonxml::clear_problem_counter();
 9016: 	&Apache::lonnet::delenv('scantron.');
 9017:     }
 9018:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9019:     &Apache::lonnet::remove_lock($lock);
 9020: #    my $lasttime = &Time::HiRes::time()-$start;
 9021: #    $r->print("<p>took $lasttime</p>");
 9022: 
 9023:     $r->print("</form>");
 9024:     return '';
 9025: }
 9026: 
 9027: sub graders_resources_pass {
 9028:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9029:         $bubbles_per_row) = @_;
 9030:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9031:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9032:         foreach my $resource (@{$resources}) {
 9033:             my $ressymb = $resource->symb();
 9034:             my ($analysis,$parts) =
 9035:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9036:                                           $env{'user.name'},$env{'user.domain'},
 9037:                                           1,$bubbles_per_row);
 9038:             $grader_partids_by_symb->{$ressymb} = $parts;
 9039:             if (ref($analysis) eq 'HASH') {
 9040:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9041:                     $grader_randomlists_by_symb->{$ressymb} =
 9042:                         $analysis->{'parts_withrandomlist'};
 9043:                 }
 9044:             }
 9045:         }
 9046:     }
 9047:     return;
 9048: }
 9049: 
 9050: =pod
 9051: 
 9052: =item users_order
 9053: 
 9054:   Returns array of resources in current map, ordered based on either CODE,
 9055:   if this is a CODEd exam, or based on student's identity if this is a
 9056:   "NAMEd" exam.
 9057: 
 9058:   Should be used when randomorder and/or randompick applied when the 
 9059:   corresponding exam was printed, prior to students completing bubblesheets 
 9060:   for the version of the exam the student received.
 9061: 
 9062: =cut
 9063: 
 9064: sub users_order  {
 9065:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9066:     my @mapresources;
 9067:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9068:         return @mapresources;
 9069:     }
 9070:     if ($scancode) {
 9071:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9072:             @mapresources = @{$orderedforcode->{$scancode}};
 9073:         } else {
 9074:             $env{'form.CODE'} = $scancode;
 9075:             my $actual_seq =
 9076:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9077:                                                                $master_seq,
 9078:                                                                $user,$scancode,1);
 9079:             if (ref($actual_seq) eq 'ARRAY') {
 9080:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9081:                 if (ref($orderedforcode) eq 'HASH') {
 9082:                     if (@mapresources > 0) {
 9083:                         $orderedforcode->{$scancode} = \@mapresources;
 9084:                     }
 9085:                 }
 9086:             }
 9087:             delete($env{'form.CODE'});
 9088:         }
 9089:     } else {
 9090:         my $actual_seq =
 9091:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9092:                                                            $master_seq,
 9093:                                                            $user,undef,1);
 9094:         if (ref($actual_seq) eq 'ARRAY') {
 9095:             @mapresources =
 9096:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9097:         }
 9098:     }
 9099:     return @mapresources;
 9100: }
 9101: 
 9102: sub grade_student_bubbles {
 9103:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9104:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9105:     my $uselookup = 0;
 9106:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9107:         (ref($startline) eq 'HASH')) {
 9108:         $uselookup = 1;
 9109:     }
 9110: 
 9111:     if (ref($resources) eq 'ARRAY') {
 9112:         my $count = 0;
 9113:         foreach my $resource (@{$resources}) {
 9114:             my $ressymb = $resource->symb();
 9115:             my %form = ('submitted'      => 'scantron',
 9116:                         'grade_target'   => 'grade',
 9117:                         'grade_username' => $uname,
 9118:                         'grade_domain'   => $udom,
 9119:                         'grade_courseid' => $env{'request.course.id'},
 9120:                         'grade_symb'     => $ressymb,
 9121:                         'CODE'           => $scancode
 9122:                        );
 9123:             if ($bubbles_per_row ne '') {
 9124:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9125:             }
 9126:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9127:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9128:             }
 9129:             if (ref($parts) eq 'HASH') {
 9130:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9131:                     foreach my $part (@{$parts->{$ressymb}}) {
 9132:                         if ($uselookup) {
 9133:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9134:                         } else {
 9135:                             $form{'scantron_questnum_start.'.$part} =
 9136:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9137:                         }
 9138:                         $count++;
 9139:                     }
 9140:                 }
 9141:             }
 9142:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9143:             return 'ssi_error' if ($ssi_error);
 9144:             last if (&Apache::loncommon::connection_aborted($r));
 9145:         }
 9146:     }
 9147:     return;
 9148: }
 9149: 
 9150: sub scantron_upload_scantron_data {
 9151:     my ($r,$symb) = @_;
 9152:     my $dom = $env{'request.role.domain'};
 9153:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9154:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9155:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9156:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9157: 							  'domainid',
 9158: 							  'coursename',$dom);
 9159:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9160:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9161:     my $default_form_data=&defaultFormData($symb);
 9162:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9163:     &js_escape(\$nofile_alert);
 9164:     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.");
 9165:     &js_escape(\$nocourseid_alert);
 9166:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9167:     function checkUpload(formname) {
 9168: 	if (formname.upfile.value == "") {
 9169: 	    alert("'.$nofile_alert.'");
 9170: 	    return false;
 9171: 	}
 9172:         if (formname.courseid.value == "") {
 9173:             alert("'.$nocourseid_alert.'");
 9174:             return false;
 9175:         }
 9176: 	formname.submit();
 9177:     }
 9178: 
 9179:     function ToSyllabus() {
 9180:         var cdom = '."'$dom'".';
 9181:         var cnum = document.rules.courseid.value;
 9182:         if (cdom == "" || cdom == null) {
 9183:             return;
 9184:         }
 9185:         if (cnum == "" || cnum == null) {
 9186:            return;
 9187:         }
 9188:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9189:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9190:         return;
 9191:     }
 9192: 
 9193:     '.$formatjs.'
 9194: '));
 9195:     $r->print('
 9196: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9197: 
 9198: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9199: '.$default_form_data.
 9200:   &Apache::lonhtmlcommon::start_pick_box().
 9201:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9202:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9203:   &Apache::lonhtmlcommon::row_closure().
 9204:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9205:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9206:   &Apache::lonhtmlcommon::row_closure().
 9207:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9208:   '<input name="domainid" type="hidden" />'.$domdesc.
 9209:   &Apache::lonhtmlcommon::row_closure());
 9210:     if ($formatoptions) {
 9211:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9212:                   &Apache::lonhtmlcommon::row_closure());
 9213:     }
 9214:     $r->print(
 9215:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9216:   '<input type="file" name="upfile" size="50" />'.
 9217:   &Apache::lonhtmlcommon::row_closure(1).
 9218:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9219: 
 9220: <input name="command" value="scantronupload_save" type="hidden" />
 9221: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9222: </form>
 9223: ');
 9224:     return '';
 9225: }
 9226: 
 9227: sub scantron_upload_dataformat {
 9228:     my ($dom) = @_;
 9229:     my ($formatoptions,$formattitle,$formatjs);
 9230:     $formatjs = <<'END';
 9231: function toggleScantab(form) {
 9232:    return;
 9233: }
 9234: END
 9235:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9236:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9237:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9238:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9239:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9240:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9241:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9242:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9243:                             my ($onclick,$formatextra,$singleline);
 9244:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9245:                             my $count = 0;
 9246:                             foreach my $line (@lines) {
 9247:                                 next if ($line =~ /^#/);
 9248:                                 $singleline = $line;
 9249:                                 $count ++;
 9250:                             }
 9251:                             if ($count > 1) {
 9252:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9253:                                                '<span class="LC_nobreak">'.
 9254:                                                &mt('Bubblesheet type').':&nbsp;'.
 9255:                                                &scantron_scantab().'</span></div>';
 9256:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9257:                                 $formatjs = <<"END";
 9258: function toggleScantab(form) {
 9259:     var divid = 'bubbletype';
 9260:     if (document.getElementById(divid)) {
 9261:         var radioname = 'fileformat';
 9262:         var num = form.elements[radioname].length;
 9263:         if (num) {
 9264:             for (var i=0; i<num; i++) {
 9265:                 if (form.elements[radioname][i].checked) {
 9266:                     var chosen = form.elements[radioname][i].value;
 9267:                     if (chosen == 'dat') {
 9268:                         document.getElementById(divid).style.display = 'none';
 9269:                     } else if (chosen == 'csv') {
 9270:                         document.getElementById(divid).style.display = 'block';
 9271:                     }
 9272:                 }
 9273:             }
 9274:         }
 9275:     }
 9276:     return;
 9277: }
 9278: 
 9279: END
 9280:                             } elsif ($count == 1) {
 9281:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9282:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9283:                             }
 9284:                             $formattitle = &mt('File format');
 9285:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9286:                                              &mt('Plain Text (no delimiters)').
 9287:                                              '</label>'.('&nbsp;'x2).
 9288:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9289:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9290:                         }
 9291:                     }
 9292:                 }
 9293:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9294:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9295:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9296:                         $formattitle = &mt('Bubblesheet type');
 9297:                         $formatoptions = &scantron_scantab();
 9298:                     }
 9299:                 }
 9300:             }
 9301:         }
 9302:     }
 9303:     return ($formatoptions,$formattitle,$formatjs);
 9304: }
 9305: 
 9306: sub scantron_upload_scantron_data_save {
 9307:     my ($r,$symb) = @_;
 9308:     my $doanotherupload=
 9309: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9310: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9311: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9312: 	'</form>'."\n";
 9313:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9314: 	!&Apache::lonnet::allowed('usc',
 9315: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9316: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9317:         unless ($symb) {
 9318: 	    $r->print($doanotherupload);
 9319: 	}
 9320: 	return '';
 9321:     }
 9322:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9323:     my $uploadedfile;
 9324:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9325:     if (length($env{'form.upfile'}) < 2) {
 9326:         $r->print(
 9327:             &Apache::lonhtmlcommon::confirm_success(
 9328:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9329:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9330:     } else {
 9331:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9332:         my $parser;
 9333:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9334:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9335:                 my $is_csv;
 9336:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9337:                 if (@possibles > 1) {
 9338:                     if ($env{'form.fileformat'} eq 'csv') {
 9339:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9340:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9341:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9342:                                     $is_csv = 1;
 9343:                                 }
 9344:                             }
 9345:                         }
 9346:                     }
 9347:                 } elsif (@possibles == 1) {
 9348:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9349:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9350:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9351:                                 $is_csv = 1;
 9352:                             }
 9353:                         }
 9354:                     }
 9355:                 }
 9356:                 if ($is_csv) {
 9357:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9358:                 }
 9359:             }
 9360:         }
 9361:         my $result =
 9362:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9363:                                             $env{'form.courseid'},$env{'form.domainid'});
 9364: 	if ($result =~ m{^/uploaded/}) {
 9365:             $r->print(
 9366:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9367:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9368:                         (length($env{'form.upfile'})-1),
 9369:                         '<span class="LC_filename">'.$result.'</span>'));
 9370:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9371:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9372:                                                        $env{'form.courseid'},$uploadedfile));
 9373: 	} else {
 9374:             $r->print(
 9375:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9376:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9377:                           $result,
 9378: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9379: 	}
 9380:     }
 9381:     if ($symb) {
 9382: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9383:     } else {
 9384: 	$r->print($doanotherupload);
 9385:     }
 9386:     return '';
 9387: }
 9388: 
 9389: sub validate_uploaded_scantron_file {
 9390:     my ($cdom,$cname,$fname) = @_;
 9391:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9392:     my @lines;
 9393:     if ($scanlines ne '-1') {
 9394:         @lines=split("\n",$scanlines,-1);
 9395:     }
 9396:     my $output;
 9397:     if (@lines) {
 9398:         my (%counts,$max_match_format);
 9399:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9400:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9401:         my %idmap = &username_to_idmap($classlist);
 9402:         foreach my $key (keys(%idmap)) {
 9403:             my $lckey = lc($key);
 9404:             $idmap{$lckey} = $idmap{$key};
 9405:         }
 9406:         my %unique_formats;
 9407:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9408:         foreach my $line (@formatlines) {
 9409:             chomp($line);
 9410:             my @config = split(/:/,$line);
 9411:             my $idstart = $config[5];
 9412:             my $idlength = $config[6];
 9413:             if (($idstart ne '') && ($idlength > 0)) {
 9414:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9415:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9416:                 } else {
 9417:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9418:                 }
 9419:             }
 9420:         }
 9421:         foreach my $key (keys(%unique_formats)) {
 9422:             my ($idstart,$idlength) = split(':',$key);
 9423:             %{$counts{$key}} = (
 9424:                                'found'   => 0,
 9425:                                'total'   => 0,
 9426:                               );
 9427:             foreach my $line (@lines) {
 9428:                 next if ($line =~ /^#/);
 9429:                 next if ($line =~ /^[\s\cz]*$/);
 9430:                 my $id = substr($line,$idstart-1,$idlength);
 9431:                 $id = lc($id);
 9432:                 if (exists($idmap{$id})) {
 9433:                     $counts{$key}{'found'} ++;
 9434:                 }
 9435:                 $counts{$key}{'total'} ++;
 9436:             }
 9437:             if ($counts{$key}{'total'}) {
 9438:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9439:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9440:                     $max_match_pct = $percent_match;
 9441:                     $max_match_format = $key;
 9442:                     $found_match_count = $counts{$key}{'found'};
 9443:                     $max_match_count = $counts{$key}{'total'};
 9444:                 }
 9445:             }
 9446:         }
 9447:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9448:             my $format_descs;
 9449:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9450:             for (my $i=0; $i<$numwithformat; $i++) {
 9451:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9452:                 if ($i<$numwithformat-2) {
 9453:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9454:                 } elsif ($i==$numwithformat-2) {
 9455:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9456:                 } elsif ($i==$numwithformat-1) {
 9457:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9458:                 }
 9459:             }
 9460:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9461:             $output .= '<br />';
 9462:             if ($found_match_count == $max_match_count) {
 9463:                 # 100% matching entries
 9464:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9465:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9466:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9467:                 &mt('Comparison of student IDs in the uploaded file with'.
 9468:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9469:                     ' in the file (for the format defined for [_3]).',
 9470:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9471:             } else {
 9472:                 # Not all entries matching? -> Show warning and additional info
 9473:                 $output .=
 9474:                     &Apache::lonhtmlcommon::confirm_success(
 9475:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9476:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9477:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9478:                     &mt('Comparison of student IDs in the uploaded file with'.
 9479:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9480:                         ' in the file (for the format defined for [_3]).',
 9481:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9482:                     '<p class="LC_info">'.
 9483:                     &mt('A low percentage of matches results from one of the following:').
 9484:                     '</p><ul>'.
 9485:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9486:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9487:                                '<i>'.$cdom.'</i>').'</li>'.
 9488:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9489:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9490:                     '</ul>';
 9491:             }
 9492:         }
 9493:     } else {
 9494:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9495:     }
 9496:     return $output;
 9497: }
 9498: 
 9499: sub valid_file {
 9500:     my ($requested_file)=@_;
 9501:     foreach my $filename (sort(&scantron_filenames())) {
 9502: 	if ($requested_file eq $filename) { return 1; }
 9503:     }
 9504:     return 0;
 9505: }
 9506: 
 9507: sub scantron_download_scantron_data {
 9508:     my ($r,$symb) = @_;
 9509:     my $default_form_data=&defaultFormData($symb);
 9510:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9511:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9512:     my $file=$env{'form.scantron_selectfile'};
 9513:     if (! &valid_file($file)) {
 9514: 	$r->print('
 9515: 	<p>
 9516: 	    '.&mt('The requested filename was invalid.').'
 9517:         </p>
 9518: ');
 9519: 	return;
 9520:     }
 9521:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9522:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9523:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9524:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9525:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9526:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9527:     $r->print('
 9528:     <p>
 9529: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9530: 	      '<a href="'.$orig.'">','</a>').'
 9531:     </p>
 9532:     <p>
 9533: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9534: 	      '<a href="'.$corrected.'">','</a>').'
 9535:     </p>
 9536:     <p>
 9537: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9538: 	      '<a href="'.$skipped.'">','</a>').'
 9539:     </p>
 9540: ');
 9541:     return '';
 9542: }
 9543: 
 9544: sub checkscantron_results {
 9545:     my ($r,$symb) = @_;
 9546:     if (!$symb) {return '';}
 9547:     my $cid = $env{'request.course.id'};
 9548:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9549:     my $numletts = scalar(keys(%lettdig));
 9550:     my $cnum = $env{'course.'.$cid.'.num'};
 9551:     my $cdom = $env{'course.'.$cid.'.domain'};
 9552:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9553:     my %record;
 9554:     my %scantron_config =
 9555:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9556:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9557:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9558:     my $classlist=&Apache::loncoursedata::get_classlist();
 9559:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9560:     my $navmap=Apache::lonnavmaps::navmap->new();
 9561:     unless (ref($navmap)) {
 9562:         $r->print(&navmap_errormsg());
 9563:         return '';
 9564:     }
 9565:     my $map=$navmap->getResourceByUrl($sequence);
 9566:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9567:         %grader_randomlists_by_symb,%orderedforcode);
 9568:     if (ref($map)) {
 9569:         $randomorder=$map->randomorder();
 9570:         $randompick=$map->randompick();
 9571:     }
 9572:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9573:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9574:     if ($nav_error) {
 9575:         $r->print(&navmap_errormsg());
 9576:         return '';
 9577:     }
 9578:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9579:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9580:     my ($uname,$udom);
 9581:     my (%scandata,%lastname,%bylast);
 9582:     $r->print('
 9583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9584: 
 9585:     my @delayqueue;
 9586:     my %completedstudents;
 9587: 
 9588:     my $count=&get_todo_count($scanlines,$scan_data);
 9589:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9590:     my ($username,$domain,$started);
 9591:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9592:     if ($nav_error) {
 9593:         $r->print(&navmap_errormsg());
 9594:         return '';
 9595:     }
 9596: 
 9597:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9598:                                           'Processing first student');
 9599:     my $start=&Time::HiRes::time();
 9600:     my $i=-1;
 9601: 
 9602:     while ($i<$scanlines->{'count'}) {
 9603:         ($username,$domain,$uname)=('','','');
 9604:         $i++;
 9605:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9606:         if ($line=~/^[\s\cz]*$/) { next; }
 9607:         if ($started) {
 9608:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9609:                                                      'last student');
 9610:         }
 9611:         $started=1;
 9612:         my $scan_record=
 9613:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9614:                                                      $scan_data);
 9615:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9616:                                               \%idmap,$i)) {
 9617:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9618:                                 'Unable to find a student that matches',1);
 9619:             next;
 9620:         }
 9621:         if (exists $completedstudents{$uname}) {
 9622:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9623:                                 'Student '.$uname.' has multiple sheets',2);
 9624:             next;
 9625:         }
 9626:         my $pid = $scan_record->{'scantron.ID'};
 9627:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9628:         push(@{$bylast{$lastname{$pid}}},$pid);
 9629:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9630:         my $user = $uname.':'.$usec;
 9631:         ($username,$domain)=split(/:/,$uname);
 9632: 
 9633:         my $scancode;
 9634:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9635:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9636:             $scancode = $scan_record->{'scantron.CODE'};
 9637:         } else {
 9638:             $scancode = '';
 9639:         }
 9640: 
 9641:         my @mapresources = @resources;
 9642:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9643:         my %respnumlookup=();
 9644:         my %startline=();
 9645:         if ($randomorder || $randompick) {
 9646:             @mapresources =
 9647:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9648:                              \%orderedforcode);
 9649:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9650:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9651:                                              \%grader_partids_by_symb,\%orderedforcode,
 9652:                                              \%respnumlookup,\%startline);
 9653:             if ($randompick && $total) {
 9654:                 $lastpos = $total*$scantron_config{'Qlength'};
 9655:             }
 9656:         }
 9657:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9658:         chomp($scandata{$pid});
 9659:         $scandata{$pid} =~ s/\r$//;
 9660: 
 9661:         my $counter = -1;
 9662:         foreach my $resource (@mapresources) {
 9663:             my $parts;
 9664:             my $ressymb = $resource->symb();
 9665:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9666:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9667:                 my $currcode;
 9668:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9669:                     $currcode = $scancode;
 9670:                 }
 9671:                 (my $analysis,$parts) =
 9672:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9673:                                               $username,$domain,undef,
 9674:                                               $bubbles_per_row,$currcode);
 9675:             } else {
 9676:                 $parts = $grader_partids_by_symb{$ressymb};
 9677:             }
 9678:             ($counter,my $recording) =
 9679:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9680:                                          $scandata{$pid},$parts,
 9681:                                          \%scantron_config,\%lettdig,$numletts,
 9682:                                          $randomorder,$randompick,
 9683:                                          \%respnumlookup,\%startline);
 9684:             $record{$pid} .= $recording;
 9685:         }
 9686:     }
 9687:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9688:     $r->print('<br />');
 9689:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9690:     $passed = 0;
 9691:     $failed = 0;
 9692:     $numstudents = 0;
 9693:     foreach my $last (sort(keys(%bylast))) {
 9694:         if (ref($bylast{$last}) eq 'ARRAY') {
 9695:             foreach my $pid (sort(@{$bylast{$last}})) {
 9696:                 my $showscandata = $scandata{$pid};
 9697:                 my $showrecord = $record{$pid};
 9698:                 $showscandata =~ s/\s/&nbsp;/g;
 9699:                 $showrecord =~ s/\s/&nbsp;/g;
 9700:                 if ($scandata{$pid} eq $record{$pid}) {
 9701:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9702:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9703: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9704: '</tr>'."\n".
 9705: '<tr class="'.$css_class.'">'."\n".
 9706: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9707:                     $passed ++;
 9708:                 } else {
 9709:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9710:                     $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".
 9711: '</tr>'."\n".
 9712: '<tr class="'.$css_class.'">'."\n".
 9713: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9714: '</tr>'."\n";
 9715:                     $failed ++;
 9716:                 }
 9717:                 $numstudents ++;
 9718:             }
 9719:         }
 9720:     }
 9721:     $r->print('<p>'.
 9722:               &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).',
 9723:                   '<b>',
 9724:                   $numstudents,
 9725:                   '</b>',
 9726:                   $env{'form.scantron_maxbubble'}).
 9727:               '</p>'
 9728:     );
 9729:     $r->print('<p>'
 9730:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9731:              .'<br />'
 9732:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9733:              .'</p>');
 9734:     if ($passed) {
 9735:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9736:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9737:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9738:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9739:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9740:                  $okstudents."\n".
 9741:                  &Apache::loncommon::end_data_table().'<br />');
 9742:     }
 9743:     if ($failed) {
 9744:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9745:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9746:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9747:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9748:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9749:                  $badstudents."\n".
 9750:                  &Apache::loncommon::end_data_table()).'<br />'.
 9751:                  &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.');  
 9752:     }
 9753:     $r->print('</form><br />');
 9754:     return;
 9755: }
 9756: 
 9757: sub verify_scantron_grading {
 9758:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9759:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9760:         $respnumlookup,$startline) = @_;
 9761:     my ($record,%expected,%startpos);
 9762:     return ($counter,$record) if (!ref($resource));
 9763:     return ($counter,$record) if (!$resource->is_problem());
 9764:     my $symb = $resource->symb();
 9765:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9766:     foreach my $part_id (@{$partids}) {
 9767:         $counter ++;
 9768:         $expected{$part_id} = 0;
 9769:         my $respnum = $counter;
 9770:         if ($randomorder || $randompick) {
 9771:             $respnum = $respnumlookup->{$counter};
 9772:             $startpos{$part_id} = $startline->{$counter} + 1;
 9773:         } else {
 9774:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9775:         }
 9776:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9777:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9778:             foreach my $item (@sub_lines) {
 9779:                 $expected{$part_id} += $item;
 9780:             }
 9781:         } else {
 9782:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9783:         }
 9784:     }
 9785:     if ($symb) {
 9786:         my %recorded;
 9787:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9788:         if ($returnhash{'version'}) {
 9789:             my %lasthash=();
 9790:             my $version;
 9791:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9792:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9793:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9794:                 }
 9795:             }
 9796:             foreach my $key (keys(%lasthash)) {
 9797:                 if ($key =~ /\.scantron$/) {
 9798:                     my $value = &unescape($lasthash{$key});
 9799:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9800:                     if ($value eq '') {
 9801:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9802:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9803:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9804:                             }
 9805:                         }
 9806:                     } else {
 9807:                         my @tocheck;
 9808:                         my @items = split(//,$value);
 9809:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9810:                             ($scantron_config->{'Qon'} eq 'number')) {
 9811:                             if (@items < $expected{$part_id}) {
 9812:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9813:                                 my @singles = split(//,$fragment);
 9814:                                 foreach my $pos (@singles) {
 9815:                                     if ($pos eq ' ') {
 9816:                                         push(@tocheck,$pos);
 9817:                                     } else {
 9818:                                         my $next = shift(@items);
 9819:                                         push(@tocheck,$next);
 9820:                                     }
 9821:                                 }
 9822:                             } else {
 9823:                                 @tocheck = @items;
 9824:                             }
 9825:                             foreach my $letter (@tocheck) {
 9826:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9827:                                     if ($letter !~ /^[A-J]$/) {
 9828:                                         $letter = $scantron_config->{'Qoff'};
 9829:                                     }
 9830:                                     $recorded{$part_id} .= $letter;
 9831:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9832:                                     my $digit;
 9833:                                     if ($letter !~ /^[A-J]$/) {
 9834:                                         $digit = $scantron_config->{'Qoff'};
 9835:                                     } else {
 9836:                                         $digit = $lettdig->{$letter};
 9837:                                     }
 9838:                                     $recorded{$part_id} .= $digit;
 9839:                                 }
 9840:                             }
 9841:                         } else {
 9842:                             @tocheck = @items;
 9843:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9844:                                 my $curr_sub = shift(@tocheck);
 9845:                                 my $digit;
 9846:                                 if ($curr_sub =~ /^[A-J]$/) {
 9847:                                     $digit = $lettdig->{$curr_sub}-1;
 9848:                                 }
 9849:                                 if ($curr_sub eq 'J') {
 9850:                                     $digit += scalar($numletts);
 9851:                                 }
 9852:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9853:                                     if ($j == $digit) {
 9854:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9855:                                     } else {
 9856:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9857:                                     }
 9858:                                 }
 9859:                             }
 9860:                         }
 9861:                     }
 9862:                 }
 9863:             }
 9864:         }
 9865:         foreach my $part_id (@{$partids}) {
 9866:             if ($recorded{$part_id} eq '') {
 9867:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9868:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9869:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9870:                     }
 9871:                 }
 9872:             }
 9873:             $record .= $recorded{$part_id};
 9874:         }
 9875:     }
 9876:     return ($counter,$record);
 9877: }
 9878: 
 9879: #-------- end of section for handling grading scantron forms -------
 9880: #
 9881: #-------------------------------------------------------------------
 9882: 
 9883: #-------------------------- Menu interface -------------------------
 9884: #
 9885: #--- Href with symb and command ---
 9886: 
 9887: sub href_symb_cmd {
 9888:     my ($symb,$cmd)=@_;
 9889:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9890: }
 9891: 
 9892: sub grading_menu {
 9893:     my ($request,$symb) = @_;
 9894:     if (!$symb) {return '';}
 9895: 
 9896:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9897:                   'command'=>'individual');
 9898: 
 9899:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9900: 
 9901:     $fields{'command'}='ungraded';
 9902:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9903: 
 9904:     $fields{'command'}='table';
 9905:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9906: 
 9907:     $fields{'command'}='all_for_one';
 9908:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9909: 
 9910:     $fields{'command'}='downloadfilesselect';
 9911:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9912:     
 9913:     $fields{'command'} = 'csvform';
 9914:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9915:     
 9916:     $fields{'command'} = 'processclicker';
 9917:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9918:     
 9919:     $fields{'command'} = 'scantron_selectphase';
 9920:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9921: 
 9922:     $fields{'command'} = 'initialverifyreceipt';
 9923:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9924: 
 9925:     my %permissions;
 9926:     if ($perm{'mgr'}) {
 9927:         $permissions{'either'} = 'F';
 9928:         $permissions{'mgr'} = 'F';
 9929:     }
 9930:     if ($perm{'vgr'}) {
 9931:         $permissions{'either'} = 'F';
 9932:         $permissions{'vgr'} = 'F';
 9933:     }
 9934: 
 9935:     my @menu = ({	categorytitle=>'Hand Grading',
 9936:             items =>[
 9937:                         {       linktext => 'Select individual students to grade',
 9938:                                 url => $url1a,
 9939:                                 permission => $permissions{'either'},
 9940:                                 icon => 'grade_students.png',
 9941:                                 linktitle => 'Grade current resource for a selection of students.'
 9942:                         },
 9943:                         {       linktext => 'Grade ungraded submissions',
 9944:                                 url => $url1b,
 9945:                                 permission => $permissions{'either'},
 9946:                                 icon => 'ungrade_sub.png',
 9947:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9948:                         },
 9949: 
 9950:                         {       linktext => 'Grading table',
 9951:                                 url => $url1c,
 9952:                                 permission => $permissions{'either'},
 9953:                                 icon => 'grading_table.png',
 9954:                                 linktitle => 'Grade current resource for all students.'
 9955:                         },
 9956:                         {       linktext => 'Grade page/folder for one student',
 9957:                                 url => $url1d,
 9958:                                 permission => $permissions{'either'},
 9959:                                 icon => 'grade_PageFolder.png',
 9960:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9961:                         },
 9962:                         {       linktext => 'Download submitted files',
 9963:                                 url => $url1e,
 9964:                                 permission => $permissions{'either'},
 9965:                                 icon => 'download_sub.png',
 9966:                                 linktitle => 'Download all files submitted by students.'
 9967:                         }]},
 9968:                          { categorytitle=>'Automated Grading',
 9969:                items =>[
 9970: 
 9971:                 	    {	linktext => 'Upload Scores',
 9972:                     		url => $url2,
 9973:                     		permission => $permissions{'mgr'},
 9974:                     		icon => 'uploadscores.png',
 9975:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9976:                 	    },
 9977:                 	    {	linktext => 'Process Clicker',
 9978:                     		url => $url3,
 9979:                     		permission => $permissions{'mgr'},
 9980:                     		icon => 'addClickerInfoFile.png',
 9981:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9982:                 	    },
 9983:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9984:                     		url => $url4,
 9985:                     		permission => $permissions{'mgr'},
 9986:                     		icon => 'bubblesheet.png',
 9987:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9988:                 	    },
 9989:                             {   linktext => 'Verify Receipt Number',
 9990:                                 url => $url5,
 9991:                                 permission => $permissions{'either'},
 9992:                                 icon => 'receipt_number.png',
 9993:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9994:                             }
 9995: 
 9996:                     ]
 9997:             });
 9998: 
 9999:     # Create the menu
10000:     my $Str;
10001:     $Str .= '<form method="post" action="" name="gradingMenu">';
10002:     $Str .= '<input type="hidden" name="command" value="" />'.
10003:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10004: 
10005:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10006:     return $Str;    
10007: }
10008: 
10009: sub ungraded {
10010:     my ($request)=@_;
10011:     &submit_options($request);
10012: }
10013: 
10014: sub submit_options_sequence {
10015:     my ($request,$symb) = @_;
10016:     if (!$symb) {return '';}
10017:     &commonJSfunctions($request);
10018:     my $result;
10019: 
10020:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10021:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10022:     $result.=&selectfield(0).
10023:             '<input type="hidden" name="command" value="pickStudentPage" />
10024:             <div>
10025:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10026:             </div>
10027:         </div>
10028:   </form>';
10029:     return $result;
10030: }
10031: 
10032: sub submit_options_table {
10033:     my ($request,$symb) = @_;
10034:     if (!$symb) {return '';}
10035:     &commonJSfunctions($request);
10036:     my $result;
10037: 
10038:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10039:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10040: 
10041:     $result.=&selectfield(1).
10042:             '<input type="hidden" name="command" value="viewgrades" />
10043:             <div>
10044:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10045:             </div>
10046:         </div>
10047:   </form>';
10048:     return $result;
10049: }
10050: 
10051: sub submit_options_download {
10052:     my ($request,$symb) = @_;
10053:     if (!$symb) {return '';}
10054: 
10055:     my $res_error;
10056:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10057:         &response_type($symb,\$res_error);
10058:     if ($res_error) {
10059:         $request->print(&mt('An error occurred retrieving response types'));
10060:         return;
10061:     }
10062:     unless ($numessay) {
10063:         $request->print(&mt('No essayresponse items found'));
10064:         return;
10065:     }
10066:     my $table;
10067:     if (ref($partlist) eq 'ARRAY') {
10068:         if (scalar(@$partlist) > 1 ) {
10069:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10070:         }
10071:     }
10072: 
10073:     &commonJSfunctions($request);
10074: 
10075:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10076:         $table."\n".
10077:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10078:     $result.='
10079: <h2>
10080:   '.&mt('Select Students for whom to Download Submitted Files').'
10081: </h2>'.&selectfield(1).'
10082:                 <input type="hidden" name="command" value="downloadfileslink" />
10083:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10084:             </div>
10085:           </div>
10086: 
10087: 
10088:   </form>';
10089:     return $result;
10090: }
10091: 
10092: #--- Displays the submissions first page -------
10093: sub submit_options {
10094:     my ($request,$symb) = @_;
10095:     if (!$symb) {return '';}
10096: 
10097:     &commonJSfunctions($request);
10098:     my $result;
10099: 
10100:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10101: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10102:     $result.=&selectfield(1).'
10103:                 <input type="hidden" name="command" value="submission" />
10104:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10105:             </div>
10106:           </div>
10107:   </form>';
10108:     return $result;
10109: }
10110: 
10111: sub selectfield {
10112:    my ($full)=@_;
10113:    my %options =
10114:        (&substatus_options,
10115:         'select_form_order' => ['yes','queued','graded','incorrect','all']);
10116:    my $result='<div class="LC_columnSection">
10117: 
10118:     <fieldset>
10119:       <legend>
10120:        '.&mt('Sections').'
10121:       </legend>
10122:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10123:     </fieldset>
10124: 
10125:     <fieldset>
10126:       <legend>
10127:         '.&mt('Groups').'
10128:       </legend>
10129:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10130:     </fieldset>
10131:  
10132:     <fieldset>
10133:       <legend>
10134:         '.&mt('Access Status').'
10135:       </legend>
10136:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10137:     </fieldset>';
10138:     if ($full) {
10139:         $result.='
10140:     <fieldset>
10141:       <legend>
10142:         '.&mt('Submission Status').'
10143:       </legend>'.
10144:        &Apache::loncommon::select_form('all','submitonly',\%options).
10145:    '</fieldset>';
10146:     }
10147:     $result.='</div><br />';
10148:     return $result;
10149: }
10150: 
10151: sub substatus_options {
10152:     return &Apache::lonlocal::texthash(
10153:                                       'yes'       => 'with submissions',
10154:                                       'queued'    => 'in grading queue',
10155:                                       'graded'    => 'with ungraded submissions',
10156:                                       'incorrect' => 'with incorrect submissions',
10157:                                       'all'       => 'with any status',
10158:                                       );
10159: }
10160: 
10161: sub transtatus_options {
10162:     return &Apache::lonlocal::texthash(
10163:                                        'yes'       => 'with score transactions',
10164:                                        'incorrect' => 'with less than full credit',
10165:                                        'all'       => 'with any status',
10166:                                       );
10167: }
10168: 
10169: sub reset_perm {
10170:     undef(%perm);
10171: }
10172: 
10173: sub init_perm {
10174:     &reset_perm();
10175:     foreach my $test_perm ('vgr','mgr','opa') {
10176: 
10177: 	my $scope = $env{'request.course.id'};
10178: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10179: 
10180: 	    $scope .= '/'.$env{'request.course.sec'};
10181: 	    if ( $perm{$test_perm}=
10182: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10183: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10184: 	    } else {
10185: 		delete($perm{$test_perm});
10186: 	    }
10187: 	}
10188:     }
10189: }
10190: 
10191: sub init_old_essays {
10192:     my ($symb,$apath,$adom,$aname) = @_;
10193:     if ($symb ne '') {
10194:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10195:         if (keys(%essays) > 0) {
10196:             $old_essays{$symb} = \%essays;
10197:         }
10198:     }
10199:     return;
10200: }
10201: 
10202: sub reset_old_essays {
10203:     undef(%old_essays);
10204: }
10205: 
10206: sub gather_clicker_ids {
10207:     my %clicker_ids;
10208: 
10209:     my $classlist = &Apache::loncoursedata::get_classlist();
10210: 
10211:     # Set up a couple variables.
10212:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10213:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10214:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10215: 
10216:     foreach my $student (keys(%$classlist)) {
10217:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10218:         my $username = $classlist->{$student}->[$username_idx];
10219:         my $domain   = $classlist->{$student}->[$domain_idx];
10220:         my $clickers =
10221: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10222:         foreach my $id (split(/\,/,$clickers)) {
10223:             $id=~s/^[\#0]+//;
10224:             $id=~s/[\-\:]//g;
10225:             if (exists($clicker_ids{$id})) {
10226: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10227:             } else {
10228: 		$clicker_ids{$id}=$username.':'.$domain;
10229:             }
10230:         }
10231:     }
10232:     return %clicker_ids;
10233: }
10234: 
10235: sub gather_adv_clicker_ids {
10236:     my %clicker_ids;
10237:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10238:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10239:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10240:     foreach my $element (sort(keys(%coursepersonnel))) {
10241:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10242:             my ($puname,$pudom)=split(/\:/,$person);
10243:             my $clickers =
10244: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10245:             foreach my $id (split(/\,/,$clickers)) {
10246: 		$id=~s/^[\#0]+//;
10247:                 $id=~s/[\-\:]//g;
10248: 		if (exists($clicker_ids{$id})) {
10249: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10250: 		} else {
10251: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10252: 		}
10253:             }
10254:         }
10255:     }
10256:     return %clicker_ids;
10257: }
10258: 
10259: sub clicker_grading_parameters {
10260:     return ('gradingmechanism' => 'scalar',
10261:             'upfiletype' => 'scalar',
10262:             'specificid' => 'scalar',
10263:             'pcorrect' => 'scalar',
10264:             'pincorrect' => 'scalar');
10265: }
10266: 
10267: sub process_clicker {
10268:     my ($r,$symb)=@_;
10269:     if (!$symb) {return '';}
10270:     my $result=&checkforfile_js();
10271:     $result.=&Apache::loncommon::start_data_table().
10272:              &Apache::loncommon::start_data_table_header_row().
10273:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10274:              &Apache::loncommon::end_data_table_header_row().
10275:              &Apache::loncommon::start_data_table_row()."<td>\n";
10276: # Attempt to restore parameters from last session, set defaults if not present
10277:     my %Saveable_Parameters=&clicker_grading_parameters();
10278:     &Apache::loncommon::restore_course_settings('grades_clicker',
10279:                                                  \%Saveable_Parameters);
10280:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10281:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10282:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10283:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10284: 
10285:     my %checked;
10286:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10287:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10288:           $checked{$gradingmechanism}=' checked="checked"';
10289:        }
10290:     }
10291: 
10292:     my $upload=&mt("Evaluate File");
10293:     my $type=&mt("Type");
10294:     my $attendance=&mt("Award points just for participation");
10295:     my $personnel=&mt("Correctness determined from response by course personnel");
10296:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10297:     my $given=&mt("Correctness determined from given list of answers").' '.
10298:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10299:     my $pcorrect=&mt("Percentage points for correct solution");
10300:     my $pincorrect=&mt("Percentage points for incorrect solution");
10301:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10302:                                                    {'iclicker' => 'i>clicker',
10303:                                                     'interwrite' => 'interwrite PRS',
10304:                                                     'turning' => 'Turning Technologies'});
10305:     $symb = &Apache::lonenc::check_encrypt($symb);
10306:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10307: function sanitycheck() {
10308: // Accept only integer percentages
10309:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10310:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10311: // Find out grading choice
10312:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10313:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10314:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10315:       }
10316:    }
10317: // By default, new choice equals user selection
10318:    newgradingchoice=gradingchoice;
10319: // Not good to give more points for false answers than correct ones
10320:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10321:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10322:    }
10323: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10324:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10325:       document.forms.gradesupload.pcorrect.value=100;
10326:       document.forms.gradesupload.pincorrect.value=100;
10327:    }
10328: // If the values are different, cannot be attendance only
10329:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10330:        (gradingchoice=='attendance')) {
10331:        newgradingchoice='personnel';
10332:    }
10333: // Change grading choice to new one
10334:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10335:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10336:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10337:       } else {
10338:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10339:       }
10340:    }
10341: // Remember the old state
10342:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10343: }
10344: ENDUPFORM
10345:     $result.= <<ENDUPFORM;
10346: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10347: <input type="hidden" name="symb" value="$symb" />
10348: <input type="hidden" name="command" value="processclickerfile" />
10349: <input type="file" name="upfile" size="50" />
10350: <br /><label>$type: $selectform</label>
10351: ENDUPFORM
10352:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10353:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10354:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10355: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10356: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10357: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10358: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10359: <br />&nbsp;&nbsp;&nbsp;
10360: <input type="text" name="givenanswer" size="50" />
10361: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10362: ENDGRADINGFORM
10363:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10364:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10365:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10366: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10367: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10368: </form>
10369: ENDPERCFORM
10370:     $result.='</td>'.
10371:              &Apache::loncommon::end_data_table_row().
10372:              &Apache::loncommon::end_data_table();
10373:     return $result;
10374: }
10375: 
10376: sub process_clicker_file {
10377:     my ($r,$symb) = @_;
10378:     if (!$symb) {return '';}
10379: 
10380:     my %Saveable_Parameters=&clicker_grading_parameters();
10381:     &Apache::loncommon::store_course_settings('grades_clicker',
10382:                                               \%Saveable_Parameters);
10383:     my $result='';
10384:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10385: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10386: 	return $result;
10387:     }
10388:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10389:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10390:         return $result;
10391:     }
10392:     my $foundgiven=0;
10393:     if ($env{'form.gradingmechanism'} eq 'given') {
10394:         $env{'form.givenanswer'}=~s/^\s*//gs;
10395:         $env{'form.givenanswer'}=~s/\s*$//gs;
10396:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10397:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10398:         my @answers=split(/\,/,$env{'form.givenanswer'});
10399:         $foundgiven=$#answers+1;
10400:     }
10401:     my %clicker_ids=&gather_clicker_ids();
10402:     my %correct_ids;
10403:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10404: 	%correct_ids=&gather_adv_clicker_ids();
10405:     }
10406:     if ($env{'form.gradingmechanism'} eq 'specific') {
10407: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10408: 	   $correct_id=~tr/a-z/A-Z/;
10409: 	   $correct_id=~s/\s//gs;
10410: 	   $correct_id=~s/^[\#0]+//;
10411:            $correct_id=~s/[\-\:]//g;
10412:            if ($correct_id) {
10413: 	      $correct_ids{$correct_id}='specified';
10414:            }
10415:         }
10416:     }
10417:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10418: 	$result.=&mt('Score based on attendance only');
10419:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10420:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10421:     } else {
10422: 	my $number=0;
10423: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10424: 	foreach my $id (sort(keys(%correct_ids))) {
10425: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10426: 	    if ($correct_ids{$id} eq 'specified') {
10427: 		$result.=&mt('specified');
10428: 	    } else {
10429: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10430: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10431: 	    }
10432: 	    $number++;
10433: 	}
10434:         $result.="</p>\n";
10435:         if ($number==0) {
10436:             $result .=
10437:                  &Apache::lonhtmlcommon::confirm_success(
10438:                      &mt('No IDs found to determine correct answer'),1);
10439:             return $result;
10440:         }
10441:     }
10442:     if (length($env{'form.upfile'}) < 2) {
10443:         $result .=
10444:             &Apache::lonhtmlcommon::confirm_success(
10445:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10446:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10447:         return $result;
10448:     }
10449:     my $mimetype;
10450:     if ($env{'form.upfiletype'} eq 'iclicker') {
10451:         my $mm = new File::MMagic;
10452:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10453:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10454:             $result.= '<p>'.
10455:                 &Apache::lonhtmlcommon::confirm_success(
10456:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10457:             return $result;
10458:         }
10459:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10460:         $result .= '<p>'.
10461:             &Apache::lonhtmlcommon::confirm_success(
10462:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10463:         return $result;
10464:     }
10465: 
10466: # Were able to get all the info needed, now analyze the file
10467: 
10468:     $result.=&Apache::loncommon::studentbrowser_javascript();
10469:     $symb = &Apache::lonenc::check_encrypt($symb);
10470:     $result.=&Apache::loncommon::start_data_table().
10471:              &Apache::loncommon::start_data_table_header_row().
10472:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10473:              &Apache::loncommon::end_data_table_header_row().
10474:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10475: <td>
10476: <form method="post" action="/adm/grades" name="clickeranalysis">
10477: <input type="hidden" name="symb" value="$symb" />
10478: <input type="hidden" name="command" value="assignclickergrades" />
10479: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10480: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10481: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10482: ENDHEADER
10483:     if ($env{'form.gradingmechanism'} eq 'given') {
10484:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10485:     } 
10486:     my %responses;
10487:     my @questiontitles;
10488:     my $errormsg='';
10489:     my $number=0;
10490:     if ($env{'form.upfiletype'} eq 'iclicker') {
10491:         if ($mimetype eq 'text/plain') {
10492:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10493:         } elsif ($mimetype eq 'text/html') {
10494:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10495:         }
10496:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10497:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10498:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10499:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10500:     }
10501:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10502:              '<input type="hidden" name="number" value="'.$number.'" />'.
10503:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10504:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10505:              '<br />';
10506:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10507:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10508:        return $result;
10509:     } 
10510: # Remember Question Titles
10511: # FIXME: Possibly need delimiter other than ":"
10512:     for (my $i=0;$i<$number;$i++) {
10513:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10514:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10515:     }
10516:     my $correct_count=0;
10517:     my $student_count=0;
10518:     my $unknown_count=0;
10519: # Match answers with usernames
10520: # FIXME: Possibly need delimiter other than ":"
10521:     foreach my $id (keys(%responses)) {
10522:        if ($correct_ids{$id}) {
10523:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10524:           $correct_count++;
10525:        } elsif ($clicker_ids{$id}) {
10526:           if ($clicker_ids{$id}=~/\,/) {
10527: # More than one user with the same clicker!
10528:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10529:                            &Apache::loncommon::start_data_table_row()."<td>".
10530:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10531:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10532:                            "<select name='multi".$id."'>";
10533:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10534:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10535:              }
10536:              $result.='</select>';
10537:              $unknown_count++;
10538:           } else {
10539: # Good: found one and only one user with the right clicker
10540:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10541:              $student_count++;
10542:           }
10543:        } else {
10544:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10545:                            &Apache::loncommon::start_data_table_row()."<td>".
10546:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10547:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10548:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10549:                    "\n".&mt("Domain").": ".
10550:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10551:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10552:           $unknown_count++;
10553:        }
10554:     }
10555:     $result.='<hr />'.
10556:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10557:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10558:        if ($correct_count==0) {
10559:           $errormsg.="Found no correct answers for grading!";
10560:        } elsif ($correct_count>1) {
10561:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10562:        }
10563:     }
10564:     if ($number<1) {
10565:        $errormsg.="Found no questions.";
10566:     }
10567:     if ($errormsg) {
10568:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10569:     } else {
10570:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10571:     }
10572:     $result.='</form></td>'.
10573:              &Apache::loncommon::end_data_table_row().
10574:              &Apache::loncommon::end_data_table();
10575:     return $result;
10576: }
10577: 
10578: sub iclicker_eval {
10579:     my ($questiontitles,$responses)=@_;
10580:     my $number=0;
10581:     my $errormsg='';
10582:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10583:         my %components=&Apache::loncommon::record_sep($line);
10584:         my @entries=map {$components{$_}} (sort(keys(%components)));
10585: 	if ($entries[0] eq 'Question') {
10586: 	    for (my $i=3;$i<$#entries;$i+=6) {
10587: 		$$questiontitles[$number]=$entries[$i];
10588: 		$number++;
10589: 	    }
10590: 	}
10591: 	if ($entries[0]=~/^\#/) {
10592: 	    my $id=$entries[0];
10593: 	    my @idresponses;
10594: 	    $id=~s/^[\#0]+//;
10595: 	    for (my $i=0;$i<$number;$i++) {
10596: 		my $idx=3+$i*6;
10597:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10598: 		push(@idresponses,$entries[$idx]);
10599: 	    }
10600: 	    $$responses{$id}=join(',',@idresponses);
10601: 	}
10602:     }
10603:     return ($errormsg,$number);
10604: }
10605: 
10606: sub iclickerxml_eval {
10607:     my ($questiontitles,$responses)=@_;
10608:     my $number=0;
10609:     my $errormsg='';
10610:     my @state;
10611:     my %respbyid;
10612:     my $p = HTML::Parser->new
10613:     (
10614:         xml_mode => 1,
10615:         start_h =>
10616:             [sub {
10617:                  my ($tagname,$attr) = @_;
10618:                  push(@state,$tagname);
10619:                  if ("@state" eq "ssn p") {
10620:                      my $title = $attr->{qn};
10621:                      $title =~ s/(^\s+|\s+$)//g;
10622:                      $questiontitles->[$number]=$title;
10623:                  } elsif ("@state" eq "ssn p v") {
10624:                      my $id = $attr->{id};
10625:                      my $entry = $attr->{ans};
10626:                      $id=~s/^[\#0]+//;
10627:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10628:                      $respbyid{$id}[$number] = $entry;
10629:                  }
10630:             }, "tagname, attr"],
10631:          end_h =>
10632:                [sub {
10633:                    my ($tagname) = @_;
10634:                    if ("@state" eq "ssn p") {
10635:                        $number++;
10636:                    }
10637:                    pop(@state);
10638:                 }, "tagname"],
10639:     );
10640: 
10641:     $p->parse($env{'form.upfile'});
10642:     $p->eof;
10643:     foreach my $id (keys(%respbyid)) {
10644:         $responses->{$id}=join(',',@{$respbyid{$id}});
10645:     }
10646:     return ($errormsg,$number);
10647: }
10648: 
10649: sub interwrite_eval {
10650:     my ($questiontitles,$responses)=@_;
10651:     my $number=0;
10652:     my $errormsg='';
10653:     my $skipline=1;
10654:     my $questionnumber=0;
10655:     my %idresponses=();
10656:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10657:         my %components=&Apache::loncommon::record_sep($line);
10658:         my @entries=map {$components{$_}} (sort(keys(%components)));
10659:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10660:         if ($entries[1] eq 'Response') { $skipline=1; }
10661:         next if $skipline;
10662:         if ($entries[0]!=$questionnumber) {
10663:            $questionnumber=$entries[0];
10664:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10665:            $number++;
10666:         }
10667:         my $id=$entries[4];
10668:         $id=~s/^[\#0]+//;
10669:         $id=~s/^v\d*\://i;
10670:         $id=~s/[\-\:]//g;
10671:         $idresponses{$id}[$number]=$entries[6];
10672:     }
10673:     foreach my $id (keys(%idresponses)) {
10674:        $$responses{$id}=join(',',@{$idresponses{$id}});
10675:        $$responses{$id}=~s/^\s*\,//;
10676:     }
10677:     return ($errormsg,$number);
10678: }
10679: 
10680: sub turning_eval {
10681:     my ($questiontitles,$responses)=@_;
10682:     my $number=0;
10683:     my $errormsg='';
10684:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10685:         my %components=&Apache::loncommon::record_sep($line);
10686:         my @entries=map {$components{$_}} (sort(keys(%components)));
10687:         if ($#entries>$number) { $number=$#entries; }
10688:         my $id=$entries[0];
10689:         my @idresponses;
10690:         $id=~s/^[\#0]+//;
10691:         unless ($id) { next; }
10692:         for (my $idx=1;$idx<=$#entries;$idx++) {
10693:             $entries[$idx]=~s/\,/\;/g;
10694:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10695:             push(@idresponses,$entries[$idx]);
10696:         }
10697:         $$responses{$id}=join(',',@idresponses);
10698:     }
10699:     for (my $i=1; $i<=$number; $i++) {
10700:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10701:     }
10702:     return ($errormsg,$number);
10703: }
10704: 
10705: sub assign_clicker_grades {
10706:     my ($r,$symb) = @_;
10707:     if (!$symb) {return '';}
10708: # See which part we are saving to
10709:     my $res_error;
10710:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10711:     if ($res_error) {
10712:         return &navmap_errormsg();
10713:     }
10714: # FIXME: This should probably look for the first handgradeable part
10715:     my $part=$$partlist[0];
10716: # Start screen output
10717:     my $result = &Apache::loncommon::start_data_table(). 
10718:                  &Apache::loncommon::start_data_table_header_row().
10719:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10720:                  &Apache::loncommon::end_data_table_header_row().
10721:                  &Apache::loncommon::start_data_table_row().'<td>';
10722: # Get correct result
10723: # FIXME: Possibly need delimiter other than ":"
10724:     my @correct=();
10725:     my $gradingmechanism=$env{'form.gradingmechanism'};
10726:     my $number=$env{'form.number'};
10727:     if ($gradingmechanism ne 'attendance') {
10728:        foreach my $key (keys(%env)) {
10729:           if ($key=~/^form\.correct\:/) {
10730:              my @input=split(/\,/,$env{$key});
10731:              for (my $i=0;$i<=$#input;$i++) {
10732:                  if (($correct[$i]) && ($input[$i]) &&
10733:                      ($correct[$i] ne $input[$i])) {
10734:                     $result.='<br /><span class="LC_warning">'.
10735:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10736:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10737:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10738:                     $correct[$i]=$input[$i];
10739:                  }
10740:              }
10741:           }
10742:        }
10743:        for (my $i=0;$i<$number;$i++) {
10744:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10745:              $result.='<br /><span class="LC_error">'.
10746:                       &mt('No correct result given for question "[_1]"!',
10747:                           $env{'form.question:'.$i}).'</span>';
10748:           }
10749:        }
10750:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10751:     }
10752: # Start grading
10753:     my $pcorrect=$env{'form.pcorrect'};
10754:     my $pincorrect=$env{'form.pincorrect'};
10755:     my $storecount=0;
10756:     my %users=();
10757:     foreach my $key (keys(%env)) {
10758:        my $user='';
10759:        if ($key=~/^form\.student\:(.*)$/) {
10760:           $user=$1;
10761:        }
10762:        if ($key=~/^form\.unknown\:(.*)$/) {
10763:           my $id=$1;
10764:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10765:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10766:           } elsif ($env{'form.multi'.$id}) {
10767:              $user=$env{'form.multi'.$id};
10768:           }
10769:        }
10770:        if ($user) {
10771:           if ($users{$user}) {
10772:              $result.='<br /><span class="LC_warning">'.
10773:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10774:                       '</span><br />';
10775:           }
10776:           $users{$user}=1;
10777:           my @answer=split(/\,/,$env{$key});
10778:           my $sum=0;
10779:           my $realnumber=$number;
10780:           for (my $i=0;$i<$number;$i++) {
10781:              if  ($correct[$i] eq '-') {
10782:                 $realnumber--;
10783:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10784:                 if ($gradingmechanism eq 'attendance') {
10785:                    $sum+=$pcorrect;
10786:                 } elsif ($correct[$i] eq '*') {
10787:                    $sum+=$pcorrect;
10788:                 } else {
10789: # We actually grade if correct or not
10790:                    my $increment=$pincorrect;
10791: # Special case: numerical answer "0"
10792:                    if ($correct[$i] eq '0') {
10793:                       if ($answer[$i]=~/^[0\.]+$/) {
10794:                          $increment=$pcorrect;
10795:                       }
10796: # General numerical answer, both evaluate to something non-zero
10797:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10798:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10799:                          $increment=$pcorrect;
10800:                       }
10801: # Must be just alphanumeric
10802:                    } elsif ($answer[$i] eq $correct[$i]) {
10803:                       $increment=$pcorrect;
10804:                    }
10805:                    $sum+=$increment;
10806:                 }
10807:              }
10808:           }
10809:           my $ave=$sum/(100*$realnumber);
10810: # Store
10811:           my ($username,$domain)=split(/\:/,$user);
10812:           my %grades=();
10813:           $grades{"resource.$part.solved"}='correct_by_override';
10814:           $grades{"resource.$part.awarded"}=$ave;
10815:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10816:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10817:                                                  $env{'request.course.id'},
10818:                                                  $domain,$username);
10819:           if ($returncode ne 'ok') {
10820:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10821:           } else {
10822:              $storecount++;
10823:           }
10824:        }
10825:     }
10826: # We are done
10827:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10828:              '</td>'.
10829:              &Apache::loncommon::end_data_table_row().
10830:              &Apache::loncommon::end_data_table();
10831:     return $result;
10832: }
10833: 
10834: sub navmap_errormsg {
10835:     return '<div class="LC_error">'.
10836:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10837:            &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>').
10838:            '</div>';
10839: }
10840: 
10841: sub startpage {
10842:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
10843:     my %args;
10844:     if ($onload) {
10845:          my %loaditems = (
10846:                         'onload' => $onload,
10847:                       );
10848:          $args{'add_entries'} = \%loaditems;
10849:     }
10850:     if ($nomenu) {
10851:         $args{'only_body'} = 1;
10852:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
10853:     } else {
10854:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10855:         $args{'bread_crumbs'} = $crumbs;
10856:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
10857:     }
10858:     unless ($nodisplayflag) {
10859:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
10860:     }
10861: }
10862: 
10863: sub select_problem {
10864:     my ($r)=@_;
10865:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10866:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
10867:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10868:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10869: }
10870: 
10871: sub handler {
10872:     my $request=$_[0];
10873:     &reset_caches();
10874:     if ($request->header_only) {
10875:         &Apache::loncommon::content_type($request,'text/html');
10876:         $request->send_http_header;
10877:         return OK;
10878:     }
10879:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10880: 
10881: # see what command we need to execute
10882:  
10883:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10884:     my $command=$commands[0];
10885: 
10886:     &init_perm();
10887:     if (!$env{'request.course.id'}) {
10888:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10889:                 ($command =~ /^scantronupload/)) {
10890:             # Not in a course.
10891:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10892:             return HTTP_NOT_ACCEPTABLE;
10893:         }
10894:     } elsif (!%perm) {
10895:         $request->internal_redirect('/adm/quickgrades');
10896:         return OK;
10897:     }
10898:     &Apache::loncommon::content_type($request,'text/html');
10899:     $request->send_http_header;
10900: 
10901:     if ($#commands > 0) {
10902: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10903:     }
10904: 
10905: # see what the symb is
10906: 
10907:     my $symb=$env{'form.symb'};
10908:     unless ($symb) {
10909:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10910:        $symb=&Apache::lonnet::symbread($url);
10911:     }
10912:     &Apache::lonenc::check_decrypt(\$symb);
10913: 
10914:     $ssi_error = 0;
10915:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10916: #
10917: # Not called from a resource, but inside a course
10918: #
10919:         &startpage($request,undef,[],1,1);
10920:         &select_problem($request);
10921:     } else {
10922:         if ($command eq 'submission' && $perm{'vgr'}) {
10923:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
10924:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10925:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10926:                     &choose_task_version_form($symb,$env{'form.student'},
10927:                                               $env{'form.userdom'});
10928:             }
10929:             my $divforres;
10930:             if ($env{'form.student'} eq '') {
10931:                 $js .= &part_selector_js();
10932:                 $onload = "toggleParts('gradesub');";
10933:             } else {
10934:                 $divforres = 1;
10935:             }
10936:             my $head_extra = $js;
10937:             unless ($env{'form.vProb'} eq 'no') {
10938:                 my $csslinks = &Apache::loncommon::css_links($symb);
10939:                 if ($csslinks) {
10940:                     $head_extra .= "\n$csslinks";
10941:                 }
10942:             }
10943:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
10944:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
10945:             if ($versionform) {
10946:                 if ($divforres) {
10947:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
10948:                 }
10949:                 $request->print($versionform);
10950:             }
10951:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
10952:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10953:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10954:                 &choose_task_version_form($symb,$env{'form.student'},
10955:                                           $env{'form.userdom'},
10956:                                           $env{'form.inhibitmenu'});
10957:             my $head_extra = $js;
10958:             unless ($env{'form.vProb'} eq 'no') {
10959:                 my $csslinks = &Apache::loncommon::css_links($symb);
10960:                 if ($csslinks) {
10961:                     $head_extra .= "\n$csslinks";
10962:                 }
10963:             }
10964:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
10965:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
10966:             if ($versionform) {
10967:                 $request->print($versionform);
10968:             }
10969:             $request->print('<br clear="all" />');
10970:             $request->print(&show_previous_task_version($request,$symb));
10971:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10972:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10973:                                        {href=>'',text=>'Select student'}],1,1);
10974:             &pickStudentPage($request,$symb);
10975:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10976:             my $csslinks;
10977:             unless ($env{'form.vProb'} eq 'no') {
10978:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
10979:             }
10980:             &startpage($request,$symb,
10981:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10982:                                        {href=>'',text=>'Select student'},
10983:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
10984:             &displayPage($request,$symb);
10985:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10986:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10987:                                        {href=>'',text=>'Select student'},
10988:                                        {href=>'',text=>'Grade student'},
10989:                                        {href=>'',text=>'Store grades'}],1,1);
10990:             &updateGradeByPage($request,$symb);
10991:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10992:             my $csslinks;
10993:             unless ($env{'form.vProb'} eq 'no') {
10994:                 $csslinks = &Apache::loncommon::css_links($symb);
10995:             }
10996:             &startpage($request,$symb,[{href=>'',text=>'...'},
10997:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
10998:             &processGroup($request,$symb);
10999:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11000:             &startpage($request,$symb);
11001:             $request->print(&grading_menu($request,$symb));
11002:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
11003:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11004:             $request->print(&submit_options($request,$symb));
11005:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11006:             my $js = &part_selector_js();
11007:             my $onload = "toggleParts('gradesub');";
11008:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11009:                        undef,undef,undef,undef,undef,$js,$onload);
11010:             $request->print(&listStudents($request,$symb,'graded'));
11011:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11012:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11013:             $request->print(&submit_options_table($request,$symb));
11014:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11015:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11016:             $request->print(&submit_options_sequence($request,$symb));
11017:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11018:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11019:             $request->print(&viewgrades($request,$symb));
11020:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11021:             &startpage($request,$symb,[{href=>'',text=>'...'},
11022:                                        {href=>'',text=>'Store grades'}]);
11023:             $request->print(&processHandGrade($request,$symb));
11024:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11025:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11026:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11027:                                                                              text=>"Modify grades"},
11028:                                        {href=>'', text=>"Store grades"}]);
11029:             $request->print(&editgrades($request,$symb));
11030:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11031:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11032:             $request->print(&initialverifyreceipt($request,$symb));
11033:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
11034:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11035:                                        {href=>'',text=>'Verification Result'}]);
11036:             $request->print(&verifyreceipt($request,$symb));
11037:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11038:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11039:             $request->print(&process_clicker($request,$symb));
11040:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11041:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11042:                                        {href=>'', text=>'Process clicker file'}]);
11043:             $request->print(&process_clicker_file($request,$symb));
11044:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11045:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11046:                                        {href=>'', text=>'Process clicker file'},
11047:                                        {href=>'', text=>'Store grades'}]);
11048:             $request->print(&assign_clicker_grades($request,$symb));
11049:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
11050:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11051:             $request->print(&upcsvScores_form($request,$symb));
11052:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11053:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11054:             $request->print(&csvupload($request,$symb));
11055:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11056:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11057:             $request->print(&csvuploadmap($request,$symb));
11058:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11059:             if ($env{'form.associate'} ne 'Reverse Association') {
11060:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11061:                 $request->print(&csvuploadoptions($request,$symb));
11062:             } else {
11063:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11064:                     $env{'form.upfile_associate'} = 'reverse';
11065:                 } else {
11066:                     $env{'form.upfile_associate'} = 'forward';
11067:                 }
11068:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11069:                 $request->print(&csvuploadmap($request,$symb));
11070:             }
11071:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11072:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11073:             $request->print(&csvuploadassign($request,$symb));
11074:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11075:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11076:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11077:             $request->print(&scantron_selectphase($request,undef,$symb));
11078:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11079:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11080:             $request->print(&scantron_do_warning($request,$symb));
11081:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11082:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11083:             $request->print(&scantron_validate_file($request,$symb));
11084:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11085:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11086:             $request->print(&scantron_process_students($request,$symb));
11087:         } elsif ($command eq 'scantronupload' &&
11088:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11089:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11090:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11091:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11092:             $request->print(&scantron_upload_scantron_data($request,$symb));
11093:         } elsif ($command eq 'scantronupload_save' &&
11094:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11095:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11096:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11097:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11098:         } elsif ($command eq 'scantron_download' &&
11099:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11100:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11101:             $request->print(&scantron_download_scantron_data($request,$symb));
11102:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11103:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11104:             $request->print(&checkscantron_results($request,$symb));
11105:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11106:             my $js = &part_selector_js();
11107:             my $onload = "toggleParts('gradingMenu');";
11108:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11109:                        undef,undef,undef,undef,undef,$js,$onload);
11110:             $request->print(&submit_options_download($request,$symb));
11111:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11112:             &startpage($request,$symb,
11113:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11114:     {href=>'', text=>'Download submitted files'}],
11115:                undef,undef,undef,undef,undef,undef,undef,1);
11116:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11117:             &submit_download_link($request,$symb);
11118:         } elsif ($command) {
11119:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11120:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11121:         }
11122:     }
11123:     if ($ssi_error) {
11124: 	&ssi_print_error($request);
11125:     }
11126:     $request->print(&Apache::loncommon::end_page());
11127:     &reset_caches();
11128:     return OK;
11129: }
11130: 
11131: 1;
11132: 
11133: __END__;
11134: 
11135: 
11136: =head1 NAME
11137: 
11138: Apache::grades
11139: 
11140: =head1 SYNOPSIS
11141: 
11142: Handles the viewing of grades.
11143: 
11144: This is part of the LearningOnline Network with CAPA project
11145: described at http://www.lon-capa.org.
11146: 
11147: =head1 OVERVIEW
11148: 
11149: Do an ssi with retries:
11150: While I'd love to factor out this with the vesrion in lonprintout,
11151: 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
11152: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11153: 
11154: At least the logic that drives this has been pulled out into loncommon.
11155: 
11156: 
11157: 
11158: ssi_with_retries - Does the server side include of a resource.
11159:                      if the ssi call returns an error we'll retry it up to
11160:                      the number of times requested by the caller.
11161:                      If we still have a problem, no text is appended to the
11162:                      output and we set some global variables.
11163:                      to indicate to the caller an SSI error occurred.  
11164:                      All of this is supposed to deal with the issues described
11165:                      in LON-CAPA BZ 5631 see:
11166:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11167:                      by informing the user that this happened.
11168: 
11169: Parameters:
11170:   resource   - The resource to include.  This is passed directly, without
11171:                interpretation to lonnet::ssi.
11172:   form       - The form hash parameters that guide the interpretation of the resource
11173:                
11174:   retries    - Number of retries allowed before giving up completely.
11175: Returns:
11176:   On success, returns the rendered resource identified by the resource parameter.
11177: Side Effects:
11178:   The following global variables can be set:
11179:    ssi_error                - If an unrecoverable error occurred this becomes true.
11180:                               It is up to the caller to initialize this to false
11181:                               if desired.
11182:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11183:                               of the resource that could not be rendered by the ssi
11184:                               call.
11185:    ssi_error_message   - The error string fetched from the ssi response
11186:                               in the event of an error.
11187: 
11188: 
11189: =head1 HANDLER SUBROUTINE
11190: 
11191: ssi_with_retries()
11192: 
11193: =head1 SUBROUTINES
11194: 
11195: =over
11196: 
11197: =item scantron_get_correction() : 
11198: 
11199:    Builds the interface screen to interact with the operator to fix a
11200:    specific error condition in a specific scanline
11201: 
11202:  Arguments:
11203:     $r           - Apache request object
11204:     $i           - number of the current scanline
11205:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11206:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11207:     $line        - full contents of the current scanline
11208:     $error       - error condition, valid values are
11209:                    'incorrectCODE', 'duplicateCODE',
11210:                    'doublebubble', 'missingbubble',
11211:                    'duplicateID', 'incorrectID'
11212:     $arg         - extra information needed
11213:        For errors:
11214:          - duplicateID   - paper number that this studentID was seen before on
11215:          - duplicateCODE - array ref of the paper numbers this CODE was
11216:                            seen on before
11217:          - incorrectCODE - current incorrect CODE 
11218:          - doublebubble  - array ref of the bubble lines that have double
11219:                            bubble errors
11220:          - missingbubble - array ref of the bubble lines that have missing
11221:                            bubble errors
11222: 
11223:    $randomorder - True if exam folder has randomorder set
11224:    $randompick  - True if exam folder has randompick set
11225:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11226:                      for current line to question number used for same question
11227:                      in "Master Seqence" (as seen by Course Coordinator).
11228:    $startline   - Reference to hash where key is question number (0 is first)
11229:                   and value is number of first bubble line for current student
11230:                   or code-based randompick and/or randomorder.
11231: 
11232: 
11233: =item  scantron_get_maxbubble() : 
11234: 
11235:    Arguments:
11236:        $nav_error  - Reference to scalar which is a flag to indicate a
11237:                       failure to retrieve a navmap object.
11238:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11239:        calling routine should trap the error condition and display the warning
11240:        found in &navmap_errormsg().
11241: 
11242:        $scantron_config - Reference to bubblesheet format configuration hash.
11243: 
11244:    Returns the maximum number of bubble lines that are expected to
11245:    occur. Does this by walking the selected sequence rendering the
11246:    resource and then checking &Apache::lonxml::get_problem_counter()
11247:    for what the current value of the problem counter is.
11248: 
11249:    Caches the results to $env{'form.scantron_maxbubble'},
11250:    $env{'form.scantron.bubble_lines.n'}, 
11251:    $env{'form.scantron.first_bubble_line.n'} and
11252:    $env{"form.scantron.sub_bubblelines.n"}
11253:    which are the total number of bubble lines, the number of bubble
11254:    lines for response n and number of the first bubble line for response n,
11255:    and a comma separated list of numbers of bubble lines for sub-questions
11256:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11257: 
11258: 
11259: =item  scantron_validate_missingbubbles() : 
11260: 
11261:    Validates all scanlines in the selected file to not have any
11262:     answers that don't have bubbles that have not been verified
11263:     to be bubble free.
11264: 
11265: =item  scantron_process_students() : 
11266: 
11267:    Routine that does the actual grading of the bubblesheet information.
11268: 
11269:    The parsed scanline hash is added to %env 
11270: 
11271:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11272:    foreach resource , with the form data of
11273: 
11274: 	'submitted'     =>'scantron' 
11275: 	'grade_target'  =>'grade',
11276: 	'grade_username'=> username of student
11277: 	'grade_domain'  => domain of student
11278: 	'grade_courseid'=> of course
11279: 	'grade_symb'    => symb of resource to grade
11280: 
11281:     This triggers a grading pass. The problem grading code takes care
11282:     of converting the bubbled letter information (now in %env) into a
11283:     valid submission.
11284: 
11285: =item  scantron_upload_scantron_data() :
11286: 
11287:     Creates the screen for adding a new bubblesheet data file to a course.
11288: 
11289: =item  scantron_upload_scantron_data_save() : 
11290: 
11291:    Adds a provided bubble information data file to the course if user
11292:    has the correct privileges to do so. 
11293: 
11294: =item  valid_file() :
11295: 
11296:    Validates that the requested bubble data file exists in the course.
11297: 
11298: =item  scantron_download_scantron_data() : 
11299: 
11300:    Shows a list of the three internal files (original, corrected,
11301:    skipped) for a specific bubblesheet data file that exists in the
11302:    course.
11303: 
11304: =item  scantron_validate_ID() : 
11305: 
11306:    Validates all scanlines in the selected file to not have any
11307:    invalid or underspecified student/employee IDs
11308: 
11309: =item navmap_errormsg() :
11310: 
11311:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11312:    Should be called whenever the request to instantiate a navmap object fails.  
11313: 
11314: =back
11315: 
11316: =cut

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