File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.58: download - view: text, annotated - select for diffs
Fri Dec 17 15:22:13 2021 UTC (2 years, 4 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  Backport 1.785, 1.786

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.58 2021/12/17 15:22:13 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::bridgetask();
   48: use Apache::lontexconvert();
   49: use HTML::Parser();
   50: use File::MMagic;
   51: use String::Similarity;
   52: use LONCAPA;
   53: 
   54: use POSIX qw(floor);
   55: 
   56: 
   57: 
   58: my %perm=();
   59: my %old_essays=();
   60: 
   61: #  These variables are used to recover from ssi errors
   62: 
   63: my $ssi_retries = 5;
   64: my $ssi_error;
   65: my $ssi_error_resource;
   66: my $ssi_error_message;
   67: 
   68: 
   69: sub ssi_with_retries {
   70:     my ($resource, $retries, %form) = @_;
   71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   72:     if ($response->is_error) {
   73: 	$ssi_error          = 1;
   74: 	$ssi_error_resource = $resource;
   75: 	$ssi_error_message  = $response->code . " " . $response->message;
   76:     }
   77: 
   78:     return $content;
   79: 
   80: }
   81: #
   82: #  Prodcuces an ssi retry failure error message to the user:
   83: #
   84: 
   85: sub ssi_print_error {
   86:     my ($r) = @_;
   87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   88:     $r->print('
   89: <br />
   90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   91: <p>
   92: '.&mt('Unable to retrieve a resource from a server:').'<br />
   93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   94: '.&mt('Error:').' '.$ssi_error_message.'
   95: </p>
   96: <p>'.
   97: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   99: '</p>');
  100:     return;
  101: }
  102: 
  103: #
  104: # --- Retrieve the parts from the metadata file.---
  105: # Returns an array of everything that the resources stores away
  106: #
  107: 
  108: sub getpartlist {
  109:     my ($symb,$errorref) = @_;
  110: 
  111:     my $navmap   = Apache::lonnavmaps::navmap->new();
  112:     unless (ref($navmap)) {
  113:         if (ref($errorref)) { 
  114:             $$errorref = 'navmap';
  115:             return;
  116:         }
  117:     }
  118:     my $res      = $navmap->getBySymb($symb);
  119:     my $partlist = $res->parts();
  120:     my $url      = $res->src();
  121:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  122: 
  123:     my @stores;
  124:     foreach my $part (@{ $partlist }) {
  125: 	foreach my $key (@metakeys) {
  126: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  127: 	}
  128:     }
  129:     return @stores;
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: #--- Count responseIDs, essayresponse items, and dropbox items ---
  147: #--- Sets response_error pointer to "1" if navmaps object broken ---
  148: sub response_type {
  149:     my ($symb,$response_error) = @_;
  150: 
  151:     my $navmap = Apache::lonnavmaps::navmap->new();
  152:     unless (ref($navmap)) {
  153:         if (ref($response_error)) {
  154:             $$response_error = 1;
  155:         }
  156:         return;
  157:     }
  158:     my $res = $navmap->getBySymb($symb);
  159:     unless (ref($res)) {
  160:         $$response_error = 1;
  161:         return;
  162:     }
  163:     my $partlist = $res->parts();
  164:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  165:     my %vPart = 
  166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  167:     my (%response_types,%handgrade);
  168:     foreach my $part (@{ $partlist }) {
  169: 	next if (%vPart && !exists($vPart{$part}));
  170: 
  171: 	my @types = $res->responseType($part);
  172: 	my @ids = $res->responseIds($part);
  173: 	for (my $i=0; $i < scalar(@ids); $i++) {
  174:             $numresp ++;
  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  176:             if ($types[$i] eq 'essay') {
  177:                 $numessay ++;
  178:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  179:                     $numdropbox ++;
  180:                 }
  181:             }
  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
  183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  184: 				     '.handgrade',$symb);
  185: 	}
  186:     }
  187:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  188: }
  189: 
  190: sub flatten_responseType {
  191:     my ($responseType) = @_;
  192:     my @part_response_id =
  193: 	map { 
  194: 	    my $part = $_;
  195: 	    map {
  196: 		[$part,$_]
  197: 		} sort(keys(%{ $responseType->{$part} }));
  198: 	} sort(keys(%$responseType));
  199:     return @part_response_id;
  200: }
  201: 
  202: sub get_display_part {
  203:     my ($partID,$symb)=@_;
  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  205:     if (defined($display) and $display ne '') {
  206:         $display.= ' (<span class="LC_internal_info">'
  207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  208:     } else {
  209: 	$display=$partID;
  210:     }
  211:     return $display;
  212: }
  213: 
  214: #--- Show parts and response type
  215: sub showResourceInfo {
  216:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  217:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  218:         return '<br clear="all">';
  219:     }
  220:     my $coltitle = &mt('Problem Part Shown');
  221:     if ($checkboxes) {
  222:         $coltitle = &mt('Problem Part');
  223:     } else {
  224:         my $checkedparts = 0;
  225:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  226:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  227:                 $checkedparts ++;
  228:             }
  229:         }
  230:         if ($checkedparts == scalar(@{$partlist})) {
  231:             return '<br clear="all">';
  232:         }
  233:         if ($uploads) {
  234:             $coltitle = &mt('Problem Part Selected');
  235:         }
  236:     }
  237:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  238:     if ($checkboxes) {
  239:         my $legend = &mt('Parts to display');
  240:         if ($uploads) {
  241:             $legend = &mt('Part(s) with dropbox');
  242:         }
  243:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  244:                    '<span class="LC_nobreak">'.
  245:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  246:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  247:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  248:                    &mt('Selected parts').'</label></span>'.
  249:                    '<div id="LC_partselector" style="display:none">';
  250:     }
  251:     $result .= &Apache::loncommon::start_data_table()
  252:               .&Apache::loncommon::start_data_table_header_row();
  253:     if ($checkboxes) {
  254:         $result .= '<th>'.&mt('Display?').'</th>';
  255:     }
  256:     $result .= '<th>'.$coltitle.'</th>'
  257:               .'<th>'.&mt('Res. ID').'</th>'
  258:               .'<th>'.&mt('Type').'</th>'
  259:               .&Apache::loncommon::end_data_table_header_row();
  260:     my %partsseen;
  261:     foreach my $partID (sort(keys(%$responseType))) {
  262:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  263:             my $responsetype = $responseType->{$partID}->{$resID};
  264:             if ($uploads) {
  265:                 next unless ($responsetype eq 'essay');
  266:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  267:             }
  268:             my $display_part=&get_display_part($partID,$symb);
  269:             if (exists($partsseen{$partID})) {
  270:                 $result.=&Apache::loncommon::continue_data_table_row();
  271:             } else {
  272:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  273:                 $result.=&Apache::loncommon::start_data_table_row().
  274:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  275:                 if ($checkboxes) {
  276:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  277:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  278:                 } else {
  279:                     $result.=$display_part.'</td>';
  280:                 }
  281:             }
  282:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  283:                     .'<td>'.&mt($responsetype).'</td>'
  284:                     .&Apache::loncommon::end_data_table_row();
  285:         }
  286:     }
  287:     $result.=&Apache::loncommon::end_data_table();
  288:     if ($checkboxes) {
  289:         $result .= '</div></fieldset>';
  290:     }
  291:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  292:     if (!keys(%partsseen)) {
  293:         $result = '';
  294:         if ($uploads) {
  295:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  296:                    '<p class="LC_info">'.
  297:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  298:                    '</p>';
  299:         } else {
  300:             return '<br clear="all" />';
  301:         }
  302:     }  
  303:     return $result;
  304: }
  305: 
  306: sub part_selector_js {
  307:     my $js = <<"END";
  308: function toggleParts(formname) {
  309:     if (document.getElementById('LC_partselector')) {
  310:         var index = '';
  311:         if (document.forms.length) {
  312:             for (var i=0; i<document.forms.length; i++) {
  313:                 if (document.forms[i].name == formname) {
  314:                     index = i;
  315:                     break;
  316:                 }
  317:             }
  318:         }
  319:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  320:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  321:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  322:                    var val = document.forms[index].elements['chooseparts'][i].value;
  323:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  324:                         document.getElementById('LC_partselector').style.display = 'block';
  325:                     } else {
  326:                         document.getElementById('LC_partselector').style.display = 'none';
  327:                     }
  328:                 }
  329:             }
  330:         }
  331:     }
  332: }
  333: END
  334:     return &Apache::lonhtmlcommon::scripttag($js);
  335: }
  336: 
  337: sub reset_caches {
  338:     &reset_analyze_cache();
  339:     &reset_perm();
  340:     &reset_old_essays();
  341: }
  342: 
  343: {
  344:     my %analyze_cache;
  345:     my %analyze_cache_formkeys;
  346: 
  347:     sub reset_analyze_cache {
  348: 	undef(%analyze_cache);
  349:         undef(%analyze_cache_formkeys);
  350:     }
  351: 
  352:     sub get_analyze {
  353: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  354: 	my $key = "$symb\0$uname\0$udom";
  355:         if ($type eq 'randomizetry') {
  356:             if ($trial ne '') {
  357:                 $key .= "\0".$trial;
  358:             }
  359:         }
  360: 	if (exists($analyze_cache{$key})) {
  361:             my $getupdate = 0;
  362:             if (ref($add_to_hash) eq 'HASH') {
  363:                 foreach my $item (keys(%{$add_to_hash})) {
  364:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  365:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  366:                             $getupdate = 1;
  367:                             last;
  368:                         }
  369:                     } else {
  370:                         $getupdate = 1;
  371:                     }
  372:                 }
  373:             }
  374:             if (!$getupdate) {
  375:                 return $analyze_cache{$key};
  376:             }
  377:         }
  378: 
  379: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  380: 	$url=&Apache::lonnet::clutter($url);
  381:         my %form = ('grade_target'      => 'analyze',
  382:                     'grade_domain'      => $udom,
  383:                     'grade_symb'        => $symb,
  384:                     'grade_courseid'    =>  $env{'request.course.id'},
  385:                     'grade_username'    => $uname,
  386:                     'grade_noincrement' => $no_increment);
  387:         if ($bubbles_per_row ne '') {
  388:             $form{'bubbles_per_row'} = $bubbles_per_row;
  389:         }
  390:         if ($type eq 'randomizetry') {
  391:             $form{'grade_questiontype'} = $type;
  392:             if ($rndseed ne '') {
  393:                 $form{'grade_rndseed'} = $rndseed;
  394:             }
  395:         }
  396:         if (ref($add_to_hash)) {
  397:             %form = (%form,%{$add_to_hash});
  398:         }
  399: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  400: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  401: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  402:         if (ref($add_to_hash) eq 'HASH') {
  403:             $analyze_cache_formkeys{$key} = $add_to_hash;
  404:         } else {
  405:             $analyze_cache_formkeys{$key} = {};
  406:         }
  407: 	return $analyze_cache{$key} = \%analyze;
  408:     }
  409: 
  410:     sub get_order {
  411: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  412: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  413: 	return $analyze->{"$partid.$respid.shown"};
  414:     }
  415: 
  416:     sub get_radiobutton_correct_foil {
  417: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  418: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  419:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  420:         if (ref($foils) eq 'ARRAY') {
  421: 	    foreach my $foil (@{$foils}) {
  422: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  423: 		    return $foil;
  424: 	        }
  425: 	    }
  426: 	}
  427:     }
  428: 
  429:     sub scantron_partids_tograde {
  430:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  431:         my (%analysis,@parts);
  432:         if (ref($resource)) {
  433:             my $symb = $resource->symb();
  434:             my $add_to_form;
  435:             if ($check_for_randomlist) {
  436:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  437:             }
  438:             if ($scancode) {
  439:                 if (ref($add_to_form) eq 'HASH') {
  440:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  441:                 } else {
  442:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  443:                 }
  444:             }
  445:             my $analyze =
  446:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  447:                              undef,undef,undef,$bubbles_per_row);
  448:             if (ref($analyze) eq 'HASH') {
  449:                 %analysis = %{$analyze};
  450:             }
  451:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  452:                 foreach my $part (@{$analysis{'parts'}}) {
  453:                     my ($id,$respid) = split(/\./,$part);
  454:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  455:                         push(@parts,$part);
  456:                     }
  457:                 }
  458:             }
  459:         }
  460:         return (\%analysis,\@parts);
  461:     }
  462: 
  463: }
  464: 
  465: #--- Clean response type for display
  466: #--- Currently filters option/rank/radiobutton/match/essay/Task
  467: #        response types only.
  468: sub cleanRecord {
  469:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  470: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  471:     my $grayFont = '<span class="LC_internal_info">';
  472:     if ($response =~ /^(option|rank)$/) {
  473: 	my %answer=&Apache::lonnet::str2hash($answer);
  474:         my @answer = %answer;
  475:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  476: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  477: 	my ($toprow,$bottomrow);
  478: 	foreach my $foil (@$order) {
  479: 	    if ($grading{$foil} == 1) {
  480: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  481: 	    } else {
  482: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  483: 	    }
  484: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  485: 	}
  486: 	return '<blockquote><table border="1">'.
  487: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  488: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  489: 	    $bottomrow.'</tr></table></blockquote>';
  490:     } elsif ($response eq 'match') {
  491: 	my %answer=&Apache::lonnet::str2hash($answer);
  492:         my @answer = %answer;
  493:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  494: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  495: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  496: 	my ($toprow,$middlerow,$bottomrow);
  497: 	foreach my $foil (@$order) {
  498: 	    my $item=shift(@items);
  499: 	    if ($grading{$foil} == 1) {
  500: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  501: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  502: 	    } else {
  503: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  504: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  505: 	    }
  506: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  507: 	}
  508: 	return '<blockquote><table border="1">'.
  509: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  510: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  511: 	    $middlerow.'</tr>'.
  512: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  513: 	    $bottomrow.'</tr></table></blockquote>';
  514:     } elsif ($response eq 'radiobutton') {
  515: 	my %answer=&Apache::lonnet::str2hash($answer);
  516:         my @answer = %answer;
  517:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  518: 	my ($toprow,$bottomrow);
  519: 	my $correct = 
  520: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  521: 	foreach my $foil (@$order) {
  522: 	    if (exists($answer{$foil})) {
  523: 		if ($foil eq $correct) {
  524: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  525: 		} else {
  526: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  527: 		}
  528: 	    } else {
  529: 		$toprow.='<td>'.&mt('false').'</td>';
  530: 	    }
  531: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  532: 	}
  533: 	return '<blockquote><table border="1">'.
  534: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  535: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  536: 	    $bottomrow.'</tr></table></blockquote>';
  537:     } elsif ($response eq 'essay') {
  538: 	if (! exists ($env{'form.'.$symb})) {
  539: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  540: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  541: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  542: 
  543: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  544: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  545: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  546: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  547: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  548: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  549: 	}
  550:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  551: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  552:     } elsif ( $response eq 'organic') {
  553:         my $result=&mt('Smile representation: [_1]',
  554:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  555: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  556: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  557: 	return $result;
  558:     } elsif ( $response eq 'Task') {
  559: 	if ( $answer eq 'SUBMITTED') {
  560: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  561: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  562: 	    return $result;
  563: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  564: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  565: 			       keys(%{$record}));
  566: 	    return join('<br />',($version,@matches));
  567: 			       
  568: 			       
  569: 	} else {
  570: 	    my $result =
  571: 		'<p>'
  572: 		.&mt('Overall result: [_1]',
  573: 		     $record->{$version."resource.$respid.$partid.status"})
  574: 		.'</p>';
  575: 	    
  576: 	    $result .= '<ul>';
  577: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  578: 			     keys(%{$record}));
  579: 	    foreach my $grade (sort(@grade)) {
  580: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  581: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  582: 				     $dim, $record->{$grade}).
  583: 			  '</li>';
  584: 	    }
  585: 	    $result.='</ul>';
  586: 	    return $result;
  587: 	}
  588:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  589:         # Respect multiple input fields, see Bug #5409 
  590: 	$answer = 
  591: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  592: 							      $answer);
  593: 	return $answer;
  594:     }
  595:     return &HTML::Entities::encode($answer, '"<>&');
  596: }
  597: 
  598: #-- A couple of common js functions
  599: sub commonJSfunctions {
  600:     my $request = shift;
  601:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  602:     function radioSelection(radioButton) {
  603: 	var selection=null;
  604: 	if (radioButton.length > 1) {
  605: 	    for (var i=0; i<radioButton.length; i++) {
  606: 		if (radioButton[i].checked) {
  607: 		    return radioButton[i].value;
  608: 		}
  609: 	    }
  610: 	} else {
  611: 	    if (radioButton.checked) return radioButton.value;
  612: 	}
  613: 	return selection;
  614:     }
  615: 
  616:     function pullDownSelection(selectOne) {
  617: 	var selection="";
  618: 	if (selectOne.length > 1) {
  619: 	    for (var i=0; i<selectOne.length; i++) {
  620: 		if (selectOne[i].selected) {
  621: 		    return selectOne[i].value;
  622: 		}
  623: 	    }
  624: 	} else {
  625:             // only one value it must be the selected one
  626: 	    return selectOne.value;
  627: 	}
  628:     }
  629: COMMONJSFUNCTIONS
  630: }
  631: 
  632: #--- Dumps the class list with usernames,list of sections,
  633: #--- section, ids and fullnames for each user.
  634: sub getclasslist {
  635:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  636:     my @getsec;
  637:     my @getgroup;
  638:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  639:     if (!ref($getsec)) {
  640: 	if ($getsec ne '' && $getsec ne 'all') {
  641: 	    @getsec=($getsec);
  642: 	}
  643:     } else {
  644: 	@getsec=@{$getsec};
  645:     }
  646:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  647:     if (!ref($getgroup)) {
  648: 	if ($getgroup ne '' && $getgroup ne 'all') {
  649: 	    @getgroup=($getgroup);
  650: 	}
  651:     } else {
  652: 	@getgroup=@{$getgroup};
  653:     }
  654:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  655: 
  656:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  657:     # Bail out if we were unable to get the classlist
  658:     return if (! defined($classlist));
  659:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  660:     #
  661:     my %sections;
  662:     my %fullnames;
  663:     my ($cdom,$cnum,$partlist);
  664:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  665:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  666:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  667:         my $res_error;
  668:         ($partlist) = &response_type($symb,\$res_error);
  669:     }
  670:     foreach my $student (keys(%$classlist)) {
  671:         my $end      = 
  672:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  673:         my $start    = 
  674:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  675:         my $id       = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  677:         my $section  = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  679:         my $fullname = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  681:         my $status   = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  683:         my $group   = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  685: 	# filter students according to status selected
  686: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  687: 	    if (!($stu_status =~ $status)) {
  688: 		delete($classlist->{$student});
  689: 		next;
  690: 	    }
  691: 	}
  692: 	# filter students according to groups selected
  693: 	my @stu_groups = split(/,/,$group);
  694: 	if (@getgroup) {
  695: 	    my $exclude = 1;
  696: 	    foreach my $grp (@getgroup) {
  697: 	        foreach my $stu_group (@stu_groups) {
  698: 	            if ($stu_group eq $grp) {
  699: 	                $exclude = 0;
  700:     	            } 
  701: 	        }
  702:     	        if (($grp eq 'none') && !$group) {
  703:         	    $exclude = 0;
  704:         	}
  705: 	    }
  706: 	    if ($exclude) {
  707: 	        delete($classlist->{$student});
  708: 		next;
  709: 	    }
  710: 	}
  711:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  712:             my $udom =
  713:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  714:             my $uname =
  715:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  716:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  717:                 if ($submitonly eq 'queued') {
  718:                     my %queue_status =
  719:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  720:                                                                 $udom,$uname);
  721:                     if (!defined($queue_status{'gradingqueue'})) {
  722:                         delete($classlist->{$student});
  723:                         next;
  724:                     }
  725:                 } else {
  726:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  727:                     my $submitted = 0;
  728:                     my $graded = 0;
  729:                     my $incorrect = 0;
  730:                     foreach (keys(%status)) {
  731:                         $submitted = 1 if ($status{$_} ne 'nothing');
  732:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  733:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  734: 
  735:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  736:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  737:                             $submitted = 0;
  738:                         }
  739:                     }
  740:                     if (!$submitted && ($submitonly eq 'yes' ||
  741:                                         $submitonly eq 'incorrect' ||
  742:                                         $submitonly eq 'graded')) {
  743:                         delete($classlist->{$student});
  744:                         next;
  745:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  746:                         delete($classlist->{$student});
  747:                         next;
  748:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  749:                         delete($classlist->{$student});
  750:                         next;
  751:                     }
  752:                 }
  753:             }
  754:         }
  755: 	$section = ($section ne '' ? $section : 'none');
  756: 	if (&canview($section)) {
  757: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  758: 		$sections{$section}++;
  759: 		if ($classlist->{$student}) {
  760: 		    $fullnames{$student}=$fullname;
  761: 		}
  762: 	    } else {
  763: 		delete($classlist->{$student});
  764: 	    }
  765: 	} else {
  766: 	    delete($classlist->{$student});
  767: 	}
  768:     }
  769:     my @sections = sort(keys(%sections));
  770:     return ($classlist,\@sections,\%fullnames);
  771: }
  772: 
  773: sub canmodify {
  774:     my ($sec)=@_;
  775:     if ($perm{'mgr'}) {
  776: 	if (!defined($perm{'mgr_section'})) {
  777: 	    # can modify whole class
  778: 	    return 1;
  779: 	} else {
  780: 	    if ($sec eq $perm{'mgr_section'}) {
  781: 		#can modify the requested section
  782: 		return 1;
  783: 	    } else {
  784: 		# can't modify the requested section
  785: 		return 0;
  786: 	    }
  787: 	}
  788:     }
  789:     #can't modify
  790:     return 0;
  791: }
  792: 
  793: sub canview {
  794:     my ($sec)=@_;
  795:     if ($perm{'vgr'}) {
  796: 	if (!defined($perm{'vgr_section'})) {
  797: 	    # can view whole class
  798: 	    return 1;
  799: 	} else {
  800: 	    if ($sec eq $perm{'vgr_section'}) {
  801: 		#can view the requested section
  802: 		return 1;
  803: 	    } else {
  804: 		# can't view the requested section
  805: 		return 0;
  806: 	    }
  807: 	}
  808:     }
  809:     #can't view
  810:     return 0;
  811: }
  812: 
  813: #--- Retrieve the grade status of a student for all the parts
  814: sub student_gradeStatus {
  815:     my ($symb,$udom,$uname,$partlist) = @_;
  816:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  817:     my %partstatus = ();
  818:     foreach (@$partlist) {
  819: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  820: 	$status              = 'nothing' if ($status eq '');
  821: 	$partstatus{$_}      = $status;
  822: 	my $subkey           = "resource.$_.submitted_by";
  823: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  824:     }
  825:     return %partstatus;
  826: }
  827: 
  828: # hidden form and javascript that calls the form
  829: # Use by verifyscript and viewgrades
  830: # Shows a student's view of problem and submission
  831: sub jscriptNform {
  832:     my ($symb) = @_;
  833:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  834:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  835: 	'    function viewOneStudent(user,domain) {'."\n".
  836: 	'	document.onestudent.student.value = user;'."\n".
  837: 	'	document.onestudent.userdom.value = domain;'."\n".
  838: 	'	document.onestudent.submit();'."\n".
  839: 	'    }'."\n".
  840: 	"\n");
  841:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  842: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  843: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  844: 	'<input type="hidden" name="command" value="submission" />'."\n".
  845: 	'<input type="hidden" name="student" value="" />'."\n".
  846: 	'<input type="hidden" name="userdom" value="" />'."\n".
  847: 	'</form>'."\n";
  848:     return $jscript;
  849: }
  850: 
  851: 
  852: 
  853: # Given the score (as a number [0-1] and the weight) what is the final
  854: # point value? This function will round to the nearest tenth, third,
  855: # or quarter if one of those is within the tolerance of .00001.
  856: sub compute_points {
  857:     my ($score, $weight) = @_;
  858:     
  859:     my $tolerance = .00001;
  860:     my $points = $score * $weight;
  861: 
  862:     # Check for nearness to 1/x.
  863:     my $check_for_nearness = sub {
  864:         my ($factor) = @_;
  865:         my $num = ($points * $factor) + $tolerance;
  866:         my $floored_num = floor($num);
  867:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  868:             return $floored_num / $factor;
  869:         }
  870:         return $points;
  871:     };
  872: 
  873:     $points = $check_for_nearness->(10);
  874:     $points = $check_for_nearness->(3);
  875:     $points = $check_for_nearness->(4);
  876:     
  877:     return $points;
  878: }
  879: 
  880: #------------------ End of general use routines --------------------
  881: 
  882: #
  883: # Find most similar essay
  884: #
  885: 
  886: sub most_similar {
  887:     my ($uname,$udom,$symb,$uessay)=@_;
  888: 
  889:     unless ($symb) { return ''; }
  890: 
  891:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  892: 
  893: # ignore spaces and punctuation
  894: 
  895:     $uessay=~s/\W+/ /gs;
  896: 
  897: # ignore empty submissions (occuring when only files are sent)
  898: 
  899:     unless ($uessay=~/\w+/s) { return ''; }
  900: 
  901: # these will be returned. Do not care if not at least 50 percent similar
  902:     my $limit=0.6;
  903:     my $sname='';
  904:     my $sdom='';
  905:     my $scrsid='';
  906:     my $sessay='';
  907: # go through all essays ...
  908:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  909: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  910: # ... except the same student
  911:         next if (($tname eq $uname) && ($tdom eq $udom));
  912: 	my $tessay=$old_essays{$symb}{$tkey};
  913: 	$tessay=~s/\W+/ /gs;
  914: # String similarity gives up if not even limit
  915: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  916: # Found one
  917: 	if ($tsimilar>$limit) {
  918: 	    $limit=$tsimilar;
  919: 	    $sname=$tname;
  920: 	    $sdom=$tdom;
  921: 	    $scrsid=$tcrsid;
  922: 	    $sessay=$old_essays{$symb}{$tkey};
  923: 	}
  924:     }
  925:     if ($limit>0.6) {
  926:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  927:     } else {
  928:        return ('','','','',0);
  929:     }
  930: }
  931: 
  932: #-------------------------------------------------------------------
  933: 
  934: #------------------------------------ Receipt Verification Routines
  935: #
  936: 
  937: sub initialverifyreceipt {
  938:    my ($request,$symb) = @_;
  939:    &commonJSfunctions($request);
  940:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  941:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  942:         '-<input type="text" name="receipt" size="4" />'.
  943:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  944:         '<input type="hidden" name="command" value="verify" />'.
  945:         "</form>\n";
  946: }
  947: 
  948: #--- Check whether a receipt number is valid.---
  949: sub verifyreceipt {
  950:     my ($request,$symb) = @_;
  951: 
  952:     my $courseid = $env{'request.course.id'};
  953:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  954: 	$env{'form.receipt'};
  955:     $receipt     =~ s/[^\-\d]//g;
  956: 
  957:     my $title =
  958: 	'<h3><span class="LC_info">'.
  959: 	&mt('Verifying Receipt Number [_1]',$receipt).
  960: 	'</span></h3>'."\n";
  961: 
  962:     my ($string,$contents,$matches) = ('','',0);
  963:     my (undef,undef,$fullname) = &getclasslist('all','0');
  964:     
  965:     my $receiptparts=0;
  966:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  967: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  968:     my $parts=['0'];
  969:     if ($receiptparts) {
  970:         my $res_error; 
  971:         ($parts)=&response_type($symb,\$res_error);
  972:         if ($res_error) {
  973:             return &navmap_errormsg();
  974:         } 
  975:     }
  976:     
  977:     my $header = 
  978: 	&Apache::loncommon::start_data_table().
  979: 	&Apache::loncommon::start_data_table_header_row().
  980: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  981: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  982: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  983:     if ($receiptparts) {
  984: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  985:     }
  986:     $header.=
  987: 	&Apache::loncommon::end_data_table_header_row();
  988: 
  989:     foreach (sort 
  990: 	     {
  991: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  992: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  993: 		 }
  994: 		 return $a cmp $b;
  995: 	     } (keys(%$fullname))) {
  996: 	my ($uname,$udom)=split(/\:/);
  997: 	foreach my $part (@$parts) {
  998: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  999: 		$contents.=
 1000: 		    &Apache::loncommon::start_data_table_row().
 1001: 		    '<td>&nbsp;'."\n".
 1002: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1003: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1004: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1005: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1006: 		if ($receiptparts) {
 1007: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1008: 		}
 1009: 		$contents.= 
 1010: 		    &Apache::loncommon::end_data_table_row()."\n";
 1011: 		
 1012: 		$matches++;
 1013: 	    }
 1014: 	}
 1015:     }
 1016:     if ($matches == 0) {
 1017:         $string = $title
 1018:                  .'<p class="LC_warning">'
 1019:                  .&mt('No match found for the above receipt number.')
 1020:                  .'</p>';
 1021:     } else {
 1022: 	$string = &jscriptNform($symb).$title.
 1023: 	    '<p>'.
 1024: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1025: 	    '</p>'.
 1026: 	    $header.
 1027: 	    $contents.
 1028: 	    &Apache::loncommon::end_data_table()."\n";
 1029:     }
 1030:     return $string;
 1031: }
 1032: 
 1033: #--- This is called by a number of programs.
 1034: #--- Called from the Grading Menu - View/Grade an individual student
 1035: #--- Also called directly when one clicks on the subm button 
 1036: #    on the problem page.
 1037: sub listStudents {
 1038:     my ($request,$symb,$submitonly,$divforres) = @_;
 1039: 
 1040:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1041:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1042:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1043:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1044:     unless ($submitonly) {
 1045:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1046:     }
 1047: 
 1048:     my $result='';
 1049:     my $res_error;
 1050:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1051: 
 1052:     my $table;
 1053:     if (ref($partlist) eq 'ARRAY') {
 1054:         if (scalar(@$partlist) > 1 ) {
 1055:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1056:         } elsif ($divforres) {
 1057:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1058:         } else {
 1059:             $table = '<br clear="all" />';
 1060:         }
 1061:     }
 1062: 
 1063:     my %js_lt = &Apache::lonlocal::texthash (
 1064: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1065: 		'single'   => 'Please select the student before clicking on the Next button.',
 1066: 	     );
 1067:     &js_escape(\%js_lt);
 1068:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1069:     function checkSelect(checkBox) {
 1070: 	var ctr=0;
 1071: 	var sense="";
 1072: 	if (checkBox.length > 1) {
 1073: 	    for (var i=0; i<checkBox.length; i++) {
 1074: 		if (checkBox[i].checked) {
 1075: 		    ctr++;
 1076: 		}
 1077: 	    }
 1078: 	    sense = '$js_lt{'multiple'}';
 1079: 	} else {
 1080: 	    if (checkBox.checked) {
 1081: 		ctr = 1;
 1082: 	    }
 1083: 	    sense = '$js_lt{'single'}';
 1084: 	}
 1085: 	if (ctr == 0) {
 1086: 	    alert(sense);
 1087: 	    return false;
 1088: 	}
 1089: 	document.gradesub.submit();
 1090:     }
 1091: 
 1092:     function reLoadList(formname) {
 1093: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1094: 	formname.command.value = 'submission';
 1095: 	formname.submit();
 1096:     }
 1097: LISTJAVASCRIPT
 1098: 
 1099:     &commonJSfunctions($request);
 1100:     $request->print($result);
 1101: 
 1102:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1103: 	"\n".$table;
 1104: 
 1105:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1106:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1107:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1108:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1109:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1110:                   .&Apache::lonhtmlcommon::row_closure();
 1111:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1112:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1113:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1114:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1115:                   .&Apache::lonhtmlcommon::row_closure();
 1116: 
 1117:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1118:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1119:     $env{'form.Status'} = $saveStatus;
 1120:     my %optiontext = &Apache::lonlocal::texthash (
 1121:                           lastonly => 'last submission',
 1122:                           last     => 'last submission with details',
 1123:                           datesub  => 'all submissions',
 1124:                           all      => 'all submissions with details',
 1125:                       );
 1126:     my $submission_options =
 1127:         '<span class="LC_nobreak">'.
 1128:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1129:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1130:         '<span class="LC_nobreak">'.
 1131:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1132:         $optiontext{'last'}.' </label></span>'."\n".
 1133:         '<span class="LC_nobreak">'.
 1134:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1135:         $optiontext{'datesub'}.'</label></span>'."\n".
 1136:         '<span class="LC_nobreak">'.
 1137:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1138:         $optiontext{'all'}.'</label></span>';
 1139:     my ($compmsg,$nocompmsg);
 1140:     $nocompmsg = ' checked="checked"';
 1141:     if ($numessay) {
 1142:         $compmsg = $nocompmsg;
 1143:         $nocompmsg = '';
 1144:     }
 1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
 1146:                   .$submission_options;
 1147: # Check if any gradable
 1148:     my $showmore;
 1149:     if ($perm{'mgr'}) {
 1150:         my @sections;
 1151:         if ($env{'request.course.sec'} ne '') {
 1152:             @sections = ($env{'request.course.sec'});
 1153:         } elsif ($env{'form.section'} eq '') {
 1154:             @sections = ('all');
 1155:         } else {
 1156:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1157:         }
 1158:         if (grep(/^all$/,@sections)) {
 1159:             $showmore = 1;
 1160:         } else {
 1161:             foreach my $sec (@sections) {
 1162:                 if (&canmodify($sec)) {
 1163:                     $showmore = 1;
 1164:                     last;
 1165:                 }
 1166:             }
 1167:         }
 1168:     }
 1169: 
 1170:     if ($showmore) {
 1171:         $gradeTable .=
 1172:                    &Apache::lonhtmlcommon::row_closure()
 1173:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1174:                   .'<span class="LC_nobreak">'
 1175:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1176:                   .&mt('No').('&nbsp;'x2).'</label>'
 1177:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1178:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1179:                   .&Apache::lonhtmlcommon::row_closure();
 1180: 
 1181:         $gradeTable .= 
 1182:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1183:                   .'<select name="increment">'
 1184:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1185:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1186:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1187:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1188:                   .'</select>';
 1189:     }
 1190:     $gradeTable .= 
 1191:         &build_section_inputs().
 1192: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1194: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1195:     if (exists($env{'form.Status'})) {
 1196: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
 1197:     } else {
 1198:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1199:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1200:                       .&Apache::lonhtmlcommon::StatusOptions(
 1201:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1202:     }
 1203:     if ($numessay) {
 1204:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1205:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1206:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1207:     }
 1208:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1209:                   .&Apache::lonhtmlcommon::end_pick_box();
 1210: 
 1211:     $gradeTable .= '<p>'
 1212:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1213:                   .'<input type="hidden" name="command" value="processGroup" />'
 1214:                   .'</p>';
 1215: 
 1216: # checkall buttons
 1217:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1218:     $gradeTable.='<input type="button" '."\n".
 1219:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1220:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1221:     $gradeTable.=&check_buttons();
 1222:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1223:     $gradeTable.= &Apache::loncommon::start_data_table().
 1224: 	&Apache::loncommon::start_data_table_header_row();
 1225:     my $loop = 0;
 1226:     while ($loop < 2) {
 1227: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1228: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1229: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1230: 	    foreach my $part (sort(@$partlist)) {
 1231: 		my $display_part=
 1232: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1233: 		$gradeTable.=
 1234: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1235: 	    }
 1236: 	} elsif ($submitonly eq 'queued') {
 1237: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1238: 	}
 1239: 	$loop++;
 1240: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1241:     }
 1242:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1243: 
 1244:     my $ctr = 0;
 1245:     foreach my $student (sort 
 1246: 			 {
 1247: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1248: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1249: 			     }
 1250: 			     return $a cmp $b;
 1251: 			 }
 1252: 			 (keys(%$fullname))) {
 1253: 	my ($uname,$udom) = split(/:/,$student);
 1254: 
 1255: 	my %status = ();
 1256: 
 1257: 	if ($submitonly eq 'queued') {
 1258: 	    my %queue_status = 
 1259: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1260: 							$udom,$uname);
 1261: 	    next if (!defined($queue_status{'gradingqueue'}));
 1262: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1263: 	}
 1264: 
 1265: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1266: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1267: 	    my $submitted = 0;
 1268: 	    my $graded = 0;
 1269: 	    my $incorrect = 0;
 1270: 	    foreach (keys(%status)) {
 1271: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1272: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1273: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1274: 		
 1275: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1276: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1277: 		    $submitted = 0;
 1278: 		    my ($part)=split(/\./,$partid);
 1279: 		    $gradeTable.='<input type="hidden" name="'.
 1280: 			$student.':'.$part.':submitted_by" value="'.
 1281: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1282: 		}
 1283: 	    }
 1284: 	    
 1285: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1286: 				     $submitonly eq 'incorrect' ||
 1287: 				     $submitonly eq 'graded'));
 1288: 	    next if (!$graded && ($submitonly eq 'graded'));
 1289: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1290: 	}
 1291: 
 1292: 	$ctr++;
 1293: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1294:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1295: 	if ( $perm{'vgr'} eq 'F' ) {
 1296: 	    if ($ctr%2 ==1) {
 1297: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1298: 	    }
 1299: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1300:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1301:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1302: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1303: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1304: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1305: 
 1306: 	    if ($submitonly ne 'all') {
 1307: 		foreach (sort(keys(%status))) {
 1308: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1309: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1310: 		}
 1311: 	    }
 1312: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1313: 	    if ($ctr%2 ==0) {
 1314: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1315: 	    }
 1316: 	}
 1317:     }
 1318:     if ($ctr%2 ==1) {
 1319: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1320: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1321: 		foreach (@$partlist) {
 1322: 		    $gradeTable.='<td>&nbsp;</td>';
 1323: 		}
 1324: 	    } elsif ($submitonly eq 'queued') {
 1325: 		$gradeTable.='<td>&nbsp;</td>';
 1326: 	    }
 1327: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1328:     }
 1329: 
 1330:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1331:         '<input type="button" '.
 1332:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1333:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1334:     if ($ctr == 0) {
 1335: 	my $num_students=(scalar(keys(%$fullname)));
 1336: 	if ($num_students eq 0) {
 1337: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1338: 	} else {
 1339: 	    my $submissions='submissions';
 1340: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1341: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1342: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1343: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1344: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1345: 		    $num_students).
 1346: 		'</span><br />';
 1347: 	}
 1348:     } elsif ($ctr == 1) {
 1349: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1350:     }
 1351:     $request->print($gradeTable);
 1352:     return '';
 1353: }
 1354: 
 1355: #---- Called from the listStudents routine
 1356: 
 1357: sub check_script {
 1358:     my ($form,$type) = @_;
 1359:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1360:     function checkall() {
 1361:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1362:             ele = document.forms.'.$form.'.elements[i];
 1363:             if (ele.name == "'.$type.'") {
 1364:             document.forms.'.$form.'.elements[i].checked=true;
 1365:                                        }
 1366:         }
 1367:     }
 1368: 
 1369:     function checksec() {
 1370:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1371:             ele = document.forms.'.$form.'.elements[i];
 1372:            string = document.forms.'.$form.'.chksec.value;
 1373:            if
 1374:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1375:               document.forms.'.$form.'.elements[i].checked=true;
 1376:             }
 1377:         }
 1378:     }
 1379: 
 1380: 
 1381:     function uncheckall() {
 1382:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1383:             ele = document.forms.'.$form.'.elements[i];
 1384:             if (ele.name == "'.$type.'") {
 1385:             document.forms.'.$form.'.elements[i].checked=false;
 1386:                                        }
 1387:         }
 1388:     }
 1389: 
 1390: '."\n");
 1391:     return $chkallscript;
 1392: }
 1393: 
 1394: sub check_buttons {
 1395:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1396:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1397:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1398:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1399:     return $buttons;
 1400: }
 1401: 
 1402: #     Displays the submissions for one student or a group of students
 1403: sub processGroup {
 1404:     my ($request,$symb) = @_;
 1405:     my $ctr        = 0;
 1406:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1407:     my $total      = scalar(@stuchecked)-1;
 1408: 
 1409:     foreach my $student (@stuchecked) {
 1410: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1411: 	$env{'form.student'}        = $uname;
 1412: 	$env{'form.userdom'}        = $udom;
 1413: 	$env{'form.fullname'}       = $fullname;
 1414: 	&submission($request,$ctr,$total,$symb);
 1415: 	$ctr++;
 1416:     }
 1417:     return '';
 1418: }
 1419: 
 1420: #------------------------------------------------------------------------------------
 1421: #
 1422: #-------------------------- Next few routines handles grading by student, essentially
 1423: #                           handles essay response type problem/part
 1424: #
 1425: #--- Javascript to handle the submission page functionality ---
 1426: sub sub_page_js {
 1427:     my $request = shift;
 1428:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1429:     &js_escape(\$alertmsg);
 1430:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1431:     function updateRadio(formname,id,weight) {
 1432: 	var gradeBox = formname["GD_BOX"+id];
 1433: 	var radioButton = formname["RADVAL"+id];
 1434: 	var oldpts = formname["oldpts"+id].value;
 1435: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1436: 	gradeBox.value = pts;
 1437: 	var resetbox = false;
 1438: 	if (isNaN(pts) || pts < 0) {
 1439: 	    alert("$alertmsg"+pts);
 1440: 	    for (var i=0; i<radioButton.length; i++) {
 1441: 		if (radioButton[i].checked) {
 1442: 		    gradeBox.value = i;
 1443: 		    resetbox = true;
 1444: 		}
 1445: 	    }
 1446: 	    if (!resetbox) {
 1447: 		formtextbox.value = "";
 1448: 	    }
 1449: 	    return;
 1450: 	}
 1451: 
 1452: 	if (pts > weight) {
 1453: 	    var resp = confirm("You entered a value ("+pts+
 1454: 			       ") greater than the weight for the part. Accept?");
 1455: 	    if (resp == false) {
 1456: 		gradeBox.value = oldpts;
 1457: 		return;
 1458: 	    }
 1459: 	}
 1460: 
 1461: 	for (var i=0; i<radioButton.length; i++) {
 1462: 	    radioButton[i].checked=false;
 1463: 	    if (pts == i && pts != "") {
 1464: 		radioButton[i].checked=true;
 1465: 	    }
 1466: 	}
 1467: 	updateSelect(formname,id);
 1468: 	formname["stores"+id].value = "0";
 1469:     }
 1470: 
 1471:     function writeBox(formname,id,pts) {
 1472: 	var gradeBox = formname["GD_BOX"+id];
 1473: 	if (checkSolved(formname,id) == 'update') {
 1474: 	    gradeBox.value = pts;
 1475: 	} else {
 1476: 	    var oldpts = formname["oldpts"+id].value;
 1477: 	    gradeBox.value = oldpts;
 1478: 	    var radioButton = formname["RADVAL"+id];
 1479: 	    for (var i=0; i<radioButton.length; i++) {
 1480: 		radioButton[i].checked=false;
 1481: 		if (i == oldpts) {
 1482: 		    radioButton[i].checked=true;
 1483: 		}
 1484: 	    }
 1485: 	}
 1486: 	formname["stores"+id].value = "0";
 1487: 	updateSelect(formname,id);
 1488: 	return;
 1489:     }
 1490: 
 1491:     function clearRadBox(formname,id) {
 1492: 	if (checkSolved(formname,id) == 'noupdate') {
 1493: 	    updateSelect(formname,id);
 1494: 	    return;
 1495: 	}
 1496: 	gradeSelect = formname["GD_SEL"+id];
 1497: 	for (var i=0; i<gradeSelect.length; i++) {
 1498: 	    if (gradeSelect[i].selected) {
 1499: 		var selectx=i;
 1500: 	    }
 1501: 	}
 1502: 	var stores = formname["stores"+id];
 1503: 	if (selectx == stores.value) { return };
 1504: 	var gradeBox = formname["GD_BOX"+id];
 1505: 	gradeBox.value = "";
 1506: 	var radioButton = formname["RADVAL"+id];
 1507: 	for (var i=0; i<radioButton.length; i++) {
 1508: 	    radioButton[i].checked=false;
 1509: 	}
 1510: 	stores.value = selectx;
 1511:     }
 1512: 
 1513:     function checkSolved(formname,id) {
 1514: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1515: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1516: 	    if (!reply) {return "noupdate";}
 1517: 	    formname.overRideScore.value = 'yes';
 1518: 	}
 1519: 	return "update";
 1520:     }
 1521: 
 1522:     function updateSelect(formname,id) {
 1523: 	formname["GD_SEL"+id][0].selected = true;
 1524: 	return;
 1525:     }
 1526: 
 1527: //=========== Check that a point is assigned for all the parts  ============
 1528:     function checksubmit(formname,val,total,parttot) {
 1529: 	formname.gradeOpt.value = val;
 1530: 	if (val == "Save & Next") {
 1531: 	    for (i=0;i<=total;i++) {
 1532: 		for (j=0;j<parttot;j++) {
 1533: 		    var partid = formname["partid"+i+"_"+j].value;
 1534: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1535: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1536: 			if (points == "") {
 1537: 			    var name = formname["name"+i].value;
 1538: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1539: 			    var resp = confirm("You did not assign a score for "+studentID+
 1540: 					       ", part "+partid+". Continue?");
 1541: 			    if (resp == false) {
 1542: 				formname["GD_BOX"+i+"_"+partid].focus();
 1543: 				return false;
 1544: 			    }
 1545: 			}
 1546: 		    }
 1547: 		}
 1548: 	    }
 1549: 	}
 1550: 	formname.submit();
 1551:     }
 1552: 
 1553: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1554:     function checkSubmitPage(formname,total) {
 1555: 	noscore = new Array(100);
 1556: 	var ptr = 0;
 1557: 	for (i=1;i<total;i++) {
 1558: 	    var partid = formname["q_"+i].value;
 1559: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1560: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1561: 		var status = formname["solved"+i+"_"+partid].value;
 1562: 		if (points == "" && status != "correct_by_student") {
 1563: 		    noscore[ptr] = i;
 1564: 		    ptr++;
 1565: 		}
 1566: 	    }
 1567: 	}
 1568: 	if (ptr != 0) {
 1569: 	    var sense = ptr == 1 ? ": " : "s: ";
 1570: 	    var prolist = "";
 1571: 	    if (ptr == 1) {
 1572: 		prolist = noscore[0];
 1573: 	    } else {
 1574: 		var i = 0;
 1575: 		while (i < ptr-1) {
 1576: 		    prolist += noscore[i]+", ";
 1577: 		    i++;
 1578: 		}
 1579: 		prolist += "and "+noscore[i];
 1580: 	    }
 1581: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1582: 	    if (resp == false) {
 1583: 		return false;
 1584: 	    }
 1585: 	}
 1586: 
 1587: 	formname.submit();
 1588:     }
 1589: SUBJAVASCRIPT
 1590: }
 1591: 
 1592: #--- javascript for grading message center
 1593: sub sub_grademessage_js {
 1594:     my $request = shift;
 1595:     my $iconpath = $request->dir_config('lonIconsURL');
 1596:     &commonJSfunctions($request);
 1597: 
 1598:     my $inner_js_msg_central= (<<INNERJS);
 1599: <script type="text/javascript">
 1600:     function checkInput() {
 1601:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1602:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1603:       var usrctr = document.msgcenter.usrctr.value;
 1604:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1605:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1606: 
 1607:       var msgchk = "";
 1608:       if (document.msgcenter.subchk.checked) {
 1609:          msgchk = "msgsub,";
 1610:       }
 1611:       var includemsg = 0;
 1612:       for (var i=1; i<=nmsg; i++) {
 1613:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1614:           var frmmsg = document.msgcenter["msg"+i];
 1615:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1616:           var showflg = opener.document.SCORE["shownOnce"+i];
 1617:           showflg.value = "1";
 1618:           var chkbox = document.msgcenter["msgn"+i];
 1619:           if (chkbox.checked) {
 1620:              msgchk += "savemsg"+i+",";
 1621:              includemsg = 1;
 1622:           }
 1623:       }
 1624:       if (document.msgcenter.newmsgchk.checked) {
 1625:          msgchk += "newmsg"+usrctr;
 1626:          includemsg = 1;
 1627:       }
 1628:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1629:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1630:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1631:       includemsg.value = msgchk;
 1632: 
 1633:       self.close()
 1634: 
 1635:     }
 1636: </script>
 1637: INNERJS
 1638: 
 1639:     my $start_page_msg_central =
 1640:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1641: 				       {'js_ready'  => 1,
 1642: 					'only_body' => 1,
 1643: 					'bgcolor'   =>'#FFFFFF',});
 1644:     my $end_page_msg_central =
 1645: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1646: 
 1647: 
 1648:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1649:     $docopen=~s/^document\.//;
 1650: 
 1651:     my %html_js_lt = &Apache::lonlocal::texthash(
 1652:                 comp => 'Compose Message for: ',
 1653:                 incl => 'Include',
 1654:                 type => 'Type',
 1655:                 subj => 'Subject',
 1656:                 mesa => 'Message',
 1657:                 new  => 'New',
 1658:                 save => 'Save',
 1659:                 canc => 'Cancel',
 1660:              );
 1661:     &html_escape(\%html_js_lt);
 1662:     &js_escape(\%html_js_lt);
 1663:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1664: 
 1665: //===================== Script to view submitted by ==================
 1666:   function viewSubmitter(submitter) {
 1667:     document.SCORE.refresh.value = "on";
 1668:     document.SCORE.NCT.value = "1";
 1669:     document.SCORE.unamedom0.value = submitter;
 1670:     document.SCORE.submit();
 1671:     return;
 1672:   }
 1673: 
 1674: //====================== Script for composing message ==============
 1675:    // preload images
 1676:    img1 = new Image();
 1677:    img1.src = "$iconpath/mailbkgrd.gif";
 1678:    img2 = new Image();
 1679:    img2.src = "$iconpath/mailto.gif";
 1680: 
 1681:   function msgCenter(msgform,usrctr,fullname) {
 1682:     var Nmsg  = msgform.savemsgN.value;
 1683:     savedMsgHeader(Nmsg,usrctr,fullname);
 1684:     var subject = msgform.msgsub.value;
 1685:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1686:     re = /msgsub/;
 1687:     var shwsel = "";
 1688:     if (re.test(msgchk)) { shwsel = "checked" }
 1689:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1690:     displaySubject(checkEntities(subject),shwsel);
 1691:     for (var i=1; i<=Nmsg; i++) {
 1692: 	var testmsg = "savemsg"+i+",";
 1693: 	re = new RegExp(testmsg,"g");
 1694: 	shwsel = "";
 1695: 	if (re.test(msgchk)) { shwsel = "checked" }
 1696: 	var message = document.SCORE["savemsg"+i].value;
 1697: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1698: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1699: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1700:     }
 1701:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1702:     shwsel = "";
 1703:     re = /newmsg/;
 1704:     if (re.test(msgchk)) { shwsel = "checked" }
 1705:     newMsg(newmsg,shwsel);
 1706:     msgTail(); 
 1707:     return;
 1708:   }
 1709: 
 1710:   function checkEntities(strx) {
 1711:     if (strx.length == 0) return strx;
 1712:     var orgStr = ["&", "<", ">", '"']; 
 1713:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1714:     var counter = 0;
 1715:     while (counter < 4) {
 1716: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1717: 	counter++;
 1718:     }
 1719:     return strx;
 1720:   }
 1721: 
 1722:   function strReplace(strx, orgStr, newStr) {
 1723:     return strx.split(orgStr).join(newStr);
 1724:   }
 1725: 
 1726:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1727:     var height = 70*Nmsg+250;
 1728:     if (height > 600) {
 1729: 	height = 600;
 1730:     }
 1731:     var xpos = (screen.width-600)/2;
 1732:     xpos = (xpos < 0) ? '0' : xpos;
 1733:     var ypos = (screen.height-height)/2-30;
 1734:     ypos = (ypos < 0) ? '0' : ypos;
 1735: 
 1736:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1737:     pWin.focus();
 1738:     pDoc = pWin.document;
 1739:     pDoc.$docopen;
 1740:     pDoc.write('$start_page_msg_central');
 1741: 
 1742:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1743:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1744:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1745: 
 1746:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1747:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1748: }
 1749:     function displaySubject(msg,shwsel) {
 1750:     pDoc = pWin.document;
 1751:     pDoc.write("<tr>");
 1752:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1753:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1754:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1755: }
 1756: 
 1757:   function displaySavedMsg(ctr,msg,shwsel) {
 1758:     pDoc = pWin.document;
 1759:     pDoc.write("<tr>");
 1760:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1761:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1762:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1763: }
 1764: 
 1765:   function newMsg(newmsg,shwsel) {
 1766:     pDoc = pWin.document;
 1767:     pDoc.write("<tr>");
 1768:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1769:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1770:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1771: }
 1772: 
 1773:   function msgTail() {
 1774:     pDoc = pWin.document;
 1775:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1776:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1777:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1778:     pDoc.write("<\\/form>");
 1779:     pDoc.write('$end_page_msg_central');
 1780:     pDoc.close();
 1781: }
 1782: 
 1783: SUBJAVASCRIPT
 1784: }
 1785: 
 1786: #--- javascript for essay type problem --
 1787: sub sub_page_kw_js {
 1788:     my $request = shift;
 1789: 
 1790:     unless ($env{'form.compmsg'}) {
 1791:         &commonJSfunctions($request);
 1792:     }
 1793: 
 1794:     my $inner_js_highlight_central= (<<INNERJS);
 1795: <script type="text/javascript">
 1796:     function updateChoice(flag) {
 1797:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1798:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1799:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1800:       opener.document.SCORE.refresh.value = "on";
 1801:       if (opener.document.SCORE.keywords.value!=""){
 1802:          opener.document.SCORE.submit();
 1803:       }
 1804:       self.close()
 1805:     }
 1806: </script>
 1807: INNERJS
 1808: 
 1809:     my $start_page_highlight_central =
 1810:         &Apache::loncommon::start_page('Highlight Central',
 1811:                                        $inner_js_highlight_central,
 1812:                                        {'js_ready'  => 1,
 1813:                                         'only_body' => 1,
 1814:                                         'bgcolor'   =>'#FFFFFF',});
 1815:     my $end_page_highlight_central =
 1816:         &Apache::loncommon::end_page({'js_ready' => 1});
 1817: 
 1818:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1819:     $docopen=~s/^document\.//;
 1820: 
 1821:     my %js_lt = &Apache::lonlocal::texthash(
 1822:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1823:                 plse => 'Please select a word or group of words from document and then click this link.',
 1824:                 adds => 'Add selection to keyword list? Edit if desired.',
 1825:                 col1 => 'red',
 1826:                 col2 => 'green',
 1827:                 col3 => 'blue',
 1828:                 siz1 => 'normal',
 1829:                 siz2 => '+1',
 1830:                 siz3 => '+2',
 1831:                 sty1 => 'normal',
 1832:                 sty2 => 'italic',
 1833:                 sty3 => 'bold',
 1834:              );
 1835:     my %html_js_lt = &Apache::lonlocal::texthash(
 1836:                 save => 'Save',
 1837:                 canc => 'Cancel',
 1838:                 kehi => 'Keyword Highlight Options',
 1839:                 txtc => 'Text Color',
 1840:                 font => 'Font Size',
 1841:                 fnst => 'Font Style',
 1842:              );
 1843:     &js_escape(\%js_lt);
 1844:     &html_escape(\%html_js_lt);
 1845:     &js_escape(\%html_js_lt);
 1846:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1847: 
 1848: //===================== Show list of keywords ====================
 1849:   function keywords(formname) {
 1850:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1851:     if (nret==null) return;
 1852:     formname.keywords.value = nret;
 1853: 
 1854:     if (formname.keywords.value != "") {
 1855:         formname.refresh.value = "on";
 1856:         formname.submit();
 1857:     }
 1858:     return;
 1859:   }
 1860: 
 1861: //===================== Script to add keyword(s) ==================
 1862:   function getSel() {
 1863:     if (document.getSelection) txt = document.getSelection();
 1864:     else if (document.selection) txt = document.selection.createRange().text;
 1865:     else return;
 1866:     if (typeof(txt) != 'string') {
 1867:         txt = String(txt);
 1868:     }
 1869:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1870:     if (cleantxt=="") {
 1871:         alert("$js_lt{'plse'}");
 1872:         return;
 1873:     }
 1874:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1875:     if (nret==null) return;
 1876:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1877:     if (document.SCORE.keywords.value != "") {
 1878:         document.SCORE.refresh.value = "on";
 1879:         document.SCORE.submit();
 1880:     }
 1881:     return;
 1882:   }
 1883: 
 1884: //====================== Script for keyword highlight options ==============
 1885:   function kwhighlight() {
 1886:     var kwclr    = document.SCORE.kwclr.value;
 1887:     var kwsize   = document.SCORE.kwsize.value;
 1888:     var kwstyle  = document.SCORE.kwstyle.value;
 1889:     var redsel = "";
 1890:     var grnsel = "";
 1891:     var blusel = "";
 1892:     var txtcol1 = "$js_lt{'col1'}";
 1893:     var txtcol2 = "$js_lt{'col2'}";
 1894:     var txtcol3 = "$js_lt{'col3'}";
 1895:     var txtsiz1 = "$js_lt{'siz1'}";
 1896:     var txtsiz2 = "$js_lt{'siz2'}";
 1897:     var txtsiz3 = "$js_lt{'siz3'}";
 1898:     var txtsty1 = "$js_lt{'sty1'}";
 1899:     var txtsty2 = "$js_lt{'sty2'}";
 1900:     var txtsty3 = "$js_lt{'sty3'}";
 1901:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1902:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1903:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1904:     var sznsel = "";
 1905:     var sz1sel = "";
 1906:     var sz2sel = "";
 1907:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1908:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1909:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1910:     var synsel = "";
 1911:     var syisel = "";
 1912:     var sybsel = "";
 1913:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1914:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1915:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1916:     highlightCentral();
 1917:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1918:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1919:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1920:     highlightend();
 1921:     return;
 1922:   }
 1923: 
 1924:   function highlightCentral() {
 1925: //    if (window.hwdWin) window.hwdWin.close();
 1926:     var xpos = (screen.width-400)/2;
 1927:     xpos = (xpos < 0) ? '0' : xpos;
 1928:     var ypos = (screen.height-330)/2-30;
 1929:     ypos = (ypos < 0) ? '0' : ypos;
 1930: 
 1931:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1932:     hwdWin.focus();
 1933:     var hDoc = hwdWin.document;
 1934:     hDoc.$docopen;
 1935:     hDoc.write('$start_page_highlight_central');
 1936:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1937:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1938: 
 1939:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1940:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1941:   }
 1942: 
 1943:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1944:     var hDoc = hwdWin.document;
 1945:     hDoc.write("<tr>");
 1946:     hDoc.write("<td align=\\"left\\">");
 1947:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1948:     hDoc.write("<td align=\\"left\\">");
 1949:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1950:     hDoc.write("<td align=\\"left\\">");
 1951:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1952:     hDoc.write("<\\/tr>");
 1953:   }
 1954: 
 1955:   function highlightend() { 
 1956:     var hDoc = hwdWin.document;
 1957:     hDoc.write("<\\/table><br \\/>");
 1958:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1959:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1960:     hDoc.write("<\\/form>");
 1961:     hDoc.write('$end_page_highlight_central');
 1962:     hDoc.close();
 1963:   }
 1964: 
 1965: SUBJAVASCRIPT
 1966: }
 1967: 
 1968: sub get_increment {
 1969:     my $increment = $env{'form.increment'};
 1970:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1971:         $increment != .1) {
 1972:         $increment = 1;
 1973:     }
 1974:     return $increment;
 1975: }
 1976: 
 1977: sub gradeBox_start {
 1978:     return (
 1979:         &Apache::loncommon::start_data_table()
 1980:        .&Apache::loncommon::start_data_table_header_row()
 1981:        .'<th>'.&mt('Part').'</th>'
 1982:        .'<th>'.&mt('Points').'</th>'
 1983:        .'<th>&nbsp;</th>'
 1984:        .'<th>'.&mt('Assign Grade').'</th>'
 1985:        .'<th>'.&mt('Weight').'</th>'
 1986:        .'<th>'.&mt('Grade Status').'</th>'
 1987:        .&Apache::loncommon::end_data_table_header_row()
 1988:     );
 1989: }
 1990: 
 1991: sub gradeBox_end {
 1992:     return (
 1993:         &Apache::loncommon::end_data_table()
 1994:     );
 1995: }
 1996: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1997: sub gradeBox {
 1998:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1999:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2000: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2001:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2002:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2003:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2004:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2005:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2006: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2007:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2008:     my $display_part= &get_display_part($partid,$symb);
 2009:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2010: 				       [$partid]);
 2011:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2012:     if ($last_resets{$partid}) {
 2013:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2014:     }
 2015:     my $result=&Apache::loncommon::start_data_table_row();
 2016:     my $ctr = 0;
 2017:     my $thisweight = 0;
 2018:     my $increment = &get_increment();
 2019: 
 2020:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2021:     while ($thisweight<=$wgt) {
 2022: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2023:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2024: 	    $thisweight.')" value="'.$thisweight.'" '.
 2025: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2026: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2027:         $thisweight += $increment;
 2028: 	$ctr++;
 2029:     }
 2030:     $radio.='</tr></table>';
 2031: 
 2032:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2033: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2034: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2035: 	$wgt.')" /></td>'."\n";
 2036:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2037: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2038: 	' </td>'."\n";
 2039:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2040: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2041:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2042: 	$line.='<option></option>'.
 2043: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2044:     } else {
 2045: 	$line.='<option selected="selected"></option>'.
 2046: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2047:     }
 2048:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2049: 
 2050: 
 2051:     $result .= 
 2052: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2053:     $result.=&Apache::loncommon::end_data_table_row();
 2054:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2055:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2056: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2057: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2058: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2059:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2060:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2061:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2062:         $aggtries.'" />'."\n";
 2063:     my $res_error;
 2064:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2065:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2066:     if ($res_error) {
 2067:         return &navmap_errormsg();
 2068:     }
 2069:     return $result;
 2070: }
 2071: 
 2072: sub handback_box {
 2073:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2074:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2075:     return unless ($numessay);
 2076:     my (@respids);
 2077:     my @part_response_id = &flatten_responseType($responseType);
 2078:     foreach my $part_response_id (@part_response_id) {
 2079:     	my ($part,$resp) = @{ $part_response_id };
 2080:         if ($part eq $partid) {
 2081:             push(@respids,$resp);
 2082:         }
 2083:     }
 2084:     my $result;
 2085:     foreach my $respid (@respids) {
 2086: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2087: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2088: 	next if (!@$files);
 2089: 	my $file_counter = 0;
 2090: 	foreach my $file (@$files) {
 2091: 	    if ($file =~ /\/portfolio\//) {
 2092:                 $file_counter++;
 2093:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2094:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 2095:     	        $file_disp = "$name.$ext";
 2096:     	        $file = $file_path.$file_disp;
 2097:     	        $result.=&mt('Return commented version of [_1] to student.',
 2098:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2099:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2100:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2101: 	    }
 2102: 	}
 2103:         if ($file_counter) {
 2104:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2105:                        '<span class="LC_info">'.
 2106:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2107:         }
 2108:     }
 2109:     return $result;    
 2110: }
 2111: 
 2112: sub show_problem {
 2113:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2114:     my $rendered;
 2115:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2116:     &Apache::lonxml::remember_problem_counter();
 2117:     if ($mode eq 'both' or $mode eq 'text') {
 2118: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2119: 						       $env{'request.course.id'},
 2120: 						       undef,\%form);
 2121:     }
 2122:     if ($removeform) {
 2123: 	$rendered=~s|<form(.*?)>||g;
 2124: 	$rendered=~s|</form>||g;
 2125: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2126:     }
 2127:     my $companswer;
 2128:     if ($mode eq 'both' or $mode eq 'answer') {
 2129: 	&Apache::lonxml::restore_problem_counter();
 2130: 	$companswer=
 2131: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2132: 						    $env{'request.course.id'},
 2133: 						    %form);
 2134:     }
 2135:     if ($removeform) {
 2136: 	$companswer=~s|<form(.*?)>||g;
 2137: 	$companswer=~s|</form>||g;
 2138: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2139:     }
 2140:     my $renderheading = &mt('View of the problem');
 2141:     my $answerheading = &mt('Correct answer');
 2142:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2143:         my $stu_fullname = $env{'form.fullname'};
 2144:         if ($stu_fullname eq '') {
 2145:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2146:         }
 2147:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2148:         if ($forwhom ne '') {
 2149:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2150:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2151:         }
 2152:     }
 2153:     $rendered=
 2154:         '<div class="LC_Box">'
 2155:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2156:        .$rendered
 2157:        .'</div>';
 2158:     $companswer=
 2159:         '<div class="LC_Box">'
 2160:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2161:        .$companswer
 2162:        .'</div>';
 2163:     my $result;
 2164:     if ($mode eq 'both') {
 2165:         $result=$rendered.$companswer;
 2166:     } elsif ($mode eq 'text') {
 2167:         $result=$rendered;
 2168:     } elsif ($mode eq 'answer') {
 2169:         $result=$companswer;
 2170:     }
 2171:     return $result;
 2172: }
 2173: 
 2174: sub files_exist {
 2175:     my ($r, $symb) = @_;
 2176:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2177:     foreach my $student (@students) {
 2178:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2179:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2180: 					      $udom,$uname);
 2181:         my ($string,$timestamp)= &get_last_submission(\%record);
 2182:         foreach my $submission (@$string) {
 2183:             my ($partid,$respid) =
 2184: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2185:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2186: 					   \%record);
 2187:             return 1 if (@$files);
 2188:         }
 2189:     }
 2190:     return 0;
 2191: }
 2192: 
 2193: sub download_all_link {
 2194:     my ($r,$symb) = @_;
 2195:     unless (&files_exist($r, $symb)) {
 2196:         $r->print(&mt('There are currently no submitted documents.'));
 2197:         return;
 2198:     }
 2199:     my $all_students = 
 2200: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2201: 
 2202:     my $parts =
 2203: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2204: 
 2205:     my $identifier = &Apache::loncommon::get_cgi_id();
 2206:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2207:                              'cgi.'.$identifier.'.symb' => $symb,
 2208:                              'cgi.'.$identifier.'.parts' => $parts,});
 2209:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2210: 	      &mt('Download All Submitted Documents').'</a>');
 2211:     return;
 2212: }
 2213: 
 2214: sub submit_download_link {
 2215:     my ($request,$symb) = @_;
 2216:     if (!$symb) { return ''; }
 2217:     my $res_error;
 2218:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2219:         &response_type($symb,\$res_error);
 2220:     if ($res_error) {
 2221:         $request->print(&mt('An error occurred retrieving response types'));
 2222:         return;
 2223:     }
 2224:     unless ($numessay) {
 2225:         $request->print(&mt('No essayresponse items found'));
 2226:         return;
 2227:     }
 2228:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2229:     if (@chosenparts) {
 2230:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2231:                                           undef,undef,1));
 2232:     }
 2233:     if ($numessay) {
 2234:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2235:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2236:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2237:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2238:         if (ref($fullname) eq 'HASH') {
 2239:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2240:             if (@students) {
 2241:                 @{$env{'form.stuinfo'}} = @students;
 2242:                 if ($numdropbox) {
 2243:                     &download_all_link($request,$symb);
 2244:                 } else {
 2245:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2246:                 }
 2247: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2248: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2249:             } else {
 2250:                 $request->print(&mt('No students match the criteria you selected'));
 2251:             }
 2252:         } else {
 2253:             $request->print(&mt('Could not retrieve student information'));
 2254:         }
 2255:     } else {
 2256:         $request->print(&mt('No essayresponse items found'));
 2257:     }
 2258:     return;
 2259: }
 2260: 
 2261: sub build_section_inputs {
 2262:     my $section_inputs;
 2263:     if ($env{'form.section'} eq '') {
 2264:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2265:     } else {
 2266:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2267:         foreach my $section (@sections) {
 2268:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2269:         }
 2270:     }
 2271:     return $section_inputs;
 2272: }
 2273: 
 2274: # --------------------------- show submissions of a student, option to grade 
 2275: sub submission {
 2276:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2277:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2278:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2279:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2280:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2281: 
 2282:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2283:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2284:     my ($essayurl,%coursedesc_by_cid);
 2285: 
 2286:     if (!&canview($usec)) {
 2287:         $request->print(
 2288:             '<span class="LC_warning">'.
 2289:             &mt('Unable to view requested student.').
 2290:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2291:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2292:             '</span>');
 2293: 	return;
 2294:     }
 2295: 
 2296:     my $res_error;
 2297:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2298:         &response_type($symb,\$res_error);
 2299:     if ($res_error) {
 2300:         $request->print(&navmap_errormsg());
 2301:         return;
 2302:     }
 2303: 
 2304:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2305:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2306:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2307:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2308:         $env{'form.compmsg'} = 1;
 2309:     }
 2310:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2311:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2312: 	'" src="'.$request->dir_config('lonIconsURL').
 2313: 	'/check.gif" height="16" border="0" />';
 2314: 
 2315:     # header info
 2316:     if ($counter == 0) {
 2317:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2318:         if (@chosenparts) {
 2319:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2320:         } elsif ($divforres) {
 2321:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2322:         } else {
 2323:             $request->print('<br clear="all" />');
 2324:         }
 2325: 	&sub_page_js($request);
 2326:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2327: 	&sub_page_kw_js($request) if ($numessay);
 2328: 
 2329: 	# option to display problem, only once else it cause problems 
 2330:         # with the form later since the problem has a form.
 2331: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2332: 	    my $mode;
 2333: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2334: 		$mode='both';
 2335: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2336: 		$mode='text';
 2337: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2338: 		$mode='answer';
 2339: 	    }
 2340: 	    &Apache::lonxml::clear_problem_counter();
 2341: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2342: 	}
 2343: 
 2344: 	my %keyhash = ();
 2345: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2346: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2347: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2348: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2349: 	}
 2350: 	# kwclr is the only variable that is guaranteed not to be blank
 2351: 	# if this subroutine has been called once.
 2352: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2353: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2354: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2355: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2356: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2357: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2358: 	}
 2359: 	if ($env{'form.compmsg'}) {
 2360: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2361: 		$keyhash{$symb.'_subject'} : $probtitle;
 2362: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2363: 	}
 2364: 
 2365: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2366: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2367: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2368: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2369: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2370: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2371: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2372: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2373: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2374: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2375: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2376: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2377: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2378: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2379: 			&build_section_inputs().
 2380: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2381: 			'<input type="hidden" name="NCT"'.
 2382: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2383: 	if ($env{'form.compmsg'}) {
 2384: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2385: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2386: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2387: 	}
 2388: 	if ($numessay) {
 2389: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2390: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2391: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2392: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2393: 	}
 2394: 
 2395: 	my ($cts,$prnmsg) = (1,'');
 2396: 	while ($cts <= $env{'form.savemsgN'}) {
 2397: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2398: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2399: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2400: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2401: 		'" />'."\n".
 2402: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2403: 	    $cts++;
 2404: 	}
 2405: 	$request->print($prnmsg);
 2406: 
 2407: 	if ($numessay) {
 2408: 
 2409:             my %lt = &Apache::lonlocal::texthash(
 2410:                           keyh => 'Keyword Highlighting for Essays',
 2411:                           keyw => 'Keyword Options',
 2412:                           list => 'List',
 2413:                           past => 'Paste Selection to List',
 2414:                           high => 'Highlight Attribute',
 2415:                      );
 2416: #
 2417: # Print out the keyword options line
 2418: #
 2419: 	    $request->print(
 2420:                 '<div class="LC_columnSection">'
 2421:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2422:                .&Apache::lonhtmlcommon::funclist_from_array(
 2423:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2424:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2425:  class="page">'.$lt{'past'}.'</a>',
 2426:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2427:                     {legend => $lt{'keyw'}})
 2428:                .'</fieldset></div>'
 2429:             );
 2430: 
 2431: #
 2432: # Load the other essays for similarity check
 2433: #
 2434:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2435:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2436:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2437:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2438:                 if ($cdom ne '' && $cnum ne '') {
 2439:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2440:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2441:                         my $apath = $1.'_'.$id;
 2442:                         $apath=~s/\W/\_/gs;
 2443:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2444:                     }
 2445:                 }
 2446:             } else {
 2447: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2448: 	        $apath=&escape($apath);
 2449: 	        $apath=~s/\W/\_/gs;
 2450:                 &init_old_essays($symb,$apath,$adom,$aname);
 2451:             }
 2452:         }
 2453:     }
 2454: 
 2455: # This is where output for one specific student would start
 2456:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2457:     $request->print(
 2458:         "\n\n"
 2459:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2460:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2461:        ."\n"
 2462:     );
 2463: 
 2464:     # Show additional functions if allowed
 2465:     if ($perm{'vgr'}) {
 2466:         $request->print(
 2467:             &Apache::loncommon::track_student_link(
 2468:                 'View recent activity',
 2469:                 $uname,$udom,'check')
 2470:            .' '
 2471:         );
 2472:     }
 2473:     if ($perm{'opa'}) {
 2474:         $request->print(
 2475:             &Apache::loncommon::pprmlink(
 2476:                 &mt('Set/Change parameters'),
 2477:                 $uname,$udom,$symb,'check'));
 2478:     }
 2479: 
 2480:     # Show Problem
 2481:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2482: 	my $mode;
 2483: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2484: 	    $mode='both';
 2485: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2486: 	    $mode='text';
 2487: 	} elsif ($env{'form.vAns'} eq 'all') {
 2488: 	    $mode='answer';
 2489: 	}
 2490: 	&Apache::lonxml::clear_problem_counter();
 2491: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2492:     }
 2493: 
 2494:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2495: 
 2496:     # Display student info
 2497:     $request->print(($counter == 0 ? '' : '<br />'));
 2498: 
 2499:     my $result='<div class="LC_Box">'
 2500:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2501:     $result.='<input type="hidden" name="name'.$counter.
 2502:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2503:     if ($numresp > $numessay) {
 2504:         $result.='<p class="LC_info">'
 2505:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2506:                 ."</p>\n";
 2507:     }
 2508: 
 2509:     # If any part of the problem is an essayresponse, then check for collaborators
 2510:     my $fullname;
 2511:     my $col_fullnames = [];
 2512:     if ($numessay) {
 2513: 	(my $sub_result,$fullname,$col_fullnames)=
 2514: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2515: 				 $counter);
 2516: 	$result.=$sub_result;
 2517:     }
 2518:     $request->print($result."\n");
 2519: 
 2520:     # print student answer/submission
 2521:     # Options are (1) Last submission only
 2522:     #             (2) Last submission (with detailed information for that submission)
 2523:     #             (3) All transactions (by date)
 2524:     #             (4) The whole record (with detailed information for all transactions)
 2525: 
 2526:     my ($string,$timestamp)= &get_last_submission(\%record);
 2527: 
 2528:     my $lastsubonly;
 2529: 
 2530:     if ($$timestamp eq '') {
 2531:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2532:     } else {
 2533:         $lastsubonly =
 2534:             '<div class="LC_grade_submissions_body">'
 2535:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2536: 
 2537: 	my %seenparts;
 2538: 	my @part_response_id = &flatten_responseType($responseType);
 2539: 	foreach my $part (@part_response_id) {
 2540: 	    my ($partid,$respid) = @{ $part };
 2541: 	    my $display_part=&get_display_part($partid,$symb);
 2542: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2543: 		if (exists($seenparts{$partid})) { next; }
 2544: 		$seenparts{$partid}=1;
 2545:                 $request->print(
 2546:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2547:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2548:                                '<a href="javascript:viewSubmitter(\''.
 2549:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2550:                                '\');" target="_self">'.
 2551:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2552:                     '<br />');
 2553: 		next;
 2554: 	    }
 2555: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2556: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2557:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2558:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2559:                     ' <span class="LC_internal_info">'.
 2560:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2561:                     '</span>&nbsp; &nbsp;'.
 2562: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2563: 		next;
 2564: 	    }
 2565: 	    foreach my $submission (@$string) {
 2566: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2567: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2568: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2569: 		# Similarity check
 2570:                 my $similar='';
 2571:                 my ($type,$trial,$rndseed);
 2572:                 if ($hide eq 'rand') {
 2573:                     $type = 'randomizetry';
 2574:                     $trial = $record{"resource.$partid.tries"};
 2575:                     $rndseed = $record{"resource.$partid.rndseed"};
 2576:                 }
 2577: 		if ($env{'form.checkPlag'}) {
 2578: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2579: 		        &most_similar($uname,$udom,$symb,$subval);
 2580: 		    if ($osim) {
 2581: 		        $osim=int($osim*100.0);
 2582:                         if ($hide eq 'anon') {
 2583:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2584:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2585:                         } else {
 2586: 			    $similar='<hr />';
 2587:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2588:                                 $similar .= '<h3><span class="LC_warning">'.
 2589:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2590:                                                 $osim,
 2591:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2592:                                             '</span></h3>';
 2593:                             } elsif ($ocrsid ne '') {
 2594:                                 my %old_course_desc;
 2595:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2596:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2597:                                 } else {
 2598:                                     my $args;
 2599:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2600:                                         $args = {'one_time' => 1};
 2601:                                     }
 2602:                                     %old_course_desc =
 2603:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2604:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2605:                                 }
 2606:                                 $similar .=
 2607:                                     '<h3><span class="LC_warning">'.
 2608: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2609: 				        $osim,
 2610: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2611: 				        $old_course_desc{'description'},
 2612: 				        $old_course_desc{'num'},
 2613: 				        $old_course_desc{'domain'}).
 2614: 				    '</span></h3>';
 2615:                             } else {
 2616:                                 $similar .=
 2617:                                     '<h3><span class="LC_warning">'.
 2618:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2619:                                         $osim,
 2620:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2621:                                     '</span></h3>';
 2622:                             }
 2623:                             $similar .= '<blockquote><i>'.
 2624:                                         &keywords_highlight($oessay).
 2625:                                         '</i></blockquote><hr />';
 2626: 		        }
 2627:                     }
 2628:                 }
 2629: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2630:                                      undef,$type,$trial,$rndseed);
 2631:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2632:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2633:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2634: 		    my $display_part=&get_display_part($partid,$symb);
 2635:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2636:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2637:                         ' <span class="LC_internal_info">'.
 2638:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2639:                         '</span>&nbsp; &nbsp;';
 2640: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2641: 		    if (@$files) {
 2642:                         if ($hide eq 'anon') {
 2643:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2644:                         } else {
 2645:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2646:                                          .'<br /><span class="LC_warning">';
 2647:                             if(@$files == 1) {
 2648:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2649:                             } else {
 2650:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2651:                             }
 2652:                             $lastsubonly .= '</span>';
 2653:                             foreach my $file (@$files) {
 2654:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2655:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2656:                             }
 2657:                         }
 2658: 			$lastsubonly.='<br />';
 2659: 		    }
 2660:                     if ($hide eq 'anon') {
 2661:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2662:                     } else {
 2663:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2664:                         if ($draft) {
 2665:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2666:                         }
 2667:                         $subval =
 2668: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2669: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2670:                         if ($responsetype eq 'essay') {
 2671:                             $subval =~ s{\n}{<br />}g;
 2672:                         }
 2673:                         $lastsubonly.=$subval."\n";
 2674:                     }
 2675:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2676: 		    $lastsubonly.='</div>';
 2677: 		}
 2678: 	    }
 2679: 	}
 2680: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2681:     }
 2682:     $request->print($lastsubonly);
 2683:     if ($env{'form.lastSub'} eq 'datesub') {
 2684:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2685: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2686:     }
 2687:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2688:         my $identifier = (&canmodify($usec)? $counter : '');
 2689: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2690: 								 $env{'request.course.id'},
 2691: 								 $last,'.submission',
 2692: 								 'Apache::grades::keywords_highlight',
 2693:                                                                  $usec,$identifier));
 2694:     }
 2695:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2696: 	.$udom.'" />'."\n");
 2697:     # return if view submission with no grading option
 2698:     if (!&canmodify($usec)) {
 2699:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2700:         return;
 2701:     } else {
 2702: 	$request->print('</div>'."\n");
 2703:     }
 2704: 
 2705:     # grading message center
 2706: 
 2707:     if ($env{'form.compmsg'}) {
 2708:         my $result='<div class="LC_Box">'.
 2709:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2710:                    '<div class="LC_grade_message_center_body">';
 2711:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2712:         my $msgfor = $givenn.' '.$lastname;
 2713:         if (scalar(@$col_fullnames) > 0) {
 2714:             my $lastone = pop(@$col_fullnames);
 2715:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2716:         }
 2717:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2718:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2719:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2720: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2721:                  ',\''.$msgfor.'\');" target="_self">'.
 2722:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2723:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2724:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2725:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2726:                  '<br />&nbsp;('.
 2727:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2728: 	         '</div></div>';
 2729:         $request->print($result);
 2730:     }
 2731: 
 2732:     my %seen = ();
 2733:     my @partlist;
 2734:     my @gradePartRespid;
 2735:     my @part_response_id = &flatten_responseType($responseType);
 2736:     $request->print(
 2737:         '<div class="LC_Box">'
 2738:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2739:     );
 2740:     $request->print(&gradeBox_start());
 2741:     foreach my $part_response_id (@part_response_id) {
 2742:     	my ($partid,$respid) = @{ $part_response_id };
 2743: 	my $part_resp = join('_',@{ $part_response_id });
 2744: 	next if ($seen{$partid} > 0);
 2745: 	$seen{$partid}++;
 2746: 	push(@partlist,$partid);
 2747: 	push(@gradePartRespid,$partid.'.'.$respid);
 2748: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2749:     }
 2750:     $request->print(&gradeBox_end()); # </div>
 2751:     $request->print('</div>');
 2752: 
 2753:     $request->print('<div class="LC_grade_info_links">');
 2754:     $request->print('</div>');
 2755: 
 2756:     $result='<input type="hidden" name="partlist'.$counter.
 2757: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2758:     $result.='<input type="hidden" name="gradePartRespid'.
 2759: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2760:     my $ctr = 0;
 2761:     while ($ctr < scalar(@partlist)) {
 2762: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2763: 	    $partlist[$ctr].'" />'."\n";
 2764: 	$ctr++;
 2765:     }
 2766:     $request->print($result.''."\n");
 2767: 
 2768: # Done with printing info for one student
 2769: 
 2770:     $request->print('</div>');#LC_grade_show_user
 2771: 
 2772: 
 2773:     # print end of form
 2774:     if ($counter == $total) {
 2775:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2776: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2777: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2778: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2779: 	my $ntstu ='<select name="NTSTU">'.
 2780: 	    '<option>1</option><option>2</option>'.
 2781: 	    '<option>3</option><option>5</option>'.
 2782: 	    '<option>7</option><option>10</option></select>'."\n";
 2783: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2784: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2785:         $endform.=&mt('[_1]student(s)',$ntstu);
 2786: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2787: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2788: 	    '<input type="button" value="'.&mt('Next').'" '.
 2789: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2790:         $endform.='<span class="LC_warning">'.
 2791:                   &mt('(Next and Previous (student) do not save the scores.)').
 2792:                   '</span>'."\n" ;
 2793:         $endform.="<input type='hidden' value='".&get_increment().
 2794:             "' name='increment' />";
 2795: 	$endform.='</td></tr></table></form>';
 2796: 	$request->print($endform);
 2797:     }
 2798:     return '';
 2799: }
 2800: 
 2801: sub check_collaborators {
 2802:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2803:     my ($result,@col_fullnames);
 2804:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2805:     foreach my $part (keys(%$handgrade)) {
 2806: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2807: 					'.maxcollaborators',
 2808: 					$symb,$udom,$uname);
 2809: 	next if ($ncol <= 0);
 2810: 	$part =~ s/\_/\./g;
 2811: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2812: 	my (@good_collaborators, @bad_collaborators);
 2813: 	foreach my $possible_collaborator
 2814: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2815: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2816: 	    next if ($possible_collaborator eq '');
 2817: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2818: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2819: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2820: 	    # Doing this grep allows 'fuzzy' specification
 2821: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2822: 			       keys(%$classlist));
 2823: 	    if (! scalar(@matches)) {
 2824: 		push(@bad_collaborators, $possible_collaborator);
 2825: 	    } else {
 2826: 		push(@good_collaborators, @matches);
 2827: 	    }
 2828: 	}
 2829: 	if (scalar(@good_collaborators) != 0) {
 2830: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2831: 	    foreach my $name (@good_collaborators) {
 2832: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2833: 		push(@col_fullnames, $givenn.' '.$lastname);
 2834: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2835: 	    }
 2836: 	    $result.='</ol><br />'."\n";
 2837: 	    my ($part)=split(/\./,$part);
 2838: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2839: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2840: 		"\n";
 2841: 	}
 2842: 	if (scalar(@bad_collaborators) > 0) {
 2843: 	    $result.='<div class="LC_warning">';
 2844: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2845: 	    $result .= '</div>';
 2846: 	}         
 2847: 	if (scalar(@bad_collaborators > $ncol)) {
 2848: 	    $result .= '<div class="LC_warning">';
 2849: 	    $result .= &mt('This student has submitted too many '.
 2850: 		'collaborators.  Maximum is [_1].',$ncol);
 2851: 	    $result .= '</div>';
 2852: 	}
 2853:     }
 2854:     return ($result,$fullname,\@col_fullnames);
 2855: }
 2856: 
 2857: #--- Retrieve the last submission for all the parts
 2858: sub get_last_submission {
 2859:     my ($returnhash)=@_;
 2860:     my (@string,$timestamp,%lasthidden);
 2861:     if ($$returnhash{'version'}) {
 2862: 	my %lasthash=();
 2863: 	my ($version);
 2864: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2865: 	    foreach my $key (sort(split(/\:/,
 2866: 					$$returnhash{$version.':keys'}))) {
 2867: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2868: 		$timestamp = 
 2869: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2870: 	    }
 2871: 	}
 2872:         my (%typeparts,%randombytry);
 2873:         my $showsurv = 
 2874:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2875:         foreach my $key (sort(keys(%lasthash))) {
 2876:             if ($key =~ /\.type$/) {
 2877:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2878:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2879:                     ($lasthash{$key} eq 'randomizetry')) {
 2880:                     my ($ign,@parts) = split(/\./,$key);
 2881:                     pop(@parts);
 2882:                     my $id = join('.',@parts);
 2883:                     if ($lasthash{$key} eq 'randomizetry') {
 2884:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2885:                     } else {
 2886:                         unless ($showsurv) {
 2887:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2888:                         }
 2889:                     }
 2890:                     delete($lasthash{$key});
 2891:                 }
 2892:             }
 2893:         }
 2894:         my @hidden = keys(%typeparts);
 2895:         my @randomize = keys(%randombytry);
 2896: 	foreach my $key (keys(%lasthash)) {
 2897: 	    next if ($key !~ /\.submission$/);
 2898:             my $hide;
 2899:             if (@hidden) {
 2900:                 foreach my $id (@hidden) {
 2901:                     if ($key =~ /^\Q$id\E/) {
 2902:                         $hide = 'anon';
 2903:                         last;
 2904:                     }
 2905:                 }
 2906:             }
 2907:             unless ($hide) {
 2908:                 if (@randomize) {
 2909:                     foreach my $id (@randomize) {
 2910:                         if ($key =~ /^\Q$id\E/) {
 2911:                             $hide = 'rand';
 2912:                             last;
 2913:                         }
 2914:                     }
 2915:                 }
 2916:             }
 2917: 	    my ($partid,$foo) = split(/submission$/,$key);
 2918: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2919:             push(@string, join(':', $key, $hide, $draft, (
 2920:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2921:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2922: 	}
 2923:     }
 2924:     if (!@string) {
 2925: 	$string[0] =
 2926: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2927:     }
 2928:     return (\@string,\$timestamp);
 2929: }
 2930: 
 2931: #--- High light keywords, with style choosen by user.
 2932: sub keywords_highlight {
 2933:     my $string    = shift;
 2934:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2935:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2936:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2937:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2938:     foreach my $keyword (@keylist) {
 2939: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2940:     }
 2941:     return $string;
 2942: }
 2943: 
 2944: # For Tasks provide a mechanism to display previous version for one specific student
 2945: 
 2946: sub show_previous_task_version {
 2947:     my ($request,$symb) = @_;
 2948:     if ($symb eq '') {
 2949:         $request->print(
 2950:             '<span class="LC_error">'.
 2951:             &mt('Unable to handle ambiguous references.').
 2952:             '</span>');
 2953:         return '';
 2954:     }
 2955:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2956:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2957:     if (!&canview($usec)) {
 2958:         $request->print('<span class="LC_warning">'.
 2959:                         &mt('Unable to view previous version for requested student.').
 2960:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2961:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2962:                         '</span>');
 2963:         return;
 2964:     }
 2965:     my $mode = 'both';
 2966:     my $isTask = ($symb =~/\.task$/);
 2967:     if ($isTask) {
 2968:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2969:             if ($env{'form.fullname'} eq '') {
 2970:                 $env{'form.fullname'} =
 2971:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2972:             }
 2973:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2974:             $request->print("\n\n".
 2975:                             '<div class="LC_grade_show_user">'.
 2976:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2977:                             '</h2>'."\n");
 2978:             &Apache::lonxml::clear_problem_counter();
 2979:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2980:                             {'previousversion' => $env{'form.previousversion'} }));
 2981:             $request->print("\n</div>");
 2982:         }
 2983:     }
 2984:     return;
 2985: }
 2986: 
 2987: sub choose_task_version_form {
 2988:     my ($symb,$uname,$udom,$nomenu) = @_;
 2989:     my $isTask = ($symb =~/\.task$/);
 2990:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2991:     if ($isTask) {
 2992:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2993:                                               $udom,$uname);
 2994:         if (($record{'resource.0.version'} eq '') ||
 2995:             ($record{'resource.0.version'} < 2)) {
 2996:             return ($record{'resource.0.version'},
 2997:                     $record{'resource.0.version'},$result,$js);
 2998:         } else {
 2999:             $current = $record{'resource.0.version'};
 3000:         }
 3001:         if ($env{'form.previousversion'}) {
 3002:             $displayed = $env{'form.previousversion'};
 3003:             $rowtitle = &mt('Choose another version:')
 3004:         } else {
 3005:             $displayed = $current;
 3006:             $rowtitle = &mt('Show earlier version:');
 3007:         }
 3008:         $result = '<div class="LC_left_float">';
 3009:         my $list;
 3010:         my $numversions = 0;
 3011:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3012:             if ($i == $current) {
 3013:                 if (!$env{'form.previousversion'} || $nomenu) {
 3014:                     next;
 3015:                 } else {
 3016:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3017:                     $numversions ++;
 3018:                 }
 3019:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3020:                 unless ($i == $env{'form.previousversion'}) {
 3021:                     $numversions ++;
 3022:                 }
 3023:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3024:             }
 3025:         }
 3026:         if ($numversions) {
 3027:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3028:             $result .=
 3029:                 '<form name="getprev" method="post" action=""'.
 3030:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3031:                 &Apache::loncommon::start_data_table().
 3032:                 &Apache::loncommon::start_data_table_row().
 3033:                 '<th align="left">'.$rowtitle.'</th>'.
 3034:                 '<td><select name="version">'.
 3035:                 '<option>'.&mt('Select').'</option>'.
 3036:                 $list.
 3037:                 '</select></td>'.
 3038:                 &Apache::loncommon::end_data_table_row();
 3039:             unless ($nomenu) {
 3040:                 $result .= &Apache::loncommon::start_data_table_row().
 3041:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3042:                 '<td><span class="LC_nobreak">'.
 3043:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3044:                 &mt('Yes').'</label>'.
 3045:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3046:                 '</span></td>'.
 3047:                 &Apache::loncommon::end_data_table_row();
 3048:             }
 3049:             $result .=
 3050:                 &Apache::loncommon::start_data_table_row().
 3051:                 '<th align="left">&nbsp;</th>'.
 3052:                 '<td>'.
 3053:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3054:                 '</td>'.
 3055:                 &Apache::loncommon::end_data_table_row().
 3056:                 &Apache::loncommon::end_data_table().
 3057:                 '</form>';
 3058:             $js = &previous_display_javascript($nomenu,$current);
 3059:         } elsif ($displayed && $nomenu) {
 3060:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3061:         } else {
 3062:             $result .= &mt('No previous versions to show for this student');
 3063:         }
 3064:         $result .= '</div>';
 3065:     }
 3066:     return ($current,$displayed,$result,$js);
 3067: }
 3068: 
 3069: sub previous_display_javascript {
 3070:     my ($nomenu,$current) = @_;
 3071:     my $js = <<"JSONE";
 3072: <script type="text/javascript">
 3073: // <![CDATA[
 3074: function previousVersion(uname,udom,symb) {
 3075:     var current = '$current';
 3076:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3077:     var prevstr = new RegExp("^\\\\d+\$");
 3078:     if (!prevstr.test(version)) {
 3079:         return false;
 3080:     }
 3081:     var url = '';
 3082:     if (version == current) {
 3083:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3084:     } else {
 3085:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3086:     }
 3087: JSONE
 3088:     if ($nomenu) {
 3089:         $js .= <<"JSTWO";
 3090:     document.location.href = url;
 3091: JSTWO
 3092:     } else {
 3093:         $js .= <<"JSTHREE";
 3094:     var newwin = 0;
 3095:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3096:         if (document.getprev.prevwin[i].checked == true) {
 3097:             newwin = document.getprev.prevwin[i].value;
 3098:         }
 3099:     }
 3100:     if (newwin == 1) {
 3101:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3102:         url = url+'&inhibitmenu=yes';
 3103:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3104:             previousWin = window.open(url,'',options,1);
 3105:         } else {
 3106:             previousWin.location.href = url;
 3107:         }
 3108:         previousWin.focus();
 3109:         return false;
 3110:     } else {
 3111:         document.location.href = url;
 3112:         return false;
 3113:     }
 3114: JSTHREE
 3115:     }
 3116:     $js .= <<"ENDJS";
 3117:     return false;
 3118: }
 3119: // ]]>
 3120: </script>
 3121: ENDJS
 3122: 
 3123: }
 3124: 
 3125: #--- Called from submission routine
 3126: sub processHandGrade {
 3127:     my ($request,$symb) = @_;
 3128:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3129:     my $button = $env{'form.gradeOpt'};
 3130:     my $ngrade = $env{'form.NCT'};
 3131:     my $ntstu  = $env{'form.NTSTU'};
 3132:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3133:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3134:     my ($res_error,%queueable);
 3135:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3136:     if ($res_error) {
 3137:         $request->print(&navmap_errormsg());
 3138:         return;
 3139:     } else {
 3140:         foreach my $part (@{$partlist}) {
 3141:             if (ref($responseType->{$part}) eq 'HASH') {
 3142:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3143:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3144:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3145:                         $queueable{$part} = 1;
 3146:                         last;
 3147:                     }
 3148:                 }
 3149:             }
 3150:         }
 3151:     }
 3152: 
 3153:     if ($button eq 'Save & Next') {
 3154: 	my $ctr = 0;
 3155: 	while ($ctr < $ngrade) {
 3156: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3157: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3158:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3159: 	    if ($errorflag eq 'no_score') {
 3160: 		$ctr++;
 3161: 		next;
 3162: 	    }
 3163: 	    if ($errorflag eq 'not_allowed') {
 3164:                 $request->print(
 3165:                     '<span class="LC_error">'
 3166:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3167:                    .'</span>');
 3168: 		$ctr++;
 3169: 		next;
 3170: 	    }
 3171:             if ($numhidden) {
 3172:                 $request->print(
 3173:                     '<span class="LC_info">'
 3174:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3175:                    .'</span><br />');
 3176:             }
 3177: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3178: 	    my ($subject,$message,$msgstatus) = ('','','');
 3179: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3180:             my ($feedurl,$showsymb) =
 3181: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3182: 	    my $messagetail;
 3183: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3184: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3185: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3186: 		$subject.=' ['.$restitle.']';
 3187: 		my (@msgnum) = split(/,/,$includemsg);
 3188: 		foreach (@msgnum) {
 3189: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3190: 		}
 3191: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3192: 		if ($env{'form.withgrades'.$ctr}) {
 3193: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3194: 		    $messagetail = " for <a href=\"".
 3195: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3196: 		}
 3197: 		$msgstatus = 
 3198:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3199: 						     $message.$messagetail,
 3200:                                                      undef,$feedurl,undef,
 3201:                                                      undef,undef,$showsymb,
 3202:                                                      $restitle);
 3203: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3204: 				$msgstatus.'<br />');
 3205: 	    }
 3206: 	    if ($env{'form.collaborator'.$ctr}) {
 3207: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3208: 		foreach my $collabstr (@collabstrs) {
 3209: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3210: 		    foreach my $collaborator (@collaborators) {
 3211: 			my ($errorflag,$pts,$wgt) = 
 3212: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3213: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3214: 			if ($errorflag eq 'not_allowed') {
 3215: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3216: 			    next;
 3217: 			} elsif ($message ne '') {
 3218: 			    my ($baseurl,$showsymb) = 
 3219: 				&get_feedurl_and_symb($symb,$collaborator,
 3220: 						      $udom);
 3221: 			    if ($env{'form.withgrades'.$ctr}) {
 3222: 				$messagetail = " for <a href=\"".
 3223:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3224: 			    }
 3225: 			    $msgstatus = 
 3226: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3227: 			}
 3228: 		    }
 3229: 		}
 3230: 	    }
 3231: 	    $ctr++;
 3232: 	}
 3233:     }
 3234: 
 3235:     my %keyhash = ();
 3236:     if ($numessay) {
 3237: 	# Keywords sorted in alphabatical order
 3238: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3239: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3240: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3241: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3242: 	$env{'form.keywords'} = join(' ',@keywords);
 3243: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3244: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3245: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3246: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3247: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3248:     }
 3249: 
 3250:     if ($env{'form.compmsg'}) {
 3251: 	# message center - Order of message gets changed. Blank line is eliminated.
 3252: 	# New messages are saved in env for the next student.
 3253: 	# All messages are saved in nohist_handgrade.db
 3254: 	my ($ctr,$idx) = (1,1);
 3255: 	while ($ctr <= $env{'form.savemsgN'}) {
 3256: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3257: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3258: 		$idx++;
 3259: 	    }
 3260: 	    $ctr++;
 3261: 	}
 3262: 	$ctr = 0;
 3263: 	while ($ctr < $ngrade) {
 3264: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3265: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3266: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3267: 		$idx++;
 3268: 	    }
 3269: 	    $ctr++;
 3270: 	}
 3271: 	$env{'form.savemsgN'} = --$idx;
 3272: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3273:     }
 3274:     if (($numessay) || ($env{'form.compmsg'})) {
 3275: 	my $putresult = &Apache::lonnet::put
 3276: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3277:     }
 3278: 
 3279:     # Called by Save & Refresh from Highlight Attribute Window
 3280:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3281:     if ($env{'form.refresh'} eq 'on') {
 3282: 	my ($ctr,$total) = (0,0);
 3283: 	while ($ctr < $ngrade) {
 3284: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3285: 	    $ctr++;
 3286: 	}
 3287: 	$env{'form.NTSTU'}=$ngrade;
 3288: 	$ctr = 0;
 3289: 	while ($ctr < $total) {
 3290: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3291: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3292: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3293: 	    &submission($request,$ctr,$total-1,$symb);
 3294: 	    $ctr++;
 3295: 	}
 3296: 	return '';
 3297:     }
 3298: 
 3299:     # Get the next/previous one or group of students
 3300:     my $firststu = $env{'form.unamedom0'};
 3301:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3302:     my $ctr = 2;
 3303:     while ($laststu eq '') {
 3304: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3305: 	$ctr++;
 3306: 	$laststu = $firststu if ($ctr > $ngrade);
 3307:     }
 3308: 
 3309:     my (@parsedlist,@nextlist);
 3310:     my ($nextflg) = 0;
 3311:     foreach my $item (sort 
 3312: 	     {
 3313: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3314: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3315: 		 }
 3316: 		 return $a cmp $b;
 3317: 	     } (keys(%$fullname))) {
 3318: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3319: 	    push(@parsedlist,$item);
 3320: 	}
 3321: 	$nextflg = 1 if ($item eq $laststu);
 3322: 	if ($button eq 'Previous') {
 3323: 	    last if ($item eq $firststu);
 3324: 	    push(@parsedlist,$item);
 3325: 	}
 3326:     }
 3327:     $ctr = 0;
 3328:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3329:     foreach my $student (@parsedlist) {
 3330: 	my $submitonly=$env{'form.submitonly'};
 3331: 	my ($uname,$udom) = split(/:/,$student);
 3332: 	
 3333: 	if ($submitonly eq 'queued') {
 3334: 	    my %queue_status = 
 3335: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3336: 							$udom,$uname);
 3337: 	    next if (!defined($queue_status{'gradingqueue'}));
 3338: 	}
 3339: 
 3340: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3341: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3342: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3343: 	    my $submitted = 0;
 3344: 	    my $ungraded = 0;
 3345: 	    my $incorrect = 0;
 3346: 	    foreach my $item (keys(%status)) {
 3347: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3348: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3349: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3350: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3351: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3352: 		    $submitted = 0;
 3353: 		}
 3354: 	    }
 3355: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3356: 				     $submitonly eq 'incorrect' ||
 3357: 				     $submitonly eq 'graded'));
 3358: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3359: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3360: 	}
 3361: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3362: 	last if ($ctr == $ntstu);
 3363: 	$ctr++;
 3364:     }
 3365: 
 3366:     $ctr = 0;
 3367:     my $total = scalar(@nextlist)-1;
 3368: 
 3369:     foreach (sort(@nextlist)) {
 3370: 	my ($uname,$udom,$submitter) = split(/:/);
 3371: 	$env{'form.student'}  = $uname;
 3372: 	$env{'form.userdom'}  = $udom;
 3373: 	$env{'form.fullname'} = $$fullname{$_};
 3374: 	&submission($request,$ctr,$total,$symb);
 3375: 	$ctr++;
 3376:     }
 3377:     if ($total < 0) {
 3378:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3379: 	$request->print($the_end);
 3380:     }
 3381:     return '';
 3382: }
 3383: 
 3384: #---- Save the score and award for each student, if changed
 3385: sub saveHandGrade {
 3386:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3387:     my @version_parts;
 3388:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3389: 					   $env{'request.course.id'});
 3390:     if (!&canmodify($usec)) { return('not_allowed'); }
 3391:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3392:     my @parts_graded;
 3393:     my %newrecord  = ();
 3394:     my ($pts,$wgt,$totchg) = ('','',0);
 3395:     my %aggregate = ();
 3396:     my $aggregateflag = 0;
 3397:     if ($env{'form.HIDE'.$newflg}) {
 3398:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3399:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3400:         $totchg += $numchgs;
 3401:     }
 3402:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3403:     foreach my $new_part (@parts) {
 3404: 	#collaborator ($submi may vary for different parts
 3405: 	if ($submitter && $new_part ne $part) { next; }
 3406: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3407: 	if ($dropMenu eq 'excused') {
 3408: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3409: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3410: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3411: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3412: 		}
 3413: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3414: 	    }
 3415: 	} elsif ($dropMenu eq 'reset status'
 3416: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3417: 	    foreach my $key (keys(%record)) {
 3418: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3419: 	    }
 3420: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3421: 		"$env{'user.name'}:$env{'user.domain'}";
 3422:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3423: 
 3424:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3425: 					       [$new_part]);
 3426:             my $aggtries =$totaltries;
 3427:             if ($last_resets{$new_part}) {
 3428:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3429: 					   $new_part);
 3430:             }
 3431: 
 3432:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3433:             if ($aggtries > 0) {
 3434:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3435:                 $aggregateflag = 1;
 3436:             }
 3437: 	} elsif ($dropMenu eq '') {
 3438: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3439: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3440: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3441: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3442: 		next;
 3443: 	    }
 3444: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3445: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3446: 	    my $partial= $pts/$wgt;
 3447: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3448: 		#do not update score for part if not changed.
 3449:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3450: 		next;
 3451: 	    } else {
 3452: 	        push(@parts_graded,$new_part);
 3453: 	    }
 3454: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3455: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3456: 	    }
 3457: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3458: 	    if ($partial == 0) {
 3459: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3460: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3461: 		}
 3462: 	    } else {
 3463: 		if ($record{$reckey} ne 'correct_by_override') {
 3464: 		    $newrecord{$reckey} = 'correct_by_override';
 3465: 		}
 3466: 	    }	    
 3467: 	    if ($submitter && 
 3468: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3469: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3470: 	    }
 3471: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3472: 		"$env{'user.name'}:$env{'user.domain'}";
 3473: 	}
 3474: 	# unless problem has been graded, set flag to version the submitted files
 3475: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3476: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3477: 	        $dropMenu eq 'reset status')
 3478: 	   {
 3479: 	    push(@version_parts,$new_part);
 3480: 	}
 3481:     }
 3482:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3483:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3484: 
 3485:     if (%newrecord) {
 3486:         if (@version_parts) {
 3487:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3488:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3489: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3490: 	    foreach my $new_part (@version_parts) {
 3491: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3492: 				$new_part,\%newrecord);
 3493: 	    }
 3494:         }
 3495: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3496: 				$env{'request.course.id'},$domain,$stuname);
 3497: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3498: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3499:     }
 3500:     if ($aggregateflag) {
 3501:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3502: 			      $cdom,$cnum);
 3503:     }
 3504:     return ('',$pts,$wgt,$totchg);
 3505: }
 3506: 
 3507: sub makehidden {
 3508:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3509:     return unless (ref($record) eq 'HASH');
 3510:     my %modified;
 3511:     my $numchanged = 0;
 3512:     if (exists($record->{$version.':keys'})) {
 3513:         my $partsregexp = $parts;
 3514:         $partsregexp =~ s/,/|/g;
 3515:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3516:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3517:                  my $item = $1;
 3518:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3519:                      $modified{$key} = $record->{$version.':'.$key};
 3520:                  }
 3521:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3522:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3523:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3524:                 $modified{$key} = $record->{$version.':'.$key};
 3525:             }
 3526:         }
 3527:         if (keys(%modified)) {
 3528:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3529:                                           $domain,$stuname,$tolog) eq 'ok') {
 3530:                 $numchanged ++;
 3531:             }
 3532:         }
 3533:     }
 3534:     return $numchanged;
 3535: }
 3536: 
 3537: sub check_and_remove_from_queue {
 3538:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3539:     my @ungraded_parts;
 3540:     foreach my $part (@{$parts}) {
 3541: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3542: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3543: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3544: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3545: 		) {
 3546:             if ($queueable->{$part}) {
 3547: 	        push(@ungraded_parts, $part);
 3548:             }
 3549: 	}
 3550:     }
 3551:     if ( !@ungraded_parts ) {
 3552: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3553: 					       $cnum,$domain,$stuname);
 3554:     }
 3555: }
 3556: 
 3557: sub handback_files {
 3558:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3559:     my $portfolio_root = '/userfiles/portfolio';
 3560:     my $res_error;
 3561:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3562:     if ($res_error) {
 3563:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3564:         return;
 3565:     }
 3566:     my @handedback;
 3567:     my $file_msg;
 3568:     my @part_response_id = &flatten_responseType($responseType);
 3569:     foreach my $part_response_id (@part_response_id) {
 3570:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3571: 	my $part_resp = join('_',@{ $part_response_id });
 3572:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3573:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3574:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3575: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3576:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3577:                     my ($directory,$answer_file) = 
 3578:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3579:                     my ($answer_name,$answer_ver,$answer_ext) =
 3580: 		        &file_name_version_ext($answer_file);
 3581: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3582:                     my $getpropath = 1;
 3583:                     my ($dir_list,$listerror) =
 3584:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3585:                                                  $domain,$stuname,$getpropath);
 3586: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3587:                     # fix filename
 3588:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3589:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3590:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3591:             	                                $save_file_name);
 3592:                     if ($result !~ m|^/uploaded/|) {
 3593:                         $request->print('<br /><span class="LC_error">'.
 3594:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3595:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3596:                                         '</span>');
 3597:                     } else {
 3598:                         # mark the file as read only
 3599:                         push(@handedback,$save_file_name);
 3600: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3601: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3602: 			}
 3603:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3604: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3605: 
 3606:                     }
 3607:                     $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>'));
 3608:                 }
 3609:             }
 3610:         }
 3611:     }
 3612:     if (@handedback > 0) {
 3613:         $request->print('<br />');
 3614:         my @what = ($symb,$env{'request.course.id'},'handback');
 3615:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3616:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3617:         my ($subject,$message);
 3618:         if (scalar(@handedback) == 1) {
 3619:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3620:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3621:         } else {
 3622:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3623:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3624:         }
 3625:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3626:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3627:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3628:         my ($feedurl,$showsymb) =
 3629:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3630:         my $restitle = &Apache::lonnet::gettitle($symb);
 3631:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3632:         my $msgstatus =
 3633:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3634:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3635:                  $restitle);
 3636:         if ($msgstatus) {
 3637:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3638:         }
 3639:     }
 3640:     return;
 3641: }
 3642: 
 3643: sub get_feedurl_and_symb {
 3644:     my ($symb,$uname,$udom) = @_;
 3645:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3646:     $url = &Apache::lonnet::clutter($url);
 3647:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3648: 					$symb,$udom,$uname);
 3649:     if ($encrypturl =~ /^yes$/i) {
 3650: 	&Apache::lonenc::encrypted(\$url,1);
 3651: 	&Apache::lonenc::encrypted(\$symb,1);
 3652:     }
 3653:     return ($url,$symb);
 3654: }
 3655: 
 3656: sub get_submitted_files {
 3657:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3658:     my @files;
 3659:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3660:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3661:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3662:     	    push(@files,$file_url.$file);
 3663:         }
 3664:     }
 3665:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3666:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3667:     }
 3668:     return (\@files);
 3669: }
 3670: 
 3671: # ----------- Provides number of tries since last reset.
 3672: sub get_num_tries {
 3673:     my ($record,$last_reset,$part) = @_;
 3674:     my $timestamp = '';
 3675:     my $num_tries = 0;
 3676:     if ($$record{'version'}) {
 3677:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3678:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3679:                 $timestamp = $$record{$version.':timestamp'};
 3680:                 if ($timestamp > $last_reset) {
 3681:                     $num_tries ++;
 3682:                 } else {
 3683:                     last;
 3684:                 }
 3685:             }
 3686:         }
 3687:     }
 3688:     return $num_tries;
 3689: }
 3690: 
 3691: # ----------- Determine decrements required in aggregate totals 
 3692: sub decrement_aggs {
 3693:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3694:     my %decrement = (
 3695:                         attempts => 0,
 3696:                         users => 0,
 3697:                         correct => 0
 3698:                     );
 3699:     $decrement{'attempts'} = $aggtries;
 3700:     if ($solvedstatus =~ /^correct/) {
 3701:         $decrement{'correct'} = 1;
 3702:     }
 3703:     if ($aggtries == $totaltries) {
 3704:         $decrement{'users'} = 1;
 3705:     }
 3706:     foreach my $type (keys(%decrement)) {
 3707:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3708:     }
 3709:     return;
 3710: }
 3711: 
 3712: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3713: sub get_last_resets {
 3714:     my ($symb,$courseid,$partids) =@_;
 3715:     my %last_resets;
 3716:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3717:     my $cname = $env{'course.'.$courseid.'.num'};
 3718:     my @keys;
 3719:     foreach my $part (@{$partids}) {
 3720: 	push(@keys,"$symb\0$part\0resettime");
 3721:     }
 3722:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3723: 				     $cdom,$cname);
 3724:     foreach my $part (@{$partids}) {
 3725: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3726:     }
 3727:     return %last_resets;
 3728: }
 3729: 
 3730: # ----------- Handles creating versions for portfolio files as answers
 3731: sub version_portfiles {
 3732:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3733:     my $version_parts = join('|',@$v_flag);
 3734:     my @returned_keys;
 3735:     my $parts = join('|', @$parts_graded);
 3736:     my $portfolio_root = '/userfiles/portfolio';
 3737:     foreach my $key (keys(%$record)) {
 3738:         my $new_portfiles;
 3739:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3740:             my @versioned_portfiles;
 3741:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3742:             foreach my $file (@portfiles) {
 3743:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3744:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3745: 		my ($answer_name,$answer_ver,$answer_ext) =
 3746: 		    &file_name_version_ext($answer_file);
 3747:                 my $getpropath = 1;
 3748:                 my ($dir_list,$listerror) =
 3749:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3750:                                              $stu_name,$getpropath);
 3751:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3752:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3753:                 if ($new_answer ne 'problem getting file') {
 3754:                     push(@versioned_portfiles, $directory.$new_answer);
 3755:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3756:                         [$directory.$new_answer],
 3757:                         [$symb,$env{'request.course.id'},'graded']);
 3758:                 }
 3759:             }
 3760:             $$record{$key} = join(',',@versioned_portfiles);
 3761:             push(@returned_keys,$key);
 3762:         }
 3763:     } 
 3764:     return (@returned_keys);   
 3765: }
 3766: 
 3767: sub get_next_version {
 3768:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3769:     my $version;
 3770:     if (ref($dir_list) eq 'ARRAY') {
 3771:         foreach my $row (@{$dir_list}) {
 3772:             my ($file) = split(/\&/,$row,2);
 3773:             my ($file_name,$file_version,$file_ext) =
 3774: 	        &file_name_version_ext($file);
 3775:             if (($file_name eq $answer_name) && 
 3776: 	        ($file_ext eq $answer_ext)) {
 3777:                 # gets here if filename and extension match, 
 3778:                 # regardless of version
 3779:                 if ($file_version ne '') {
 3780:                     # a versioned file is found  so save it for later
 3781:                     if ($file_version > $version) {
 3782: 		        $version = $file_version;
 3783:                     }
 3784: 	        }
 3785:             }
 3786:         }
 3787:     }
 3788:     $version ++;
 3789:     return($version);
 3790: }
 3791: 
 3792: sub version_selected_portfile {
 3793:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3794:     my ($answer_name,$answer_ver,$answer_ext) =
 3795:         &file_name_version_ext($file_name);
 3796:     my $new_answer;
 3797:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3798:     if($env{'form.copy'} eq '-1') {
 3799:         $new_answer = 'problem getting file';
 3800:     } else {
 3801:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3802:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3803:                             $stu_name,$domain,'copy',
 3804: 		        '/portfolio'.$directory.$new_answer);
 3805:     }    
 3806:     return ($new_answer);
 3807: }
 3808: 
 3809: sub file_name_version_ext {
 3810:     my ($file)=@_;
 3811:     my @file_parts = split(/\./, $file);
 3812:     my ($name,$version,$ext);
 3813:     if (@file_parts > 1) {
 3814: 	$ext=pop(@file_parts);
 3815: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3816: 	    $version=pop(@file_parts);
 3817: 	}
 3818: 	$name=join('.',@file_parts);
 3819:     } else {
 3820: 	$name=join('.',@file_parts);
 3821:     }
 3822:     return($name,$version,$ext);
 3823: }
 3824: 
 3825: #--------------------------------------------------------------------------------------
 3826: #
 3827: #-------------------------- Next few routines handles grading by section or whole class
 3828: #
 3829: #--- Javascript to handle grading by section or whole class
 3830: sub viewgrades_js {
 3831:     my ($request) = shift;
 3832: 
 3833:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3834:     &js_escape(\$alertmsg);
 3835:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3836:    function writePoint(partid,weight,point) {
 3837: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3838: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3839: 	if (point == "textval") {
 3840: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3841: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3842: 		alert("$alertmsg"+parseFloat(point));
 3843: 		var resetbox = false;
 3844: 		for (var i=0; i<radioButton.length; i++) {
 3845: 		    if (radioButton[i].checked) {
 3846: 			textbox.value = i;
 3847: 			resetbox = true;
 3848: 		    }
 3849: 		}
 3850: 		if (!resetbox) {
 3851: 		    textbox.value = "";
 3852: 		}
 3853: 		return;
 3854: 	    }
 3855: 	    if (parseFloat(point) > parseFloat(weight)) {
 3856: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3857: 				   ") greater than the weight for the part. Accept?");
 3858: 		if (resp == false) {
 3859: 		    textbox.value = "";
 3860: 		    return;
 3861: 		}
 3862: 	    }
 3863: 	    for (var i=0; i<radioButton.length; i++) {
 3864: 		radioButton[i].checked=false;
 3865: 		if (parseFloat(point) == i) {
 3866: 		    radioButton[i].checked=true;
 3867: 		}
 3868: 	    }
 3869: 
 3870: 	} else {
 3871: 	    textbox.value = parseFloat(point);
 3872: 	}
 3873: 	for (i=0;i<document.classgrade.total.value;i++) {
 3874: 	    var user = document.classgrade["ctr"+i].value;
 3875: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3876: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3877: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3878: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3879: 	    if (saveval != "correct") {
 3880: 		scorename.value = point;
 3881: 		if (selname[0].selected != true) {
 3882: 		    selname[0].selected = true;
 3883: 		}
 3884: 	    }
 3885: 	}
 3886: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3887:     }
 3888: 
 3889:     function writeRadText(partid,weight) {
 3890: 	var selval   = document.classgrade["SELVAL_"+partid];
 3891: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3892:         var override = document.classgrade["FORCE_"+partid].checked;
 3893: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3894: 	if (selval[1].selected || selval[2].selected) {
 3895: 	    for (var i=0; i<radioButton.length; i++) {
 3896: 		radioButton[i].checked=false;
 3897: 
 3898: 	    }
 3899: 	    textbox.value = "";
 3900: 
 3901: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3902: 		var user = document.classgrade["ctr"+i].value;
 3903: 		user = user.replace(new RegExp(':', 'g'),"_");
 3904: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3905: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3906: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3907: 		if ((saveval != "correct") || override) {
 3908: 		    scorename.value = "";
 3909: 		    if (selval[1].selected) {
 3910: 			selname[1].selected = true;
 3911: 		    } else {
 3912: 			selname[2].selected = true;
 3913: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3914: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3915: 		    }
 3916: 		}
 3917: 	    }
 3918: 	} else {
 3919: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3920: 		var user = document.classgrade["ctr"+i].value;
 3921: 		user = user.replace(new RegExp(':', 'g'),"_");
 3922: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3923: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3924: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3925: 		if ((saveval != "correct") || override) {
 3926: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3927: 		    selname[0].selected = true;
 3928: 		}
 3929: 	    }
 3930: 	}	    
 3931:     }
 3932: 
 3933:     function changeSelect(partid,user) {
 3934: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3935: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3936: 	var point  = textbox.value;
 3937: 	var weight = document.classgrade["weight_"+partid].value;
 3938: 
 3939: 	if (isNaN(point) || parseFloat(point) < 0) {
 3940: 	    alert("$alertmsg"+parseFloat(point));
 3941: 	    textbox.value = "";
 3942: 	    return;
 3943: 	}
 3944: 	if (parseFloat(point) > parseFloat(weight)) {
 3945: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3946: 			       ") greater than the weight of the part. Accept?");
 3947: 	    if (resp == false) {
 3948: 		textbox.value = "";
 3949: 		return;
 3950: 	    }
 3951: 	}
 3952: 	selval[0].selected = true;
 3953:     }
 3954: 
 3955:     function changeOneScore(partid,user) {
 3956: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3957: 	if (selval[1].selected || selval[2].selected) {
 3958: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3959: 	    if (selval[2].selected) {
 3960: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3961: 	    }
 3962:         }
 3963:     }
 3964: 
 3965:     function resetEntry(numpart) {
 3966: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3967: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3968: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3969: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3970: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3971: 	    for (var i=0; i<radioButton.length; i++) {
 3972: 		radioButton[i].checked=false;
 3973: 
 3974: 	    }
 3975: 	    textbox.value = "";
 3976: 	    selval[0].selected = true;
 3977: 
 3978: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3979: 		var user = document.classgrade["ctr"+i].value;
 3980: 		user = user.replace(new RegExp(':', 'g'),"_");
 3981: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3982: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3983: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3984: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3985: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3986: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3987: 		if (saveselval == "excused") {
 3988: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3989: 		} else {
 3990: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3991: 		}
 3992: 	    }
 3993: 	}
 3994:     }
 3995: 
 3996: VIEWJAVASCRIPT
 3997: }
 3998: 
 3999: #--- show scores for a section or whole class w/ option to change/update a score
 4000: sub viewgrades {
 4001:     my ($request,$symb) = @_;
 4002:     &viewgrades_js($request);
 4003: 
 4004:     #need to make sure we have the correct data for later EXT calls, 
 4005:     #thus invalidate the cache
 4006:     &Apache::lonnet::devalidatecourseresdata(
 4007:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4008:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4009:     &Apache::lonnet::clear_EXT_cache_status();
 4010: 
 4011:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 4012: 
 4013:     #view individual student submission form - called using Javascript viewOneStudent
 4014:     $result.=&jscriptNform($symb);
 4015: 
 4016:     #beginning of class grading form
 4017:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4018:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4019: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4020: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4021: 	&build_section_inputs().
 4022: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4023: 
 4024:     #retrieve selected groups
 4025:     my (@groups,$group_display);
 4026:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4027:     if (grep(/^all$/,@groups)) {
 4028:         @groups = ('all');
 4029:     } elsif (grep(/^none$/,@groups)) {
 4030:         @groups = ('none');
 4031:     } elsif (@groups > 0) {
 4032:         $group_display = join(', ',@groups);
 4033:     }
 4034: 
 4035:     my ($common_header,$specific_header,@sections,$section_display);
 4036:     if ($env{'request.course.sec'} ne '') {
 4037:         @sections = ($env{'request.course.sec'});
 4038:     } else {
 4039:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4040:     }
 4041: 
 4042: # Check if Save button should be usable
 4043:     my $disabled = ' disabled="disabled"';
 4044:     if ($perm{'mgr'}) {
 4045:         if (grep(/^all$/,@sections)) {
 4046:             undef($disabled);
 4047:         } else {
 4048:             foreach my $sec (@sections) {
 4049:                 if (&canmodify($sec)) {
 4050:                     undef($disabled);
 4051:                     last;
 4052:                 }
 4053:             }
 4054:         }
 4055:     }
 4056:     if (grep(/^all$/,@sections)) {
 4057:         @sections = ('all');
 4058:         if ($group_display) {
 4059:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4060:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4061:         } elsif (grep(/^none$/,@groups)) {
 4062:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4063:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4064:         } else {
 4065:             $common_header = &mt('Assign Common Grade to Class');
 4066:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4067:         }
 4068:     } elsif (grep(/^none$/,@sections)) {
 4069:         @sections = ('none');
 4070:         if ($group_display) {
 4071:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4072:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4073:         } elsif (grep(/^none$/,@groups)) {
 4074:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4075:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4076:         } else {
 4077:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4078:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4079:         }
 4080:     } else {
 4081:         $section_display = join (", ",@sections);
 4082:         if ($group_display) {
 4083:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4084:                                  $section_display,$group_display);
 4085:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4086:                                    $section_display,$group_display);
 4087:         } elsif (grep(/^none$/,@groups)) {
 4088:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4089:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4090:         } else {
 4091:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4092:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4093:         }
 4094:     }
 4095:     my %submit_types = &substatus_options();
 4096:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4097: 
 4098:     if ($env{'form.submitonly'} eq 'all') {
 4099:         $result.= '<h3>'.$common_header.'</h3>';
 4100:     } else {
 4101:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 4102:     }
 4103:     $result .= &Apache::loncommon::start_data_table();
 4104:     #radio buttons/text box for assigning points for a section or class.
 4105:     #handles different parts of a problem
 4106:     my $res_error;
 4107:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4108:     if ($res_error) {
 4109:         return &navmap_errormsg();
 4110:     }
 4111:     my %weight = ();
 4112:     my $ctsparts = 0;
 4113:     my %seen = ();
 4114:     my @part_response_id = &flatten_responseType($responseType);
 4115:     foreach my $part_response_id (@part_response_id) {
 4116:     	my ($partid,$respid) = @{ $part_response_id };
 4117: 	my $part_resp = join('_',@{ $part_response_id });
 4118: 	next if $seen{$partid};
 4119: 	$seen{$partid}++;
 4120: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4121: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4122: 
 4123: 	my $display_part=&get_display_part($partid,$symb);
 4124: 	my $radio.='<table border="0"><tr>';  
 4125: 	my $ctr = 0;
 4126: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4127: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4128: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4129: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4130: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4131: 	    $ctr++;
 4132: 	}
 4133: 	$radio.='</tr></table>';
 4134: 	my $line = '<input type="text" name="TEXTVAL_'.
 4135: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4136: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4137: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4138: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4139:                 '<select name="SELVAL_'.$partid.'" '.
 4140: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4141: 		$weight{$partid}.')"> '.
 4142: 	    '<option selected="selected"> </option>'.
 4143: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4144: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4145: 	    '</select></td>'.
 4146:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4147: 	$line.='<input type="hidden" name="partid_'.
 4148: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4149: 	$line.='<input type="hidden" name="weight_'.
 4150: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4151: 
 4152: 	$result.=
 4153: 	    &Apache::loncommon::start_data_table_row()."\n".
 4154: 	    '<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>'.
 4155: 	    &Apache::loncommon::end_data_table_row()."\n";
 4156: 	$ctsparts++;
 4157:     }
 4158:     $result.=&Apache::loncommon::end_data_table()."\n".
 4159: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4160:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4161: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4162: 
 4163:     #table listing all the students in a section/class
 4164:     #header of table
 4165:     if ($env{'form.submitonly'} eq 'all') { 
 4166:         $result.= '<h3>'.$specific_header.'</h3>';
 4167:     } else {
 4168:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 4169:     }
 4170:     $result.= &Apache::loncommon::start_data_table().
 4171: 	      &Apache::loncommon::start_data_table_header_row().
 4172: 	      '<th>'.&mt('No.').'</th>'.
 4173: 	      '<th>'.&nameUserString('header')."</th>\n";
 4174:     my $partserror;
 4175:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4176:     if ($partserror) {
 4177:         return &navmap_errormsg();
 4178:     }
 4179:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4180:     my @partids = ();
 4181:     foreach my $part (@parts) {
 4182: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4183:         my $narrowtext = &mt('Tries');
 4184: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4185: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 4186: 	my ($partid) = &split_part_type($part);
 4187:         push(@partids,$partid);
 4188: #
 4189: # FIXME: Looks like $display looks at English text
 4190: #
 4191: 	my $display_part=&get_display_part($partid,$symb);
 4192: 	if ($display =~ /^Partial Credit Factor/) {
 4193: 	    $result.='<th>'.
 4194:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4195:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4196: 	    next;
 4197: 	    
 4198: 	} else {
 4199: 	    if ($display =~ /Problem Status/) {
 4200: 		my $grade_status_mt = &mt('Grade Status');
 4201: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4202: 	    }
 4203: 	    my $part_mt = &mt('Part:');
 4204: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4205: 	}
 4206: 
 4207: 	$result.='<th>'.$display.'</th>'."\n";
 4208:     }
 4209:     $result.=&Apache::loncommon::end_data_table_header_row();
 4210: 
 4211:     my %last_resets = 
 4212: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4213: 
 4214:     #get info for each student
 4215:     #list all the students - with points and grade status
 4216:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4217:     my $ctr = 0;
 4218:     foreach (sort 
 4219: 	     {
 4220: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4221: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4222: 		 }
 4223: 		 return $a cmp $b;
 4224: 	     } (keys(%$fullname))) {
 4225: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4226: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 4227:     }
 4228:     $result.=&Apache::loncommon::end_data_table();
 4229:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4230:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4231: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4232:     if ($ctr == 0) {
 4233:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4234:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4235:                 '<span class="LC_warning">';
 4236:         if ($env{'form.submitonly'} eq 'all') {
 4237:             if (grep(/^all$/,@sections)) {
 4238:                 if (grep(/^all$/,@groups)) {
 4239:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4240:                                    $stu_status);
 4241:                 } elsif (grep(/^none$/,@groups)) {
 4242:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4243:                                    $stu_status);
 4244:                 } else {
 4245:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4246:                                    $group_display,$stu_status);
 4247:                 }
 4248:             } elsif (grep(/^none$/,@sections)) {
 4249:                 if (grep(/^all$/,@groups)) {
 4250:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4251:                                    $stu_status);
 4252:                 } elsif (grep(/^none$/,@groups)) {
 4253:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4254:                                    $stu_status);
 4255:                 } else {
 4256:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4257:                                    $group_display,$stu_status);
 4258:                 }
 4259:             } else {
 4260:                 if (grep(/^all$/,@groups)) {
 4261:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4262:                                    $section_display,$stu_status);
 4263:                 } elsif (grep(/^none$/,@groups)) {
 4264:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4265:                                    $section_display,$stu_status);
 4266:                 } else {
 4267:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4268:                                    $section_display,$group_display,$stu_status);
 4269:                 }
 4270:             }
 4271:         } else {
 4272:             if (grep(/^all$/,@sections)) {
 4273:                 if (grep(/^all$/,@groups)) {
 4274:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4275:                                    $stu_status,$submission_status);
 4276:                 } elsif (grep(/^none$/,@groups)) {
 4277:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4278:                                    $stu_status,$submission_status);
 4279:                 } else {
 4280:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4281:                                    $group_display,$stu_status,$submission_status);
 4282:                 }
 4283:             } elsif (grep(/^none$/,@sections)) {
 4284:                 if (grep(/^all$/,@groups)) {
 4285:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4286:                                    $stu_status,$submission_status);
 4287:                 } elsif (grep(/^none$/,@groups)) {
 4288:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4289:                                    $stu_status,$submission_status);
 4290:                 } else {
 4291:                     $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.',
 4292:                                    $group_display,$stu_status,$submission_status);
 4293:                 }
 4294:             } else {
 4295:                 if (grep(/^all$/,@groups)) {
 4296:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4297:                                    $section_display,$stu_status,$submission_status);
 4298:                 } elsif (grep(/^none$/,@groups)) {
 4299:                     $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.',
 4300:                                    $section_display,$stu_status,$submission_status);
 4301:                 } else {
 4302:                     $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.',
 4303:                                    $section_display,$group_display,$stu_status,$submission_status);
 4304:                 }
 4305:             }
 4306: 	}
 4307: 	$result .= '</span><br />';
 4308:     }
 4309:     return $result;
 4310: }
 4311: 
 4312: #--- call by previous routine to display each student who satisfies submission filter.
 4313: sub viewstudentgrade {
 4314:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4315:     my ($uname,$udom) = split(/:/,$student);
 4316:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4317:     my $submitonly = $env{'form.submitonly'};
 4318:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4319:         my %partstatus = ();
 4320:         if (ref($parts) eq 'ARRAY') {
 4321:             foreach my $apart (@{$parts}) {
 4322:                 my ($part,$type) = &split_part_type($apart);
 4323:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4324:                 $status = 'nothing' if ($status eq '');
 4325:                 $partstatus{$part}      = $status;
 4326:                 my $subkey = "resource.$part.submitted_by";
 4327:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4328:             }
 4329:             my $submitted = 0;
 4330:             my $graded = 0;
 4331:             my $incorrect = 0;
 4332:             foreach my $key (keys(%partstatus)) {
 4333:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4334:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4335:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4336: 
 4337:                 my $partid = (split(/\./,$key))[1];
 4338:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4339:                     $submitted = 0;
 4340:                 }
 4341:             }
 4342:             return if (!$submitted && ($submitonly eq 'yes' ||
 4343:                                        $submitonly eq 'incorrect' ||
 4344:                                        $submitonly eq 'graded'));
 4345:             return if (!$graded && ($submitonly eq 'graded'));
 4346:             return if (!$incorrect && $submitonly eq 'incorrect');
 4347:         }
 4348:     }
 4349:     if ($submitonly eq 'queued') {
 4350:         my ($cdom,$cnum) = split(/_/,$courseid);
 4351:         my %queue_status =
 4352:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4353:                                                     $udom,$uname);
 4354:         return if (!defined($queue_status{'gradingqueue'}));
 4355:     }
 4356:     $$ctr++;
 4357:     my %aggregates = ();
 4358:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4359: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4360: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4361: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4362: 	'\');" target="_self">'.$fullname.'</a> '.
 4363: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4364:     $student=~s/:/_/; # colon doen't work in javascript for names
 4365:     foreach my $apart (@$parts) {
 4366: 	my ($part,$type) = &split_part_type($apart);
 4367: 	my $score=$record{"resource.$part.$type"};
 4368:         $result.='<td align="center">';
 4369:         my ($aggtries,$totaltries);
 4370:         unless (exists($aggregates{$part})) {
 4371: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4372: 
 4373: 	    $aggtries = $totaltries;
 4374:             if ($$last_resets{$part}) {  
 4375:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4376: 					   $part);
 4377:             }
 4378:             $result.='<input type="hidden" name="'.
 4379:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4380:             $result.='<input type="hidden" name="'.
 4381:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4382:             $aggregates{$part} = 1;
 4383:         }
 4384: 	if ($type eq 'awarded') {
 4385: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4386: 	    $result.='<input type="hidden" name="'.
 4387: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4388: 	    $result.='<input type="text" name="'.
 4389: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4390:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4391: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4392: 	} elsif ($type eq 'solved') {
 4393: 	    my ($status,$foo)=split(/_/,$score,2);
 4394: 	    $status = 'nothing' if ($status eq '');
 4395: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4396: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4397: 	    $result.='&nbsp;<select name="'.
 4398: 		'GD_'.$student.'_'.$part.'_solved" '.
 4399:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4400: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4401: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4402: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4403: 	    $result.="</select>&nbsp;</td>\n";
 4404: 	} else {
 4405: 	    $result.='<input type="hidden" name="'.
 4406: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4407: 		    "\n";
 4408: 	    $result.='<input type="text" name="'.
 4409: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4410: 		'value="'.$score.'" size="4" /></td>'."\n";
 4411: 	}
 4412:     }
 4413:     $result.=&Apache::loncommon::end_data_table_row();
 4414:     return $result;
 4415: }
 4416: 
 4417: #--- change scores for all the students in a section/class
 4418: #    record does not get update if unchanged
 4419: sub editgrades {
 4420:     my ($request,$symb) = @_;
 4421: 
 4422:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4423:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4424:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4425: 
 4426:     my $result= &Apache::loncommon::start_data_table().
 4427: 	&Apache::loncommon::start_data_table_header_row().
 4428: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4429: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4430:     my %scoreptr = (
 4431: 		    'correct'  =>'correct_by_override',
 4432: 		    'incorrect'=>'incorrect_by_override',
 4433: 		    'excused'  =>'excused',
 4434: 		    'ungraded' =>'ungraded_attempted',
 4435:                     'credited' =>'credit_attempted',
 4436: 		    'nothing'  => '',
 4437: 		    );
 4438:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4439: 
 4440:     my (@partid);
 4441:     my %weight = ();
 4442:     my %columns = ();
 4443:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4444: 
 4445:     my $partserror;
 4446:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4447:     if ($partserror) {
 4448:         return &navmap_errormsg();
 4449:     }
 4450:     my $header;
 4451:     while ($ctr < $env{'form.totalparts'}) {
 4452: 	my $partid = $env{'form.partid_'.$ctr};
 4453: 	push(@partid,$partid);
 4454: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4455: 	$ctr++;
 4456:     }
 4457:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4458:     my $totcolspan = 0;
 4459:     foreach my $partid (@partid) {
 4460: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4461: 	    '<th align="center">'.&mt('New Score').'</th>';
 4462: 	$columns{$partid}=2;
 4463: 	foreach my $stores (@parts) {
 4464: 	    my ($part,$type) = &split_part_type($stores);
 4465: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4466: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4467: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4468: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4469:             my $narrowtext = &mt('Tries');
 4470: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4471: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4472: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4473: 	    $columns{$partid}+=2;
 4474: 	}
 4475:         $totcolspan += $columns{$partid};
 4476:     }
 4477:     foreach my $partid (@partid) {
 4478: 	my $display_part=&get_display_part($partid,$symb);
 4479: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4480: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4481: 	    '</th>';
 4482: 
 4483:     }
 4484:     $result .= &Apache::loncommon::end_data_table_header_row().
 4485: 	&Apache::loncommon::start_data_table_header_row().
 4486: 	$header.
 4487: 	&Apache::loncommon::end_data_table_header_row();
 4488:     my @noupdate;
 4489:     my ($updateCtr,$noupdateCtr) = (1,1);
 4490:     my ($got_types,%queueable);
 4491:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4492: 	my $user = $env{'form.ctr'.$i};
 4493: 	my ($uname,$udom)=split(/:/,$user);
 4494: 	my %newrecord;
 4495: 	my $updateflag = 0;
 4496:         my $usec=$classlist->{"$uname:$udom"}[5];
 4497:         my $canmodify = &canmodify($usec);
 4498:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4499:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4500:         if (!$canmodify) {
 4501:             push(@noupdate,
 4502:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4503:                  &mt('Not allowed to modify student')."</span></td>");
 4504:             next;
 4505:         }
 4506:         my %aggregate = ();
 4507:         my $aggregateflag = 0;
 4508: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4509: 	foreach (@partid) {
 4510: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4511: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4512: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4513: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4514: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4515: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4516: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4517: 	    my $score;
 4518: 	    if ($partial eq '') {
 4519: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4520: 	    } elsif ($partial > 0) {
 4521: 		$score = 'correct_by_override';
 4522: 	    } elsif ($partial == 0) {
 4523: 		$score = 'incorrect_by_override';
 4524: 	    }
 4525: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4526: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4527: 
 4528: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4529: 		"$env{'user.name'}:$env{'user.domain'}";
 4530: 	    if ($dropMenu eq 'reset status' &&
 4531: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4532: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4533: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4534: 		$newrecord{'resource.'.$_.'.award'} = '';
 4535: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4536: 		$updateflag = 1;
 4537:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4538:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4539:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4540:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4541:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4542:                     $aggregateflag = 1;
 4543:                 }
 4544: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4545: 		$updateflag = 1;
 4546: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4547: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4548: 		$rec_update++;
 4549: 	    }
 4550: 
 4551: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4552: 		'<td align="center">'.$awarded.
 4553: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4554: 
 4555: 
 4556: 	    my $partid=$_;
 4557: 	    foreach my $stores (@parts) {
 4558: 		my ($part,$type) = &split_part_type($stores);
 4559: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4560: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4561: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4562: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4563: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4564: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4565: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4566: 		    $updateflag=1;
 4567: 		}
 4568: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4569: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4570: 	    }
 4571: 	}
 4572: 	$line.="\n";
 4573: 
 4574: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4575: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4576: 
 4577: 	if ($updateflag) {
 4578: 	    $count++;
 4579: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4580: 				    $udom,$uname);
 4581: 
 4582: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4583: 					      $cnum,$udom,$uname)) {
 4584: 		# need to figure out if should be in queue.
 4585: 		my %record =  
 4586: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4587: 					     $udom,$uname);
 4588: 		my $all_graded = 1;
 4589: 		my $none_graded = 1;
 4590:                 unless ($got_types) {
 4591:                     my $error;
 4592:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4593:                     unless ($error) {
 4594:                         foreach my $part (@parts) {
 4595:                             if (ref($resptype->{$part}) eq 'HASH') {
 4596:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4597:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4598:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4599:                                         $queueable{$part} = 1;
 4600:                                         last;
 4601:                                     }
 4602:                                 }
 4603:                             }
 4604:                         }
 4605:                     }
 4606:                     $got_types = 1;
 4607:                 }
 4608: 		foreach my $part (@parts) {
 4609:                     if ($queueable{$part}) {
 4610: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4611: 			    $all_graded = 0;
 4612: 		        } else {
 4613: 			    $none_graded = 0;
 4614: 		        }
 4615:                     }
 4616: 		}
 4617: 
 4618: 		if ($all_graded || $none_graded) {
 4619: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4620: 							   $symb,$cdom,$cnum,
 4621: 							   $udom,$uname);
 4622: 		}
 4623: 	    }
 4624: 
 4625: 	    $result.=&Apache::loncommon::start_data_table_row().
 4626: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4627: 		&Apache::loncommon::end_data_table_row();
 4628: 	    $updateCtr++;
 4629: 	} else {
 4630: 	    push(@noupdate,
 4631: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4632: 	    $noupdateCtr++;
 4633: 	}
 4634:         if ($aggregateflag) {
 4635:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4636: 				  $cdom,$cnum);
 4637:         }
 4638:     }
 4639:     if (@noupdate) {
 4640:         my $numcols=$totcolspan+2;
 4641: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4642: 	    '<td align="center" colspan="'.$numcols.'">'.
 4643: 	    &mt('No Changes Occurred For the Students Below').
 4644: 	    '</td>'.
 4645: 	    &Apache::loncommon::end_data_table_row();
 4646: 	foreach my $line (@noupdate) {
 4647: 	    $result.=
 4648: 		&Apache::loncommon::start_data_table_row().
 4649: 		$line.
 4650: 		&Apache::loncommon::end_data_table_row();
 4651: 	}
 4652:     }
 4653:     $result .= &Apache::loncommon::end_data_table();
 4654:     my $msg = '<p><b>'.
 4655: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4656: 	    $rec_update,$count).'</b><br />'.
 4657: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4658: 	'</b></p>';
 4659:     return $title.$msg.$result;
 4660: }
 4661: 
 4662: sub split_part_type {
 4663:     my ($partstr) = @_;
 4664:     my ($temp,@allparts)=split(/_/,$partstr);
 4665:     my $type=pop(@allparts);
 4666:     my $part=join('_',@allparts);
 4667:     return ($part,$type);
 4668: }
 4669: 
 4670: #------------- end of section for handling grading by section/class ---------
 4671: #
 4672: #----------------------------------------------------------------------------
 4673: 
 4674: 
 4675: #----------------------------------------------------------------------------
 4676: #
 4677: #-------------------------- Next few routines handles grading by csv upload
 4678: #
 4679: #--- Javascript to handle csv upload
 4680: sub csvupload_javascript_reverse_associate {
 4681:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4682:     my $error2=&mt('You need to specify at least one grading field');
 4683:   &js_escape(\$error1);
 4684:   &js_escape(\$error2);
 4685:   return(<<ENDPICK);
 4686:   function verify(vf) {
 4687:     var foundsomething=0;
 4688:     var founduname=0;
 4689:     var foundID=0;
 4690:     for (i=0;i<=vf.nfields.value;i++) {
 4691:       tw=eval('vf.f'+i+'.selectedIndex');
 4692:       if (i==0 && tw!=0) { foundID=1; }
 4693:       if (i==1 && tw!=0) { founduname=1; }
 4694:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4695:     }
 4696:     if (founduname==0 && foundID==0) {
 4697: 	alert('$error1');
 4698: 	return;
 4699:     }
 4700:     if (foundsomething==0) {
 4701: 	alert('$error2');
 4702: 	return;
 4703:     }
 4704:     vf.submit();
 4705:   }
 4706:   function flip(vf,tf) {
 4707:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4708:     var i;
 4709:     for (i=0;i<=vf.nfields.value;i++) {
 4710:       //can not pick the same destination field for both name and domain
 4711:       if (((i ==0)||(i ==1)) && 
 4712:           ((tf==0)||(tf==1)) && 
 4713:           (i!=tf) &&
 4714:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4715:         eval('vf.f'+i+'.selectedIndex=0;')
 4716:       }
 4717:     }
 4718:   }
 4719: ENDPICK
 4720: }
 4721: 
 4722: sub csvupload_javascript_forward_associate {
 4723:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4724:     my $error2=&mt('You need to specify at least one grading field');
 4725:   &js_escape(\$error1);
 4726:   &js_escape(\$error2);
 4727:   return(<<ENDPICK);
 4728:   function verify(vf) {
 4729:     var foundsomething=0;
 4730:     var founduname=0;
 4731:     var foundID=0;
 4732:     for (i=0;i<=vf.nfields.value;i++) {
 4733:       tw=eval('vf.f'+i+'.selectedIndex');
 4734:       if (tw==1) { foundID=1; }
 4735:       if (tw==2) { founduname=1; }
 4736:       if (tw>3) { foundsomething=1; }
 4737:     }
 4738:     if (founduname==0 && foundID==0) {
 4739: 	alert('$error1');
 4740: 	return;
 4741:     }
 4742:     if (foundsomething==0) {
 4743: 	alert('$error2');
 4744: 	return;
 4745:     }
 4746:     vf.submit();
 4747:   }
 4748:   function flip(vf,tf) {
 4749:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4750:     var i;
 4751:     //can not pick the same destination field twice
 4752:     for (i=0;i<=vf.nfields.value;i++) {
 4753:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4754:         eval('vf.f'+i+'.selectedIndex=0;')
 4755:       }
 4756:     }
 4757:   }
 4758: ENDPICK
 4759: }
 4760: 
 4761: sub csvuploadmap_header {
 4762:     my ($request,$symb,$datatoken,$distotal)= @_;
 4763:     my $javascript;
 4764:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4765: 	$javascript=&csvupload_javascript_reverse_associate();
 4766:     } else {
 4767: 	$javascript=&csvupload_javascript_forward_associate();
 4768:     }
 4769: 
 4770:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4771:     my $ignore=&mt('Ignore First Line');
 4772:     $symb = &Apache::lonenc::check_encrypt($symb);
 4773:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4774:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4775:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4776:     my $reverse=&mt("Reverse Association");
 4777:     $request->print(<<ENDPICK);
 4778: <br />
 4779: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4780: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4781: <input type="hidden" name="associate"  value="" />
 4782: <input type="hidden" name="phase"      value="three" />
 4783: <input type="hidden" name="datatoken"  value="$datatoken" />
 4784: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4785: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4786: <input type="hidden" name="upfile_associate" 
 4787:                                        value="$env{'form.upfile_associate'}" />
 4788: <input type="hidden" name="symb"       value="$symb" />
 4789: <input type="hidden" name="command"    value="csvuploadoptions" />
 4790: <hr />
 4791: ENDPICK
 4792:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4793:     return '';
 4794: 
 4795: }
 4796: 
 4797: sub csvupload_fields {
 4798:     my ($symb,$errorref) = @_;
 4799:     my (@parts) = &getpartlist($symb,$errorref);
 4800:     if (ref($errorref)) {
 4801:         if ($$errorref) {
 4802:             return;
 4803:         }
 4804:     }
 4805: 
 4806:     my @fields=(['ID','Student/Employee ID'],
 4807: 		['username','Student Username'],
 4808: 		['domain','Student Domain']);
 4809:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4810:     foreach my $part (sort(@parts)) {
 4811: 	my @datum;
 4812: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4813: 	my $name=$part;
 4814: 	if  (!$display) { $display = $name; }
 4815: 	@datum=($name,$display);
 4816: 	if ($name=~/^stores_(.*)_awarded/) {
 4817: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4818: 	}
 4819: 	push(@fields,\@datum);
 4820:     }
 4821:     return (@fields);
 4822: }
 4823: 
 4824: sub csvuploadmap_footer {
 4825:     my ($request,$i,$keyfields) =@_;
 4826:     my $buttontext = &mt('Assign Grades');
 4827:     $request->print(<<ENDPICK);
 4828: </table>
 4829: <input type="hidden" name="nfields" value="$i" />
 4830: <input type="hidden" name="keyfields" value="$keyfields" />
 4831: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4832: </form>
 4833: ENDPICK
 4834: }
 4835: 
 4836: sub checkforfile_js {
 4837:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4838:     &js_escape(\$alertmsg);
 4839:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4840:     function checkUpload(formname) {
 4841: 	if (formname.upfile.value == "") {
 4842: 	    alert("$alertmsg");
 4843: 	    return false;
 4844: 	}
 4845: 	formname.submit();
 4846:     }
 4847: CSVFORMJS
 4848:     return $result;
 4849: }
 4850: 
 4851: sub upcsvScores_form {
 4852:     my ($request,$symb) = @_;
 4853:     if (!$symb) {return '';}
 4854:     my $result=&checkforfile_js();
 4855:     $result.=&Apache::loncommon::start_data_table().
 4856:              &Apache::loncommon::start_data_table_header_row().
 4857:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4858:              &Apache::loncommon::end_data_table_header_row().
 4859:              &Apache::loncommon::start_data_table_row().'<td>';
 4860:     my $upload=&mt("Upload Scores");
 4861:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4862:     my $ignore=&mt('Ignore First Line');
 4863:     $symb = &Apache::lonenc::check_encrypt($symb);
 4864:     $result.=<<ENDUPFORM;
 4865: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4866: <input type="hidden" name="symb" value="$symb" />
 4867: <input type="hidden" name="command" value="csvuploadmap" />
 4868: $upfile_select
 4869: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4870: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4871: </form>
 4872: ENDUPFORM
 4873:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4874:                            &mt("How do I create a CSV file from a spreadsheet")).
 4875:             '</td>'.
 4876:             &Apache::loncommon::end_data_table_row().
 4877:             &Apache::loncommon::end_data_table();
 4878:     return $result;
 4879: }
 4880: 
 4881: 
 4882: sub csvuploadmap {
 4883:     my ($request,$symb) = @_;
 4884:     if (!$symb) {return '';}
 4885: 
 4886:     my $datatoken;
 4887:     if (!$env{'form.datatoken'}) {
 4888: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4889:     } else {
 4890:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4891:         if ($datatoken ne '') { 
 4892: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4893:         }
 4894:     }
 4895:     my @records=&Apache::loncommon::upfile_record_sep();
 4896:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4897:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4898:     my ($i,$keyfields);
 4899:     if (@records) {
 4900:         my $fieldserror;
 4901: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4902:         if ($fieldserror) {
 4903:             $request->print(&navmap_errormsg());
 4904:             return;
 4905:         }
 4906: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4907: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4908: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4909: 							  \@fields);
 4910: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4911: 	    chop($keyfields);
 4912: 	} else {
 4913: 	    unshift(@fields,['none','']);
 4914: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4915: 							    \@fields);
 4916:             foreach my $rec (@records) {
 4917:                 my %temp = &Apache::loncommon::record_sep($rec);
 4918:                 if (%temp) {
 4919:                     $keyfields=join(',',sort(keys(%temp)));
 4920:                     last;
 4921:                 }
 4922:             }
 4923: 	}
 4924:     }
 4925:     &csvuploadmap_footer($request,$i,$keyfields);
 4926: 
 4927:     return '';
 4928: }
 4929: 
 4930: sub csvuploadoptions {
 4931:     my ($request,$symb)= @_;
 4932:     my $overwrite=&mt('Overwrite any existing score');
 4933:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4934:     my $ignore=&mt('Ignore First Line');
 4935:     $request->print(<<ENDPICK);
 4936: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4937: <input type="hidden" name="command"    value="csvuploadassign" />
 4938: <p>
 4939: <label>
 4940:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4941:    $overwrite
 4942: </label>
 4943: </p>
 4944: ENDPICK
 4945:     my %fields=&get_fields();
 4946:     if (!defined($fields{'domain'})) {
 4947: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4948:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4949:     }
 4950:     foreach my $key (sort(keys(%env))) {
 4951: 	if ($key !~ /^form\.(.*)$/) { next; }
 4952: 	my $cleankey=$1;
 4953: 	if ($cleankey eq 'command') { next; }
 4954: 	$request->print('<input type="hidden" name="'.$cleankey.
 4955: 			'"  value="'.$env{$key}.'" />'."\n");
 4956:     }
 4957:     # FIXME do a check for any duplicated user ids...
 4958:     # FIXME do a check for any invalid user ids?...
 4959:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4960: <hr /></form>'."\n");
 4961:     return '';
 4962: }
 4963: 
 4964: sub get_fields {
 4965:     my %fields;
 4966:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4967:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4968: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4969: 	    if ($env{'form.f'.$i} ne 'none') {
 4970: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4971: 	    }
 4972: 	} else {
 4973: 	    if ($env{'form.f'.$i} ne 'none') {
 4974: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4975: 	    }
 4976: 	}
 4977:     }
 4978:     return %fields;
 4979: }
 4980: 
 4981: sub csvuploadassign {
 4982:     my ($request,$symb) = @_;
 4983:     if (!$symb) {return '';}
 4984:     my $error_msg = '';
 4985:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4986:     if ($datatoken ne '') {
 4987:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4988:     }
 4989:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4990:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4991:     my %fields=&get_fields();
 4992:     my $courseid=$env{'request.course.id'};
 4993:     my ($classlist) = &getclasslist('all',0);
 4994:     my @notallowed;
 4995:     my @skipped;
 4996:     my @warnings;
 4997:     my $countdone=0;
 4998:     foreach my $grade (@gradedata) {
 4999: 	my %entries=&Apache::loncommon::record_sep($grade);
 5000: 	my $domain;
 5001: 	if ($entries{$fields{'domain'}}) {
 5002: 	    $domain=$entries{$fields{'domain'}};
 5003: 	} else {
 5004: 	    $domain=$env{'form.default_domain'};
 5005: 	}
 5006: 	$domain=~s/\s//g;
 5007: 	my $username=$entries{$fields{'username'}};
 5008: 	$username=~s/\s//g;
 5009: 	if (!$username) {
 5010: 	    my $id=$entries{$fields{'ID'}};
 5011: 	    $id=~s/\s//g;
 5012: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 5013: 	    $username=$ids{$id};
 5014: 	}
 5015: 	if (!exists($$classlist{"$username:$domain"})) {
 5016: 	    my $id=$entries{$fields{'ID'}};
 5017: 	    $id=~s/\s//g;
 5018: 	    if ($id) {
 5019: 		push(@skipped,"$id:$domain");
 5020: 	    } else {
 5021: 		push(@skipped,"$username:$domain");
 5022: 	    }
 5023: 	    next;
 5024: 	}
 5025: 	my $usec=$classlist->{"$username:$domain"}[5];
 5026: 	if (!&canmodify($usec)) {
 5027: 	    push(@notallowed,"$username:$domain");
 5028: 	    next;
 5029: 	}
 5030: 	my %points;
 5031: 	my %grades;
 5032: 	foreach my $dest (keys(%fields)) {
 5033: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5034: 		$dest eq 'domain') { next; }
 5035: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5036: 	    if ($dest=~/stores_(.*)_points/) {
 5037: 		my $part=$1;
 5038: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5039: 					      $symb,$domain,$username);
 5040:                 if ($wgt) {
 5041:                     $entries{$fields{$dest}}=~s/\s//g;
 5042:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5043:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5044:                                           : 'correct_by_override';
 5045:                     if ($pcr>1) {
 5046:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5047:                     }
 5048:                     $grades{"resource.$part.awarded"}=$pcr;
 5049:                     $grades{"resource.$part.solved"}=$award;
 5050:                     $points{$part}=1;
 5051:                 } else {
 5052:                     $error_msg = "<br />" .
 5053:                         &mt("Some point values were assigned"
 5054:                             ." for problems with a weight "
 5055:                             ."of zero. These values were "
 5056:                             ."ignored.");
 5057:                 }
 5058: 	    } else {
 5059: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5060: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5061: 		my $store_key=$dest;
 5062: 		$store_key=~s/^stores/resource/;
 5063: 		$store_key=~s/_/\./g;
 5064: 		$grades{$store_key}=$entries{$fields{$dest}};
 5065: 	    }
 5066: 	}
 5067: 	if (! %grades) {
 5068:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5069:         } else {
 5070: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5071: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5072: 					   $env{'request.course.id'},
 5073: 					   $domain,$username);
 5074: 	   if ($result eq 'ok') {
 5075: # Successfully stored
 5076: 	      $request->print('.');
 5077: # Remove from grading queue
 5078:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5079:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5080:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5081:                                              $domain,$username);
 5082: 	   } else {
 5083: 	      $request->print("<p><span class=\"LC_error\">".
 5084:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5085:                                   "$username:$domain",$result)."</span></p>");
 5086: 	   }
 5087: 	   $request->rflush();
 5088: 	   $countdone++;
 5089:         }
 5090:     }
 5091:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5092:     if (@warnings) {
 5093:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5094:         $request->print(join(', ',@warnings));
 5095:     }
 5096:     if (@skipped) {
 5097: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5098:         $request->print(join(', ',@skipped));
 5099:     }
 5100:     if (@notallowed) {
 5101: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5102: 	$request->print(join(', ',@notallowed));
 5103:     }
 5104:     $request->print("<br />\n");
 5105:     return $error_msg;
 5106: }
 5107: #------------- end of section for handling csv file upload ---------
 5108: #
 5109: #-------------------------------------------------------------------
 5110: #
 5111: #-------------- Next few routines handle grading by page/sequence
 5112: #
 5113: #--- Select a page/sequence and a student to grade
 5114: sub pickStudentPage {
 5115:     my ($request,$symb) = @_;
 5116: 
 5117:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5118:     &js_escape(\$alertmsg);
 5119:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5120: 
 5121: function checkPickOne(formname) {
 5122:     if (radioSelection(formname.student) == null) {
 5123: 	alert("$alertmsg");
 5124: 	return;
 5125:     }
 5126:     ptr = pullDownSelection(formname.selectpage);
 5127:     formname.page.value = formname["page"+ptr].value;
 5128:     formname.title.value = formname["title"+ptr].value;
 5129:     formname.submit();
 5130: }
 5131: 
 5132: LISTJAVASCRIPT
 5133:     &commonJSfunctions($request);
 5134: 
 5135:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5136:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5137:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5138:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5139: 
 5140:     my $result='<h3><span class="LC_info">&nbsp;'.
 5141: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5142: 
 5143:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5144:     my $map_error;
 5145:     my ($titles,$symbx) = &getSymbMap($map_error);
 5146:     if ($map_error) {
 5147:         $request->print(&navmap_errormsg());
 5148:         return; 
 5149:     }
 5150:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5151: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5152: #    my $type=($curpage =~ /\.(page|sequence)/);
 5153: 
 5154:     # Collection of hidden fields
 5155:     my $ctr=0;
 5156:     foreach (@$titles) {
 5157: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5158: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5159: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5160: 	$ctr++;
 5161:     }
 5162:     $result.='<input type="hidden" name="page" />'."\n".
 5163: 	'<input type="hidden" name="title" />'."\n";
 5164: 
 5165:     $result.=&build_section_inputs();
 5166:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5167:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5168:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5169:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5170: 
 5171:     # Show grading options
 5172:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5173:     my $select = '<select name="selectpage">'."\n";
 5174:     $ctr=0;
 5175:     foreach (@$titles) {
 5176:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5177:         $select.='<option value="'.$ctr.'"'.
 5178:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5179:             '>'.$showtitle.'</option>'."\n";
 5180:         $ctr++;
 5181:     }
 5182:     $select.= '</select>';
 5183: 
 5184:     $result.=
 5185:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5186:        .$select
 5187:        .&Apache::lonhtmlcommon::row_closure();
 5188: 
 5189:     $result.=
 5190:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5191:        .'<label><input type="radio" name="vProb" value="no"'
 5192:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5193:        .'<label><input type="radio" name="vProb" value="yes" />'
 5194:            .&mt('yes').'</label>'."\n"
 5195:        .&Apache::lonhtmlcommon::row_closure();
 5196: 
 5197:     $result.=
 5198:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5199:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5200:            .&mt('none').' </label>'."\n"
 5201:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5202:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5203:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5204:            .&mt('all submissions with details').' </label>'
 5205:        .&Apache::lonhtmlcommon::row_closure();
 5206: 
 5207:     $result.=
 5208:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5209:        .'<input type="text" name="CODE" value="" />'
 5210:        .&Apache::lonhtmlcommon::row_closure(1)
 5211:        .&Apache::lonhtmlcommon::end_pick_box();
 5212: 
 5213:     # Show list of students to select for grading
 5214:     $result.='<br /><input type="button" '.
 5215:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5216: 
 5217:     $request->print($result);
 5218: 
 5219:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5220: 	&Apache::loncommon::start_data_table().
 5221: 	&Apache::loncommon::start_data_table_header_row().
 5222: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5223: 	'<th>'.&nameUserString('header').'</th>'.
 5224: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5225: 	'<th>'.&nameUserString('header').'</th>'.
 5226: 	&Apache::loncommon::end_data_table_header_row();
 5227:  
 5228:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5229:     my $ptr = 1;
 5230:     foreach my $student (sort 
 5231: 			 {
 5232: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5233: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5234: 			     }
 5235: 			     return $a cmp $b;
 5236: 			 } (keys(%$fullname))) {
 5237: 	my ($uname,$udom) = split(/:/,$student);
 5238: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5239:                                   : '</td>');
 5240: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5241: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5242: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5243: 	$studentTable.=
 5244: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5245:                          : '');
 5246: 	$ptr++;
 5247:     }
 5248:     if ($ptr%2 == 0) {
 5249: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5250: 	    &Apache::loncommon::end_data_table_row();
 5251:     }
 5252:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5253:     $studentTable.='<input type="button" '.
 5254:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5255: 
 5256:     $request->print($studentTable);
 5257: 
 5258:     return '';
 5259: }
 5260: 
 5261: sub getSymbMap {
 5262:     my ($map_error) = @_;
 5263:     my $navmap = Apache::lonnavmaps::navmap->new();
 5264:     unless (ref($navmap)) {
 5265:         if (ref($map_error)) {
 5266:             $$map_error = 'navmap';
 5267:         }
 5268:         return;
 5269:     }
 5270:     my %symbx = ();
 5271:     my @titles = ();
 5272:     my $minder = 0;
 5273: 
 5274:     # Gather every sequence that has problems.
 5275:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5276: 					       1,0,1);
 5277:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5278: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5279: 	    my $title = $minder.'.'.
 5280: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5281: 	    push(@titles, $title); # minder in case two titles are identical
 5282: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5283: 	    $minder++;
 5284: 	}
 5285:     }
 5286:     return \@titles,\%symbx;
 5287: }
 5288: 
 5289: #
 5290: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5291: sub displayPage {
 5292:     my ($request,$symb) = @_;
 5293:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5294:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5295:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5296:     my $pageTitle = $env{'form.page'};
 5297:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5298:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5299:     my $usec=$classlist->{$env{'form.student'}}[5];
 5300: 
 5301:     #need to make sure we have the correct data for later EXT calls, 
 5302:     #thus invalidate the cache
 5303:     &Apache::lonnet::devalidatecourseresdata(
 5304:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5305:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5306:     &Apache::lonnet::clear_EXT_cache_status();
 5307: 
 5308:     if (!&canview($usec)) {
 5309: 	$request->print(
 5310:             '<span class="LC_warning">'.
 5311:             &mt('Unable to view requested student. ([_1])',
 5312:                 $env{'form.student'}).
 5313:             '</span>');
 5314:         return;
 5315:     }
 5316:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5317:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5318: 	'</h3>'."\n";
 5319:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5320:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5321: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5322:     } else {
 5323: 	delete($env{'form.CODE'});
 5324:     }
 5325:     &sub_page_js($request);
 5326:     $request->print($result);
 5327: 
 5328:     my $navmap = Apache::lonnavmaps::navmap->new();
 5329:     unless (ref($navmap)) {
 5330:         $request->print(&navmap_errormsg());
 5331:         return;
 5332:     }
 5333:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5334:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5335:     if (!$map) {
 5336: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5337: 	return; 
 5338:     }
 5339:     my $iterator = $navmap->getIterator($map->map_start(),
 5340: 					$map->map_finish());
 5341: 
 5342:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5343: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5344: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5345: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5346: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5347: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5348: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5349: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5350: 
 5351:     if (defined($env{'form.CODE'})) {
 5352: 	$studentTable.=
 5353: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5354:     }
 5355:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5356: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5357: 
 5358:     $studentTable.='&nbsp;<span class="LC_info">'.
 5359:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5360:         '</span>'."\n".
 5361: 	&Apache::loncommon::start_data_table().
 5362: 	&Apache::loncommon::start_data_table_header_row().
 5363: 	'<th>'.&mt('Prob.').'</th>'.
 5364: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5365: 	&Apache::loncommon::end_data_table_header_row();
 5366: 
 5367:     &Apache::lonxml::clear_problem_counter();
 5368:     my ($depth,$question,$prob) = (1,1,1);
 5369:     $iterator->next(); # skip the first BEGIN_MAP
 5370:     my $curRes = $iterator->next(); # for "current resource"
 5371:     while ($depth > 0) {
 5372:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5373:         if($curRes == $iterator->END_MAP) { $depth--; }
 5374: 
 5375:         if (ref($curRes) && $curRes->is_problem()) {
 5376: 	    my $parts = $curRes->parts();
 5377:             my $title = $curRes->compTitle();
 5378: 	    my $symbx = $curRes->symb();
 5379: 	    $studentTable.=
 5380: 		&Apache::loncommon::start_data_table_row().
 5381: 		'<td align="center" valign="top" >'.$prob.
 5382: 		(scalar(@{$parts}) == 1 ? '' 
 5383: 		                        : '<br />('.&mt('[_1]parts',
 5384: 							scalar(@{$parts}).'&nbsp;').')'
 5385: 		 ).
 5386: 		 '</td>';
 5387: 	    $studentTable.='<td valign="top">';
 5388: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5389: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5390: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5391: 					     undef,'both',\%form);
 5392: 	    } else {
 5393: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5394: 		$companswer =~ s|<form(.*?)>||g;
 5395: 		$companswer =~ s|</form>||g;
 5396: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5397: #		    $companswer =~ s/$1/ /ms;
 5398: #		    $request->print('match='.$1."<br />\n");
 5399: #		}
 5400: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5401: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5402: 	    }
 5403: 
 5404: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5405: 
 5406: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5407: 		if ($record{'version'} eq '') {
 5408: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5409: 		} else {
 5410: 		    my %responseType = ();
 5411: 		    foreach my $partid (@{$parts}) {
 5412: 			my @responseIds =$curRes->responseIds($partid);
 5413: 			my @responseType =$curRes->responseType($partid);
 5414: 			my %responseIds;
 5415: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5416: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5417: 			}
 5418: 			$responseType{$partid} = \%responseIds;
 5419: 		    }
 5420: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5421: 
 5422: 		}
 5423: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5424: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5425:                 my $identifier = (&canmodify($usec)? $prob : '');
 5426: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5427: 									$env{'request.course.id'},
 5428: 									'','.submission',undef,
 5429:                                                                         $usec,$identifier);
 5430:  
 5431: 	    }
 5432: 	    if (&canmodify($usec)) {
 5433:             $studentTable.=&gradeBox_start();
 5434: 		foreach my $partid (@{$parts}) {
 5435: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5436: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5437: 		    $question++;
 5438: 		}
 5439:             $studentTable.=&gradeBox_end();
 5440: 		$prob++;
 5441: 	    }
 5442: 	    $studentTable.='</td></tr>';
 5443: 
 5444: 	}
 5445:         $curRes = $iterator->next();
 5446:     }
 5447:     my $disabled;
 5448:     unless (&canmodify($usec)) {
 5449:         $disabled = ' disabled="disabled"';
 5450:     }
 5451: 
 5452:     $studentTable.=
 5453:         '</table>'."\n".
 5454:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5455:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5456:         '</form>'."\n";
 5457:     $request->print($studentTable);
 5458: 
 5459:     return '';
 5460: }
 5461: 
 5462: sub displaySubByDates {
 5463:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5464:     my $isCODE=0;
 5465:     my $isTask = ($symb =~/\.task$/);
 5466:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5467:     my $studentTable=&Apache::loncommon::start_data_table().
 5468: 	&Apache::loncommon::start_data_table_header_row().
 5469: 	'<th>'.&mt('Date/Time').'</th>'.
 5470: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5471:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5472: 	'<th>'.&mt('Submission').'</th>'.
 5473: 	'<th>'.&mt('Status').'</th>'.
 5474: 	&Apache::loncommon::end_data_table_header_row();
 5475:     my ($version);
 5476:     my %mark;
 5477:     my %orders;
 5478:     $mark{'correct_by_student'} = $checkIcon;
 5479:     if (!exists($$record{'1:timestamp'})) {
 5480: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5481:     }
 5482: 
 5483:     my $interaction;
 5484:     my $no_increment = 1;
 5485:     my (%lastrndseed,%lasttype);
 5486:     for ($version=1;$version<=$$record{'version'};$version++) {
 5487: 	my $timestamp = 
 5488: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5489: 	if (exists($$record{$version.':resource.0.version'})) {
 5490: 	    $interaction = $$record{$version.':resource.0.version'};
 5491: 	}
 5492:         if ($isTask && $env{'form.previousversion'}) {
 5493:             next unless ($interaction == $env{'form.previousversion'});
 5494:         }
 5495: 	my $where = ($isTask ? "$version:resource.$interaction"
 5496: 		             : "$version:resource");
 5497: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5498: 	    '<td>'.$timestamp.'</td>';
 5499: 	if ($isCODE) {
 5500: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5501: 	}
 5502:         if ($isTask) {
 5503:             $studentTable.='<td>'.$interaction.'</td>';
 5504:         }
 5505: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5506: 	my @displaySub = ();
 5507: 	foreach my $partid (@{$parts}) {
 5508:             my ($hidden,$type);
 5509:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5510:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5511:                 $hidden = 1;
 5512:             }
 5513: 	    my @matchKey;
 5514:             if ($isTask) {
 5515:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5516:             } else {
 5517: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5518:             }
 5519: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5520: 	    my $display_part=&get_display_part($partid,$symb);
 5521: 	    foreach my $matchKey (@matchKey) {
 5522: 		if (exists($$record{$version.':'.$matchKey}) &&
 5523: 		    $$record{$version.':'.$matchKey} ne '') {
 5524:                     
 5525: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5526: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5527:                     $displaySub[0].='<span class="LC_nobreak">';
 5528:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5529:                                    .' <span class="LC_internal_info">'
 5530:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5531:                                    .'</span>'
 5532:                                    .' <b>';
 5533:                     if ($hidden) {
 5534:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5535:                     } else {
 5536:                         my ($trial,$rndseed,$newvariation);
 5537:                         if ($type eq 'randomizetry') {
 5538:                             $trial = $$record{"$where.$partid.tries"};
 5539:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5540:                         }
 5541: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5542: 			    $displaySub[0].=&mt('Trial not counted');
 5543: 		        } else {
 5544: 			    $displaySub[0].=&mt('Trial: [_1]',
 5545: 					    $$record{"$where.$partid.tries"});
 5546:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5547:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5548:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5549:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5550:                                 }
 5551:                             }
 5552:                             $lastrndseed{$partid} = $rndseed;
 5553:                             $lasttype{$partid} = $type;
 5554: 		        }
 5555: 		        my $responseType=($isTask ? 'Task'
 5556:                                               : $responseType->{$partid}->{$responseId});
 5557: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5558: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5559: 			    $orders{$partid}->{$responseId}=
 5560: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5561:                                            $no_increment,$type,$trial,$rndseed);
 5562: 		        }
 5563: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5564: 		        $displaySub[0].='&nbsp; '.
 5565: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5566:                     }
 5567: 		}
 5568: 	    }
 5569: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5570: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5571: 				    $$record{"$where.$partid.checkedin"},
 5572: 				    $$record{"$where.$partid.checkedin.slot"}).
 5573: 					'<br />';
 5574: 	    }
 5575: 	    if (exists $$record{"$where.$partid.award"}) {
 5576: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5577: 		    lc($$record{"$where.$partid.award"}).' '.
 5578: 		    $mark{$$record{"$where.$partid.solved"}}.
 5579: 		    '<br />';
 5580: 	    }
 5581: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5582: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5583: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5584: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5585: 		$displaySub[2].=
 5586: 		    $$record{"$version:resource.$partid.regrader"}.
 5587: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5588: 	    }
 5589: 	}
 5590: 	# needed because old essay regrader has not parts info
 5591: 	if (exists $$record{"$version:resource.regrader"}) {
 5592: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5593: 	}
 5594: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5595: 	if ($displaySub[2]) {
 5596: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5597: 	}
 5598: 	$studentTable.='&nbsp;</td>'.
 5599: 	    &Apache::loncommon::end_data_table_row();
 5600:     }
 5601:     $studentTable.=&Apache::loncommon::end_data_table();
 5602:     return $studentTable;
 5603: }
 5604: 
 5605: sub updateGradeByPage {
 5606:     my ($request,$symb) = @_;
 5607: 
 5608:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5609:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5610:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5611:     my $pageTitle = $env{'form.page'};
 5612:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5613:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5614:     my $usec=$classlist->{$env{'form.student'}}[5];
 5615:     if (!&canmodify($usec)) {
 5616: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5617: 	return;
 5618:     }
 5619:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5620:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5621: 	'</h3>'."\n";
 5622: 
 5623:     $request->print($result);
 5624: 
 5625: 
 5626:     my $navmap = Apache::lonnavmaps::navmap->new();
 5627:     unless (ref($navmap)) {
 5628:         $request->print(&navmap_errormsg());
 5629:         return;
 5630:     }
 5631:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5632:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5633:     if (!$map) {
 5634: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5635: 	return; 
 5636:     }
 5637:     my $iterator = $navmap->getIterator($map->map_start(),
 5638: 					$map->map_finish());
 5639: 
 5640:     my $studentTable=
 5641: 	&Apache::loncommon::start_data_table().
 5642: 	&Apache::loncommon::start_data_table_header_row().
 5643: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5644: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5645: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5646: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5647: 	&Apache::loncommon::end_data_table_header_row();
 5648: 
 5649:     $iterator->next(); # skip the first BEGIN_MAP
 5650:     my $curRes = $iterator->next(); # for "current resource"
 5651:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5652:     while ($depth > 0) {
 5653:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5654:         if($curRes == $iterator->END_MAP) { $depth--; }
 5655: 
 5656:         if (ref($curRes) && $curRes->is_problem()) {
 5657: 	    my $parts = $curRes->parts();
 5658:             my $title = $curRes->compTitle();
 5659: 	    my $symbx = $curRes->symb();
 5660: 	    $studentTable.=
 5661: 		&Apache::loncommon::start_data_table_row().
 5662: 		'<td align="center" valign="top" >'.$prob.
 5663: 		(scalar(@{$parts}) == 1 ? '' 
 5664:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5665: 		.')').'</td>';
 5666: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5667: 
 5668: 	    my %newrecord=();
 5669: 	    my @displayPts=();
 5670:             my %aggregate = ();
 5671:             my $aggregateflag = 0;
 5672:             if ($env{'form.HIDE'.$prob}) {
 5673:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5674:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5675:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5676:                 $hideflag += $numchgs;
 5677:             }
 5678: 	    foreach my $partid (@{$parts}) {
 5679: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5680: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5681:                 my @types = $curRes->responseType($part);
 5682:                 if (grep(/^essay$/,@types)) {
 5683:                     $queueable{$partid} = 1;
 5684:                 } else {
 5685:                     my @ids = $curRes->responseIds($part);
 5686:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5687:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
 5688:                                                           '.handgrade',$symb);
 5689:                         if (lc($hndgrd) eq 'yes') {
 5690:                             $queueable{$partid} = 1;
 5691:                             last;
 5692:                         }
 5693:                     }
 5694:                 }
 5695: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5696: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5697: 		my $partial = $newpts/$wgt;
 5698: 		my $score;
 5699: 		if ($partial > 0) {
 5700: 		    $score = 'correct_by_override';
 5701: 		} elsif ($newpts ne '') { #empty is taken as 0
 5702: 		    $score = 'incorrect_by_override';
 5703: 		}
 5704: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5705: 		if ($dropMenu eq 'excused') {
 5706: 		    $partial = '';
 5707: 		    $score = 'excused';
 5708: 		} elsif ($dropMenu eq 'reset status'
 5709: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5710: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5711: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5712: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5713: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5714: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5715: 		    $changeflag++;
 5716: 		    $newpts = '';
 5717:                     
 5718:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5719:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5720:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5721:                     if ($aggtries > 0) {
 5722:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5723:                         $aggregateflag = 1;
 5724:                     }
 5725: 		}
 5726: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5727: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5728: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5729: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5730: 		    '&nbsp;<br />';
 5731: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5732: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5733: 		    '&nbsp;<br />';
 5734: 		$question++;
 5735: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5736: 
 5737: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5738: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5739: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5740: 		    if (scalar(keys(%newrecord)) > 0);
 5741: 
 5742: 		$changeflag++;
 5743: 	    }
 5744: 	    if (scalar(keys(%newrecord)) > 0) {
 5745: 		my %record = 
 5746: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5747: 					     $udom,$uname);
 5748: 
 5749: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5750: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5751: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5752: 		    $newrecord{'resource.CODE'} = '';
 5753: 		}
 5754: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5755: 					$udom,$uname);
 5756: 		%record = &Apache::lonnet::restore($symbx,
 5757: 						   $env{'request.course.id'},
 5758: 						   $udom,$uname);
 5759: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5760: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5761: 	    }
 5762: 	    
 5763:             if ($aggregateflag) {
 5764:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5765:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5766:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5767:             }
 5768: 
 5769: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5770: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5771: 		&Apache::loncommon::end_data_table_row();
 5772: 
 5773: 	    $prob++;
 5774: 	}
 5775:         $curRes = $iterator->next();
 5776:     }
 5777: 
 5778:     $studentTable.=&Apache::loncommon::end_data_table();
 5779:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5780: 		  &mt('The scores were changed for [quant,_1,problem].',
 5781: 		  $changeflag).'<br />');
 5782:     my $hidemsg=($hideflag == 0 ? '' :
 5783:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5784:                      $hideflag).'<br />');
 5785:     $request->print($hidemsg.$grademsg.$studentTable);
 5786: 
 5787:     return '';
 5788: }
 5789: 
 5790: #-------- end of section for handling grading by page/sequence ---------
 5791: #
 5792: #-------------------------------------------------------------------
 5793: 
 5794: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5795: #
 5796: #------ start of section for handling grading by page/sequence ---------
 5797: 
 5798: =pod
 5799: 
 5800: =head1 Bubble sheet grading routines
 5801: 
 5802:   For this documentation:
 5803: 
 5804:    'scanline' refers to the full line of characters
 5805:    from the file that we are parsing that represents one entire sheet
 5806: 
 5807:    'bubble line' refers to the data
 5808:    representing the line of bubbles that are on the physical bubblesheet
 5809: 
 5810: 
 5811: The overall process is that a scanned in bubblesheet data is uploaded
 5812: into a course. When a user wants to grade, they select a
 5813: sequence/folder of resources, a file of bubblesheet info, and pick
 5814: one of the predefined configurations for what each scanline looks
 5815: like.
 5816: 
 5817: Next each scanline is checked for any errors of either 'missing
 5818: bubbles' (it's an error because it may have been mis-scanned
 5819: because too light bubbling), 'double bubble' (each bubble line should
 5820: have no more than one letter picked), invalid or duplicated CODE,
 5821: invalid student/employee ID
 5822: 
 5823: If the CODE option is used that determines the randomization of the
 5824: homework problems, either way the student/employee ID is looked up into a
 5825: username:domain.
 5826: 
 5827: During the validation phase the instructor can choose to skip scanlines. 
 5828: 
 5829: After the validation phase, there are now 3 bubblesheet files
 5830: 
 5831:   scantron_original_filename (unmodified original file)
 5832:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5833:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5834: 
 5835: Also there is a separate hash nohist_scantrondata that contains extra
 5836: correction information that isn't representable in the bubblesheet
 5837: file (see &scantron_getfile() for more information)
 5838: 
 5839: After all scanlines are either valid, marked as valid or skipped, then
 5840: foreach line foreach problem in the picked sequence, an ssi request is
 5841: made that simulates a user submitting their selected letter(s) against
 5842: the homework problem.
 5843: 
 5844: =over 4
 5845: 
 5846: 
 5847: 
 5848: =item defaultFormData
 5849: 
 5850:   Returns html hidden inputs used to hold context/default values.
 5851: 
 5852:  Arguments:
 5853:   $symb - $symb of the current resource 
 5854: 
 5855: =cut
 5856: 
 5857: sub defaultFormData {
 5858:     my ($symb)=@_;
 5859:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5860: }
 5861: 
 5862: 
 5863: =pod 
 5864: 
 5865: =item getSequenceDropDown
 5866: 
 5867:    Return html dropdown of possible sequences to grade
 5868:  
 5869:  Arguments:
 5870:    $symb - $symb of the current resource
 5871:    $map_error - ref to scalar which will container error if
 5872:                 $navmap object is unavailable in &getSymbMap().
 5873: 
 5874: =cut
 5875: 
 5876: sub getSequenceDropDown {
 5877:     my ($symb,$map_error)=@_;
 5878:     my $result='<select name="selectpage">'."\n";
 5879:     my ($titles,$symbx) = &getSymbMap($map_error);
 5880:     if (ref($map_error)) {
 5881:         return if ($$map_error);
 5882:     }
 5883:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5884:     my $ctr=0;
 5885:     foreach (@$titles) {
 5886: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5887: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5888: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5889: 	    '>'.$showtitle.'</option>'."\n";
 5890: 	$ctr++;
 5891:     }
 5892:     $result.= '</select>';
 5893:     return $result;
 5894: }
 5895: 
 5896: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5897:                                    # key is zero-based index - 0, 1, 2 ...
 5898: 
 5899: my %first_bubble_line;             # First bubble line no. for each bubble.
 5900: 
 5901: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5902:                                    # matchresponse or rankresponse, where 
 5903:                                    # an individual response can have multiple 
 5904:                                    # lines
 5905: 
 5906: my %responsetype_per_response;     # responsetype for each response
 5907: 
 5908: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5909:                                    # numbered response. Needed when randomorder
 5910:                                    # or randompick are in use. Key is ID, value 
 5911:                                    # is response number.
 5912: 
 5913: # Save and restore the bubble lines array to the form env.
 5914: 
 5915: 
 5916: sub save_bubble_lines {
 5917:     foreach my $line (keys(%bubble_lines_per_response)) {
 5918: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5919: 	$env{"form.scantron.first_bubble_line.$line"} =
 5920: 	    $first_bubble_line{$line};
 5921:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5922:             $subdivided_bubble_lines{$line};
 5923:         $env{"form.scantron.responsetype.$line"} =
 5924:             $responsetype_per_response{$line};
 5925:     }
 5926:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5927:         my $line = $masterseq_id_responsenum{$resid};
 5928:         $env{"form.scantron.residpart.$line"} = $resid;
 5929:     }
 5930: }
 5931: 
 5932: 
 5933: sub restore_bubble_lines {
 5934:     my $line = 0;
 5935:     %bubble_lines_per_response = ();
 5936:     %masterseq_id_responsenum = ();
 5937:     while ($env{"form.scantron.bubblelines.$line"}) {
 5938: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5939: 	$bubble_lines_per_response{$line} = $value;
 5940: 	$first_bubble_line{$line}  =
 5941: 	    $env{"form.scantron.first_bubble_line.$line"};
 5942:         $subdivided_bubble_lines{$line} =
 5943:             $env{"form.scantron.sub_bubblelines.$line"};
 5944:         $responsetype_per_response{$line} =
 5945:             $env{"form.scantron.responsetype.$line"};
 5946:         my $id = $env{"form.scantron.residpart.$line"};
 5947:         $masterseq_id_responsenum{$id} = $line;
 5948: 	$line++;
 5949:     }
 5950: }
 5951: 
 5952: =pod 
 5953: 
 5954: =item scantron_filenames
 5955: 
 5956:    Returns a list of the scantron files in the current course 
 5957: 
 5958: =cut
 5959: 
 5960: sub scantron_filenames {
 5961:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5962:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5963:     my $getpropath = 1;
 5964:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5965:                                                         $cname,$getpropath);
 5966:     my @possiblenames;
 5967:     if (ref($dirlist) eq 'ARRAY') {
 5968:         foreach my $filename (sort(@{$dirlist})) {
 5969: 	    ($filename)=split(/&/,$filename);
 5970: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5971: 	    $filename=~s/^scantron_orig_//;
 5972: 	    push(@possiblenames,$filename);
 5973:         }
 5974:     }
 5975:     return @possiblenames;
 5976: }
 5977: 
 5978: =pod 
 5979: 
 5980: =item scantron_uploads
 5981: 
 5982:    Returns  html drop-down list of scantron files in current course.
 5983: 
 5984:  Arguments:
 5985:    $file2grade - filename to set as selected in the dropdown
 5986: 
 5987: =cut
 5988: 
 5989: sub scantron_uploads {
 5990:     my ($file2grade) = @_;
 5991:     my $result=	'<select name="scantron_selectfile">';
 5992:     $result.="<option></option>";
 5993:     foreach my $filename (sort(&scantron_filenames())) {
 5994: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5995:     }
 5996:     $result.="</select>";
 5997:     return $result;
 5998: }
 5999: 
 6000: =pod 
 6001: 
 6002: =item scantron_scantab
 6003: 
 6004:   Returns html drop down of the scantron formats in the scantronformat.tab
 6005:   file.
 6006: 
 6007: =cut
 6008: 
 6009: sub scantron_scantab {
 6010:     my $result='<select name="scantron_format">'."\n";
 6011:     $result.='<option></option>'."\n";
 6012:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6013:     if (@lines > 0) {
 6014:         foreach my $line (@lines) {
 6015:             next if (($line =~ /^\#/) || ($line eq ''));
 6016: 	    my ($name,$descrip)=split(/:/,$line);
 6017: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6018:         }
 6019:     }
 6020:     $result.='</select>'."\n";
 6021:     return $result;
 6022: }
 6023: 
 6024: =pod 
 6025: 
 6026: =item scantron_CODElist
 6027: 
 6028:   Returns html drop down of the saved CODE lists from current course,
 6029:   generated from earlier printings.
 6030: 
 6031: =cut
 6032: 
 6033: sub scantron_CODElist {
 6034:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6035:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6036:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6037:     my $namechoice='<option></option>';
 6038:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6039: 	if ($name =~ /^error: 2 /) { next; }
 6040: 	if ($name =~ /^type\0/) { next; }
 6041: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6042:     }
 6043:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6044:     return $namechoice;
 6045: }
 6046: 
 6047: =pod 
 6048: 
 6049: =item scantron_CODEunique
 6050: 
 6051:   Returns the html for "Each CODE to be used once" radio.
 6052: 
 6053: =cut
 6054: 
 6055: sub scantron_CODEunique {
 6056:     my $result='<span class="LC_nobreak">
 6057:                  <label><input type="radio" name="scantron_CODEunique"
 6058:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6059:                 </span>
 6060:                 <span class="LC_nobreak">
 6061:                  <label><input type="radio" name="scantron_CODEunique"
 6062:                         value="no" />'.&mt('No').' </label>
 6063:                 </span>';
 6064:     return $result;
 6065: }
 6066: 
 6067: =pod 
 6068: 
 6069: =item scantron_selectphase
 6070: 
 6071:   Generates the initial screen to start the bubblesheet process.
 6072:   Allows for - starting a grading run.
 6073:              - downloading existing scan data (original, corrected
 6074:                                                 or skipped info)
 6075: 
 6076:              - uploading new scan data
 6077: 
 6078:  Arguments:
 6079:   $r          - The Apache request object
 6080:   $file2grade - name of the file that contain the scanned data to score
 6081: 
 6082: =cut
 6083: 
 6084: sub scantron_selectphase {
 6085:     my ($r,$file2grade,$symb) = @_;
 6086:     if (!$symb) {return '';}
 6087:     my $map_error;
 6088:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6089:     if ($map_error) {
 6090:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6091:         return;
 6092:     }
 6093:     my $default_form_data=&defaultFormData($symb);
 6094:     my $file_selector=&scantron_uploads($file2grade);
 6095:     my $format_selector=&scantron_scantab();
 6096:     my $CODE_selector=&scantron_CODElist();
 6097:     my $CODE_unique=&scantron_CODEunique();
 6098:     my $result;
 6099: 
 6100:     $ssi_error = 0;
 6101: 
 6102:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6103:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6104: 
 6105:         # Chunk of form to prompt for a scantron file upload.
 6106: 
 6107:         $r->print('
 6108:     <br />');
 6109:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6110:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6111:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6112:         &js_escape(\$alertmsg);
 6113:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6114:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6115:     function checkUpload(formname) {
 6116:         if (formname.upfile.value == "") {
 6117:             alert("'.$alertmsg.'");
 6118:             return false;
 6119:         }
 6120:         formname.submit();
 6121:     }'."\n".$formatjs));
 6122:         $r->print('
 6123:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6124:                 '.$default_form_data.'
 6125:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6126:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6127:                 <input name="command" value="scantronupload_save" type="hidden" />
 6128:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6129:               '.&Apache::loncommon::start_data_table_header_row().'
 6130:                 <th>
 6131:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6132:                 </th>
 6133:               '.&Apache::loncommon::end_data_table_header_row().'
 6134:               '.&Apache::loncommon::start_data_table_row().'
 6135:             <td>
 6136:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6137:         if ($formatoptions) {
 6138:             $r->print('</td>
 6139:                  '.&Apache::loncommon::end_data_table_row().'
 6140:                  '.&Apache::loncommon::start_data_table_row().'
 6141:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6142:                  </td>
 6143:                  '.&Apache::loncommon::end_data_table_row().'
 6144:                  '.&Apache::loncommon::start_data_table_row().'
 6145:                  <td>'
 6146:             );
 6147:         } else {
 6148:             $r->print(' <br />');
 6149:         }
 6150:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6151:               </td>
 6152:              '.&Apache::loncommon::end_data_table_row().'
 6153:              '.&Apache::loncommon::end_data_table().'
 6154:              </form>'
 6155:         );
 6156: 
 6157:     }
 6158: 
 6159:     # Chunk of form to prompt for a file to grade and how:
 6160: 
 6161:     $result.= '
 6162:     <br />
 6163:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6164:     <input type="hidden" name="command" value="scantron_warning" />
 6165:     '.$default_form_data.'
 6166:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6167:        '.&Apache::loncommon::start_data_table_header_row().'
 6168:             <th colspan="2">
 6169:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6170:             </th>
 6171:        '.&Apache::loncommon::end_data_table_header_row().'
 6172:        '.&Apache::loncommon::start_data_table_row().'
 6173:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6174:        '.&Apache::loncommon::end_data_table_row().'
 6175:        '.&Apache::loncommon::start_data_table_row().'
 6176:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6177:        '.&Apache::loncommon::end_data_table_row().'
 6178:        '.&Apache::loncommon::start_data_table_row().'
 6179:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6180:        '.&Apache::loncommon::end_data_table_row().'
 6181:        '.&Apache::loncommon::start_data_table_row().'
 6182:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6183:        '.&Apache::loncommon::end_data_table_row().'
 6184:        '.&Apache::loncommon::start_data_table_row().'
 6185:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6186:        '.&Apache::loncommon::end_data_table_row().'
 6187:        '.&Apache::loncommon::start_data_table_row().'
 6188: 	    <td> '.&mt('Options:').' </td>
 6189:             <td>
 6190: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6191:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6192:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6193: 	    </td>
 6194:        '.&Apache::loncommon::end_data_table_row().'
 6195:        '.&Apache::loncommon::start_data_table_row().'
 6196:             <td colspan="2">
 6197:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6198:             </td>
 6199:        '.&Apache::loncommon::end_data_table_row().'
 6200:     '.&Apache::loncommon::end_data_table().'
 6201:     </form>
 6202: ';
 6203:    
 6204:     $r->print($result);
 6205: 
 6206:     # Chunk of the form that prompts to view a scoring office file,
 6207:     # corrected file, skipped records in a file.
 6208: 
 6209:     $r->print('
 6210:    <br />
 6211:    <form action="/adm/grades" name="scantron_download">
 6212:      '.$default_form_data.'
 6213:      <input type="hidden" name="command" value="scantron_download" />
 6214:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6215:        '.&Apache::loncommon::start_data_table_header_row().'
 6216:               <th>
 6217:                 &nbsp;'.&mt('Download a scoring office file').'
 6218:               </th>
 6219:        '.&Apache::loncommon::end_data_table_header_row().'
 6220:        '.&Apache::loncommon::start_data_table_row().'
 6221:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6222:                 <br />
 6223:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6224:        '.&Apache::loncommon::end_data_table_row().'
 6225:      '.&Apache::loncommon::end_data_table().'
 6226:    </form>
 6227:    <br />
 6228: ');
 6229: 
 6230:     &Apache::lonpickcode::code_list($r,2);
 6231: 
 6232:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6233:              $default_form_data."\n".
 6234:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6235:              &Apache::loncommon::start_data_table_header_row()."\n".
 6236:              '<th colspan="2">
 6237:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6238:              '</th>'."\n".
 6239:               &Apache::loncommon::end_data_table_header_row()."\n".
 6240:               &Apache::loncommon::start_data_table_row()."\n".
 6241:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6242:               '<td> '.$sequence_selector.' </td>'.
 6243:               &Apache::loncommon::end_data_table_row()."\n".
 6244:               &Apache::loncommon::start_data_table_row()."\n".
 6245:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6246:               '<td> '.$file_selector.' </td>'."\n".
 6247:               &Apache::loncommon::end_data_table_row()."\n".
 6248:               &Apache::loncommon::start_data_table_row()."\n".
 6249:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6250:               '<td> '.$format_selector.' </td>'."\n".
 6251:               &Apache::loncommon::end_data_table_row()."\n".
 6252:               &Apache::loncommon::start_data_table_row()."\n".
 6253:               '<td> '.&mt('Options').' </td>'."\n".
 6254:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6255:               &Apache::loncommon::end_data_table_row()."\n".
 6256:               &Apache::loncommon::start_data_table_row()."\n".
 6257:               '<td colspan="2">'."\n".
 6258:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6259:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6260:               '</td>'."\n".
 6261:               &Apache::loncommon::end_data_table_row()."\n".
 6262:               &Apache::loncommon::end_data_table()."\n".
 6263:               '</form><br />');
 6264:     return;
 6265: }
 6266: 
 6267: =pod 
 6268: 
 6269: =item username_to_idmap
 6270: 
 6271:     creates a hash keyed by student/employee ID with values of the corresponding
 6272:     student username:domain.
 6273: 
 6274:   Arguments:
 6275: 
 6276:     $classlist - reference to the class list hash. This is a hash
 6277:                  keyed by student name:domain  whose elements are references
 6278:                  to arrays containing various chunks of information
 6279:                  about the student. (See loncoursedata for more info).
 6280: 
 6281:   Returns
 6282:     %idmap - the constructed hash
 6283: 
 6284: =cut
 6285: 
 6286: sub username_to_idmap {
 6287:     my ($classlist)= @_;
 6288:     my %idmap;
 6289:     foreach my $student (keys(%$classlist)) {
 6290:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6291:         unless ($id eq '') {
 6292:             if (!exists($idmap{$id})) {
 6293:                 $idmap{$id} = $student;
 6294:             } else {
 6295:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6296:                 if ($status eq 'Active') {
 6297:                     $idmap{$id} = $student;
 6298:                 }
 6299:             }
 6300:         }
 6301:     }
 6302:     return %idmap;
 6303: }
 6304: 
 6305: =pod
 6306: 
 6307: =item scantron_fixup_scanline
 6308: 
 6309:    Process a requested correction to a scanline.
 6310: 
 6311:   Arguments:
 6312:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6313:     $scan_data         - hash of correction information 
 6314:                           (see &scantron_getfile())
 6315:     $line              - existing scanline
 6316:     $whichline         - line number of the passed in scanline
 6317:     $field             - type of change to process 
 6318:                          (either 
 6319:                           'ID'     -> correct the student/employee ID
 6320:                           'CODE'   -> correct the CODE
 6321:                           'answer' -> fixup the submitted answers)
 6322:     
 6323:    $args               - hash of additional info,
 6324:                           - 'ID' 
 6325:                                'newid' -> studentID to use in replacement
 6326:                                           of existing one
 6327:                           - 'CODE' 
 6328:                                'CODE_ignore_dup' - set to true if duplicates
 6329:                                                    should be ignored.
 6330: 	                       'CODE' - is new code or 'use_unfound'
 6331:                                         if the existing unfound code should
 6332:                                         be used as is
 6333:                           - 'answer'
 6334:                                'response' - new answer or 'none' if blank
 6335:                                'question' - the bubble line to change
 6336:                                'questionnum' - the question identifier,
 6337:                                                may include subquestion. 
 6338: 
 6339:   Returns:
 6340:     $line - the modified scanline
 6341: 
 6342:   Side effects: 
 6343:     $scan_data - may be updated
 6344: 
 6345: =cut
 6346: 
 6347: 
 6348: sub scantron_fixup_scanline {
 6349:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6350:     if ($field eq 'ID') {
 6351: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6352: 	    return ($line,1,'New value too large');
 6353: 	}
 6354: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6355: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6356: 				     $args->{'newid'});
 6357: 	}
 6358: 	substr($line,$$scantron_config{'IDstart'}-1,
 6359: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6360: 	if ($args->{'newid'}=~/^\s*$/) {
 6361: 	    &scan_data($scan_data,"$whichline.user",
 6362: 		       $args->{'username'}.':'.$args->{'domain'});
 6363: 	}
 6364:     } elsif ($field eq 'CODE') {
 6365: 	if ($args->{'CODE_ignore_dup'}) {
 6366: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6367: 	}
 6368: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6369: 	if ($args->{'CODE'} ne 'use_unfound') {
 6370: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6371: 		return ($line,1,'New CODE value too large');
 6372: 	    }
 6373: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6374: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6375: 	    }
 6376: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6377: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6378: 	}
 6379:     } elsif ($field eq 'answer') {
 6380: 	my $length=$scantron_config->{'Qlength'};
 6381: 	my $off=$scantron_config->{'Qoff'};
 6382: 	my $on=$scantron_config->{'Qon'};
 6383: 	my $answer=${off}x$length;
 6384: 	if ($args->{'response'} eq 'none') {
 6385: 	    &scan_data($scan_data,
 6386: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6387: 	} else {
 6388: 	    if ($on eq 'letter') {
 6389: 		my @alphabet=('A'..'Z');
 6390: 		$answer=$alphabet[$args->{'response'}];
 6391: 	    } elsif ($on eq 'number') {
 6392: 		$answer=$args->{'response'}+1;
 6393: 		if ($answer == 10) { $answer = '0'; }
 6394: 	    } else {
 6395: 		substr($answer,$args->{'response'},1)=$on;
 6396: 	    }
 6397: 	    &scan_data($scan_data,
 6398: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6399: 	}
 6400: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6401: 	substr($line,$where-1,$length)=$answer;
 6402:     }
 6403:     return $line;
 6404: }
 6405: 
 6406: =pod
 6407: 
 6408: =item scan_data
 6409: 
 6410:     Edit or look up  an item in the scan_data hash.
 6411: 
 6412:   Arguments:
 6413:     $scan_data  - The hash (see scantron_getfile)
 6414:     $key        - shorthand of the key to edit (actual key is
 6415:                   scantronfilename_key).
 6416:     $data        - New value of the hash entry.
 6417:     $delete      - If true, the entry is removed from the hash.
 6418: 
 6419:   Returns:
 6420:     The new value of the hash table field (undefined if deleted).
 6421: 
 6422: =cut
 6423: 
 6424: 
 6425: sub scan_data {
 6426:     my ($scan_data,$key,$value,$delete)=@_;
 6427:     my $filename=$env{'form.scantron_selectfile'};
 6428:     if (defined($value)) {
 6429: 	$scan_data->{$filename.'_'.$key} = $value;
 6430:     }
 6431:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6432:     return $scan_data->{$filename.'_'.$key};
 6433: }
 6434: 
 6435: # ----- These first few routines are general use routines.----
 6436: 
 6437: # Return the number of occurences of a pattern in a string.
 6438: 
 6439: sub occurence_count {
 6440:     my ($string, $pattern) = @_;
 6441: 
 6442:     my @matches = ($string =~ /$pattern/g);
 6443: 
 6444:     return scalar(@matches);
 6445: }
 6446: 
 6447: 
 6448: # Take a string known to have digits and convert all the
 6449: # digits into letters in the range J,A..I.
 6450: 
 6451: sub digits_to_letters {
 6452:     my ($input) = @_;
 6453: 
 6454:     my @alphabet = ('J', 'A'..'I');
 6455: 
 6456:     my @input    = split(//, $input);
 6457:     my $output ='';
 6458:     for (my $i = 0; $i < scalar(@input); $i++) {
 6459: 	if ($input[$i] =~ /\d/) {
 6460: 	    $output .= $alphabet[$input[$i]];
 6461: 	} else {
 6462: 	    $output .= $input[$i];
 6463: 	}
 6464:     }
 6465:     return $output;
 6466: }
 6467: 
 6468: =pod 
 6469: 
 6470: =item scantron_parse_scanline
 6471: 
 6472:   Decodes a scanline from the selected scantron file
 6473: 
 6474:  Arguments:
 6475:     line             - The text of the scantron file line to process
 6476:     whichline        - Line number
 6477:     scantron_config  - Hash describing the format of the scantron lines.
 6478:     scan_data        - Hash of extra information about the scanline
 6479:                        (see scantron_getfile for more information)
 6480:     just_header      - True if should not process question answers but only
 6481:                        the stuff to the left of the answers.
 6482:     randomorder      - True if randomorder in use
 6483:     randompick       - True if randompick in use
 6484:     sequence         - Exam folder URL
 6485:     master_seq       - Ref to array containing symbs in exam folder
 6486:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6487:                        (corresponding values are resource objects)
 6488:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6489:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6490:                        are refs to an array of resource objects, ordered
 6491:                        according to order used for CODE, when randomorder
 6492:                        and or randompick are in use.
 6493:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6494:                        for current line to question number used for same question
 6495:                         in "Master Sequence" (as seen by Course Coordinator).
 6496:     startline        - Ref to hash where key is question number (0 is first)
 6497:                        and value is number of first bubble line for current 
 6498:                        student or code-based randompick and/or randomorder.
 6499:     totalref         - Ref of scalar used to score total number of bubble
 6500:                        lines needed for responses in a scan line (used when
 6501:                        randompick in use. 
 6502: 
 6503:  Returns:
 6504:    Hash containing the result of parsing the scanline
 6505: 
 6506:    Keys are all proceeded by the string 'scantron.'
 6507: 
 6508:        CODE    - the CODE in use for this scanline
 6509:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6510:                  by the operator
 6511:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6512:                             CODEs were selected, but the usage has been
 6513:                             forced by the operator
 6514:        ID  - student/employee ID
 6515:        PaperID - if used, the ID number printed on the sheet when the 
 6516:                  paper was scanned
 6517:        FirstName - first name from the sheet
 6518:        LastName  - last name from the sheet
 6519: 
 6520:      if just_header was not true these key may also exist
 6521: 
 6522:        missingerror - a list of bubble ranges that are considered to be answers
 6523:                       to a single question that don't have any bubbles filled in.
 6524:                       Of the form questionnumber:firstbubblenumber:count.
 6525:        doubleerror  - a list of bubble ranges that are considered to be answers
 6526:                       to a single question that have more than one bubble filled in.
 6527:                       Of the form questionnumber::firstbubblenumber:count
 6528:    
 6529:                 In the above, count is the number of bubble responses in the
 6530:                 input line needed to represent the possible answers to the question.
 6531:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6532:                 per line would have count = 2.
 6533: 
 6534:        maxquest     - the number of the last bubble line that was parsed
 6535: 
 6536:        (<number> starts at 1)
 6537:        <number>.answer - zero or more letters representing the selected
 6538:                          letters from the scanline for the bubble line 
 6539:                          <number>.
 6540:                          if blank there was either no bubble or there where
 6541:                          multiple bubbles, (consult the keys missingerror and
 6542:                          doubleerror if this is an error condition)
 6543: 
 6544: =cut
 6545: 
 6546: sub scantron_parse_scanline {
 6547:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6548:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6549:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6550: 
 6551:     my %record;
 6552:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6553:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6554: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6555: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6556: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6557: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6558: 	    $record{'scantron.CODE'}=substr($data,
 6559: 					    $$scantron_config{'CODEstart'}-1,
 6560: 					    $$scantron_config{'CODElength'});
 6561: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6562: 		$record{'scantron.useCODE'}=1;
 6563: 	    }
 6564: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6565: 		$record{'scantron.CODE_ignore_dup'}=1;
 6566: 	    }
 6567: 	} else {
 6568: 	    #FIXME interpret first N questions
 6569: 	}
 6570:     }
 6571:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6572: 				  $$scantron_config{'IDlength'});
 6573:     $record{'scantron.PaperID'}=
 6574: 	substr($data,$$scantron_config{'PaperID'}-1,
 6575: 	       $$scantron_config{'PaperIDlength'});
 6576:     $record{'scantron.FirstName'}=
 6577: 	substr($data,$$scantron_config{'FirstName'}-1,
 6578: 	       $$scantron_config{'FirstNamelength'});
 6579:     $record{'scantron.LastName'}=
 6580: 	substr($data,$$scantron_config{'LastName'}-1,
 6581: 	       $$scantron_config{'LastNamelength'});
 6582:     if ($just_header) { return \%record; }
 6583: 
 6584:     my @alphabet=('A'..'Z');
 6585:     my $questnum=0;
 6586:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6587: 
 6588:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6589:     if ($randompick || $randomorder) {
 6590:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6591:                                          $master_seq,$symb_to_resource,
 6592:                                          $partids_by_symb,$orderedforcode,
 6593:                                          $respnumlookup,$startline);
 6594:         if ($total) {
 6595:             $lastpos = $total*$$scantron_config{'Qlength'};
 6596:         }
 6597:         if (ref($totalref)) {
 6598:             $$totalref = $total;
 6599:         }
 6600:     }
 6601:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6602:     chomp($questions);		# Get rid of any trailing \n.
 6603:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6604:     while (length($questions)) {
 6605:         my $answers_needed;
 6606:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6607:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6608:         } else {
 6609:             $answers_needed = $bubble_lines_per_response{$questnum};
 6610:         }
 6611:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6612:                              || 1;
 6613:         $questnum++;
 6614:         my $quest_id = $questnum;
 6615:         my $currentquest = substr($questions,0,$answer_length);
 6616:         $questions       = substr($questions,$answer_length);
 6617:         if (length($currentquest) < $answer_length) { next; }
 6618: 
 6619:         my $subdivided;
 6620:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6621:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6622:         } else {
 6623:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6624:         }
 6625:         if ($subdivided =~ /,/) {
 6626:             my $subquestnum = 1;
 6627:             my $subquestions = $currentquest;
 6628:             my @subanswers_needed = split(/,/,$subdivided);
 6629:             foreach my $subans (@subanswers_needed) {
 6630:                 my $subans_length =
 6631:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6632:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6633:                 $subquestions   = substr($subquestions,$subans_length);
 6634:                 $quest_id = "$questnum.$subquestnum";
 6635:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6636:                     ($$scantron_config{'Qon'} eq 'number')) {
 6637:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6638:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6639:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6640:                         $randomorder,$randompick,$respnumlookup);
 6641:                 } else {
 6642:                     $ansnum = &scantron_validator_positional($ansnum,
 6643:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6644:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6645:                         $randomorder,$randompick,$respnumlookup);
 6646:                 }
 6647:                 $subquestnum ++;
 6648:             }
 6649:         } else {
 6650:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6651:                 ($$scantron_config{'Qon'} eq 'number')) {
 6652:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6653:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6654:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6655:                     $randomorder,$randompick,$respnumlookup);
 6656:             } else {
 6657:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6658:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6659:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6660:                     $randomorder,$randompick,$respnumlookup);
 6661:             }
 6662:         }
 6663:     }
 6664:     $record{'scantron.maxquest'}=$questnum;
 6665:     return \%record;
 6666: }
 6667: 
 6668: sub get_master_seq {
 6669:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6670:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6671:                    (ref($symb_to_resource) eq 'HASH'));
 6672:     my $resource_error;
 6673:     foreach my $resource (@{$resources}) {
 6674:         my $ressymb;
 6675:         if (ref($resource)) {
 6676:             $ressymb = $resource->symb();
 6677:             push(@{$master_seq},$ressymb);
 6678:             $symb_to_resource->{$ressymb} = $resource;
 6679:         } else {
 6680:             $resource_error = 1;
 6681:             last;
 6682:         }
 6683:     }
 6684:     return $resource_error;
 6685: }
 6686: 
 6687: sub get_respnum_lookups {
 6688:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6689:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6690:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6691:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6692:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6693:                    (ref($startline) eq 'HASH'));
 6694:     my ($user,$scancode);
 6695:     if ((exists($record->{'scantron.CODE'})) &&
 6696:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6697:         $scancode = $record->{'scantron.CODE'};
 6698:     } else {
 6699:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6700:     }
 6701:     my @mapresources =
 6702:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6703:                      $orderedforcode);
 6704:     my $total = 0;
 6705:     my $count = 0;
 6706:     foreach my $resource (@mapresources) {
 6707:         my $id = $resource->id();
 6708:         my $symb = $resource->symb();
 6709:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6710:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6711:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6712:                 if ($respnum ne '') {
 6713:                     $respnumlookup->{$count} = $respnum;
 6714:                     $startline->{$count} = $total;
 6715:                     $total += $bubble_lines_per_response{$respnum};
 6716:                     $count ++;
 6717:                 }
 6718:             }
 6719:         }
 6720:     }
 6721:     return $total;
 6722: }
 6723: 
 6724: sub scantron_validator_lettnum {
 6725:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6726:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6727:         $randompick,$respnumlookup) = @_;
 6728: 
 6729:     # Qon 'letter' implies for each slot in currquest we have:
 6730:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6731:     #    about anything else (esp. a value of Qoff) for missing
 6732:     #    bubbles.
 6733:     #
 6734:     # Qon 'number' implies each slot gives a digit that indexes the
 6735:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6736:     #    and * or ? for double bubbles on a single line.
 6737:     #
 6738: 
 6739:     my $matchon;
 6740:     if ($$scantron_config{'Qon'} eq 'letter') {
 6741:         $matchon = '[A-Z]';
 6742:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6743:         $matchon = '\d';
 6744:     }
 6745:     my $occurrences = 0;
 6746:     my $responsenum = $questnum-1;
 6747:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6748:        $responsenum = $respnumlookup->{$questnum-1}
 6749:     }
 6750:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6751:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6752:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6753:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6754:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6755:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6756:         my @singlelines = split('',$currquest);
 6757:         foreach my $entry (@singlelines) {
 6758:             $occurrences = &occurence_count($entry,$matchon);
 6759:             if ($occurrences > 1) {
 6760:                 last;
 6761:             }
 6762:         }
 6763:     } else {
 6764:         $occurrences = &occurence_count($currquest,$matchon); 
 6765:     }
 6766:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6767:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6768:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6769:             my $bubble = substr($currquest,$ans,1);
 6770:             if ($bubble =~ /$matchon/ ) {
 6771:                 if ($$scantron_config{'Qon'} eq 'number') {
 6772:                     if ($bubble == 0) {
 6773:                         $bubble = 10; 
 6774:                     }
 6775:                     $record->{"scantron.$ansnum.answer"} = 
 6776:                         $alphabet->[$bubble-1];
 6777:                 } else {
 6778:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6779:                 }
 6780:             } else {
 6781:                 $record->{"scantron.$ansnum.answer"}='';
 6782:             }
 6783:             $ansnum++;
 6784:         }
 6785:     } elsif (!defined($currquest)
 6786:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6787:             || (&occurence_count($currquest,$matchon) == 0)) {
 6788:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6789:             $record->{"scantron.$ansnum.answer"}='';
 6790:             $ansnum++;
 6791:         }
 6792:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6793:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6794:         }
 6795:     } else {
 6796:         if ($$scantron_config{'Qon'} eq 'number') {
 6797:             $currquest = &digits_to_letters($currquest);            
 6798:         }
 6799:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6800:             my $bubble = substr($currquest,$ans,1);
 6801:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6802:             $ansnum++;
 6803:         }
 6804:     }
 6805:     return $ansnum;
 6806: }
 6807: 
 6808: sub scantron_validator_positional {
 6809:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6810:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6811:         $randomorder,$randompick,$respnumlookup) = @_;
 6812: 
 6813:     # Otherwise there's a positional notation;
 6814:     # each bubble line requires Qlength items, and there are filled in
 6815:     # bubbles for each case where there 'Qon' characters.
 6816:     #
 6817: 
 6818:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6819: 
 6820:     # If the split only gives us one element.. the full length of the
 6821:     # answer string, no bubbles are filled in:
 6822: 
 6823:     if ($answers_needed eq '') {
 6824:         return;
 6825:     }
 6826: 
 6827:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6828:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6829:             $record->{"scantron.$ansnum.answer"}='';
 6830:             $ansnum++;
 6831:         }
 6832:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6833:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6834:         }
 6835:     } elsif (scalar(@array) == 2) {
 6836:         my $location = length($array[0]);
 6837:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6838:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6839:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6840:             if ($ans eq $line_num) {
 6841:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6842:             } else {
 6843:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6844:             }
 6845:             $ansnum++;
 6846:          }
 6847:     } else {
 6848:         #  If there's more than one instance of a bubble character
 6849:         #  That's a double bubble; with positional notation we can
 6850:         #  record all the bubbles filled in as well as the
 6851:         #  fact this response consists of multiple bubbles.
 6852:         #
 6853:         my $responsenum = $questnum-1;
 6854:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6855:             $responsenum = $respnumlookup->{$questnum-1}
 6856:         }
 6857:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6858:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6859:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6860:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6861:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6862:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6863:             my $doubleerror = 0;
 6864:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6865:                    (!$doubleerror)) {
 6866:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6867:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6868:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6869:                if (length(@currarray) > 2) {
 6870:                    $doubleerror = 1;
 6871:                } 
 6872:             }
 6873:             if ($doubleerror) {
 6874:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6875:             }
 6876:         } else {
 6877:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6878:         }
 6879:         my $item = $ansnum;
 6880:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6881:             $record->{"scantron.$item.answer"} = '';
 6882:             $item ++;
 6883:         }
 6884: 
 6885:         my @ans=@array;
 6886:         my $i=0;
 6887:         my $increment = 0;
 6888:         while ($#ans) {
 6889:             $i+=length($ans[0]) + $increment;
 6890:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6891:             my $bubble = $i%$$scantron_config{'Qlength'};
 6892:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6893:             shift(@ans);
 6894:             $increment = 1;
 6895:         }
 6896:         $ansnum += $answers_needed;
 6897:     }
 6898:     return $ansnum;
 6899: }
 6900: 
 6901: =pod
 6902: 
 6903: =item scantron_add_delay
 6904: 
 6905:    Adds an error message that occurred during the grading phase to a
 6906:    queue of messages to be shown after grading pass is complete
 6907: 
 6908:  Arguments:
 6909:    $delayqueue  - arrary ref of hash ref of error messages
 6910:    $scanline    - the scanline that caused the error
 6911:    $errormesage - the error message
 6912:    $errorcode   - a numeric code for the error
 6913: 
 6914:  Side Effects:
 6915:    updates the $delayqueue to have a new hash ref of the error
 6916: 
 6917: =cut
 6918: 
 6919: sub scantron_add_delay {
 6920:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6921:     push(@$delayqueue,
 6922: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6923: 	  'ecode' => $errorcode }
 6924: 	 );
 6925: }
 6926: 
 6927: =pod
 6928: 
 6929: =item scantron_find_student
 6930: 
 6931:    Finds the username for the current scanline
 6932: 
 6933:   Arguments:
 6934:    $scantron_record - hash result from scantron_parse_scanline
 6935:    $scan_data       - hash of correction information 
 6936:                       (see &scantron_getfile() form more information)
 6937:    $idmap           - hash from &username_to_idmap()
 6938:    $line            - number of current scanline
 6939:  
 6940:   Returns:
 6941:    Either 'username:domain' or undef if unknown
 6942: 
 6943: =cut
 6944: 
 6945: sub scantron_find_student {
 6946:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6947:     my $scanID=$$scantron_record{'scantron.ID'};
 6948:     if ($scanID =~ /^\s*$/) {
 6949:  	return &scan_data($scan_data,"$line.user");
 6950:     }
 6951:     foreach my $id (keys(%$idmap)) {
 6952:  	if (lc($id) eq lc($scanID)) {
 6953:  	    return $$idmap{$id};
 6954:  	}
 6955:     }
 6956:     return undef;
 6957: }
 6958: 
 6959: =pod
 6960: 
 6961: =item scantron_filter
 6962: 
 6963:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6964:    hidden resources was selected
 6965: 
 6966: =cut
 6967: 
 6968: sub scantron_filter {
 6969:     my ($curres)=@_;
 6970: 
 6971:     if (ref($curres) && $curres->is_problem()) {
 6972: 	# if the user has asked to not have either hidden
 6973: 	# or 'randomout' controlled resources to be graded
 6974: 	# don't include them
 6975: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6976: 	    && $curres->randomout) {
 6977: 	    return 0;
 6978: 	}
 6979: 	return 1;
 6980:     }
 6981:     return 0;
 6982: }
 6983: 
 6984: =pod
 6985: 
 6986: =item scantron_process_corrections
 6987: 
 6988:    Gets correction information out of submitted form data and corrects
 6989:    the scanline
 6990: 
 6991: =cut
 6992: 
 6993: sub scantron_process_corrections {
 6994:     my ($r) = @_;
 6995:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6996:     my ($scanlines,$scan_data)=&scantron_getfile();
 6997:     my $classlist=&Apache::loncoursedata::get_classlist();
 6998:     my $which=$env{'form.scantron_line'};
 6999:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7000:     my ($skip,$err,$errmsg);
 7001:     if ($env{'form.scantron_skip_record'}) {
 7002: 	$skip=1;
 7003:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7004: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7005: 	    $env{'form.scantron_domain'};
 7006: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7007: 	($line,$err,$errmsg)=
 7008: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7009: 				     'ID',{'newid'=>$newid,
 7010: 				    'username'=>$env{'form.scantron_username'},
 7011: 				    'domain'=>$env{'form.scantron_domain'}});
 7012:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7013: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7014: 	my $newCODE;
 7015: 	my %args;
 7016: 	if      ($resolution eq 'use_unfound') {
 7017: 	    $newCODE='use_unfound';
 7018: 	} elsif ($resolution eq 'use_found') {
 7019: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7020: 	} elsif ($resolution eq 'use_typed') {
 7021: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7022: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7023: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7024: 	}
 7025: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7026: 	    $args{'CODE_ignore_dup'}=1;
 7027: 	}
 7028: 	$args{'CODE'}=$newCODE;
 7029: 	($line,$err,$errmsg)=
 7030: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7031: 				     'CODE',\%args);
 7032:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7033: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7034: 	    ($line,$err,$errmsg)=
 7035: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7036: 					 $which,'answer',
 7037: 					 { 'question'=>$question,
 7038: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7039:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7040: 	    if ($err) { last; }
 7041: 	}
 7042:     }
 7043:     if ($err) {
 7044: 	$r->print(
 7045:             '<p class="LC_error">'
 7046:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7047:                 $errmsg)
 7048:            .'</p>');
 7049:     } else {
 7050: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7051: 	&scantron_putfile($scanlines,$scan_data);
 7052:     }
 7053: }
 7054: 
 7055: =pod
 7056: 
 7057: =item reset_skipping_status
 7058: 
 7059:    Forgets the current set of remember skipped scanlines (and thus
 7060:    reverts back to considering all lines in the
 7061:    scantron_skipped_<filename> file)
 7062: 
 7063: =cut
 7064: 
 7065: sub reset_skipping_status {
 7066:     my ($scanlines,$scan_data)=&scantron_getfile();
 7067:     &scan_data($scan_data,'remember_skipping',undef,1);
 7068:     &scantron_putfile(undef,$scan_data);
 7069: }
 7070: 
 7071: =pod
 7072: 
 7073: =item start_skipping
 7074: 
 7075:    Marks a scanline to be skipped. 
 7076: 
 7077: =cut
 7078: 
 7079: sub start_skipping {
 7080:     my ($scan_data,$i)=@_;
 7081:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7082:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7083: 	$remembered{$i}=2;
 7084:     } else {
 7085: 	$remembered{$i}=1;
 7086:     }
 7087:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7088: }
 7089: 
 7090: =pod
 7091: 
 7092: =item should_be_skipped
 7093: 
 7094:    Checks whether a scanline should be skipped.
 7095: 
 7096: =cut
 7097: 
 7098: sub should_be_skipped {
 7099:     my ($scanlines,$scan_data,$i)=@_;
 7100:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7101: 	# not redoing old skips
 7102: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7103: 	return 0;
 7104:     }
 7105:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7106: 
 7107:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7108: 	return 0;
 7109:     }
 7110:     return 1;
 7111: }
 7112: 
 7113: =pod
 7114: 
 7115: =item remember_current_skipped
 7116: 
 7117:    Discovers what scanlines are in the scantron_skipped_<filename>
 7118:    file and remembers them into scan_data for later use.
 7119: 
 7120: =cut
 7121: 
 7122: sub remember_current_skipped {
 7123:     my ($scanlines,$scan_data)=&scantron_getfile();
 7124:     my %to_remember;
 7125:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7126: 	if ($scanlines->{'skipped'}[$i]) {
 7127: 	    $to_remember{$i}=1;
 7128: 	}
 7129:     }
 7130: 
 7131:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7132:     &scantron_putfile(undef,$scan_data);
 7133: }
 7134: 
 7135: =pod
 7136: 
 7137: =item check_for_error
 7138: 
 7139:     Checks if there was an error when attempting to remove a specific
 7140:     scantron_.. bubblesheet data file. Prints out an error if
 7141:     something went wrong.
 7142: 
 7143: =cut
 7144: 
 7145: sub check_for_error {
 7146:     my ($r,$result)=@_;
 7147:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7148: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7149:     }
 7150: }
 7151: 
 7152: =pod
 7153: 
 7154: =item scantron_warning_screen
 7155: 
 7156:    Interstitial screen to make sure the operator has selected the
 7157:    correct options before we start the validation phase.
 7158: 
 7159: =cut
 7160: 
 7161: sub scantron_warning_screen {
 7162:     my ($button_text,$symb)=@_;
 7163:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7164:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7165:     my $CODElist;
 7166:     if ($scantron_config{'CODElocation'} &&
 7167: 	$scantron_config{'CODEstart'} &&
 7168: 	$scantron_config{'CODElength'}) {
 7169: 	$CODElist=$env{'form.scantron_CODElist'};
 7170: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7171: 	$CODElist=
 7172: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7173: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7174:     }
 7175:     my $lastbubblepoints;
 7176:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7177:         $lastbubblepoints =
 7178:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7179:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7180:     }
 7181:     return ('
 7182: <p>
 7183: <span class="LC_warning">
 7184: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7185: </p>
 7186: <table>
 7187: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7188: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7189: '.$CODElist.$lastbubblepoints.'
 7190: </table>
 7191: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7192: '.&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>
 7193: 
 7194: <br />
 7195: ');
 7196: }
 7197: 
 7198: =pod
 7199: 
 7200: =item scantron_do_warning
 7201: 
 7202:    Check if the operator has picked something for all required
 7203:    fields. Error out if something is missing.
 7204: 
 7205: =cut
 7206: 
 7207: sub scantron_do_warning {
 7208:     my ($r,$symb)=@_;
 7209:     if (!$symb) {return '';}
 7210:     my $default_form_data=&defaultFormData($symb);
 7211:     $r->print(&scantron_form_start().$default_form_data);
 7212:     if ( $env{'form.selectpage'} eq '' ||
 7213: 	 $env{'form.scantron_selectfile'} eq '' ||
 7214: 	 $env{'form.scantron_format'} eq '' ) {
 7215: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7216: 	if ( $env{'form.selectpage'} eq '') {
 7217: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7218: 	} 
 7219: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7220: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7221: 	} 
 7222: 	if ( $env{'form.scantron_format'} eq '') {
 7223: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7224: 	} 
 7225:     } else {
 7226: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7227:         my $bubbledbyhand=&hand_bubble_option();
 7228: 	$r->print('
 7229: '.$warning.$bubbledbyhand.'
 7230: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7231: <input type="hidden" name="command" value="scantron_validate" />
 7232: ');
 7233:     }
 7234:     $r->print("</form><br />");
 7235:     return '';
 7236: }
 7237: 
 7238: =pod
 7239: 
 7240: =item scantron_form_start
 7241: 
 7242:     html hidden input for remembering all selected grading options
 7243: 
 7244: =cut
 7245: 
 7246: sub scantron_form_start {
 7247:     my ($max_bubble)=@_;
 7248:     my $result= <<SCANTRONFORM;
 7249: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7250:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7251:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7252:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7253:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7254:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7255:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7256:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7257:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7258:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7259: SCANTRONFORM
 7260: 
 7261:   my $line = 0;
 7262:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7263:        my $chunk =
 7264: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7265:        $chunk .=
 7266: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7267:        $chunk .= 
 7268:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7269:        $chunk .=
 7270:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7271:        $chunk .=
 7272:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7273:        $result .= $chunk;
 7274:        $line++;
 7275:     }
 7276:     return $result;
 7277: }
 7278: 
 7279: =pod
 7280: 
 7281: =item scantron_validate_file
 7282: 
 7283:     Dispatch routine for doing validation of a bubblesheet data file.
 7284: 
 7285:     Also processes any necessary information resets that need to
 7286:     occur before validation begins (ignore previous corrections,
 7287:     restarting the skipped records processing)
 7288: 
 7289: =cut
 7290: 
 7291: sub scantron_validate_file {
 7292:     my ($r,$symb) = @_;
 7293:     if (!$symb) {return '';}
 7294:     my $default_form_data=&defaultFormData($symb);
 7295:     
 7296:     # do the detection of only doing skipped records first before we delete
 7297:     # them when doing the corrections reset
 7298:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7299: 	&reset_skipping_status();
 7300:     }
 7301:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7302: 	&remember_current_skipped();
 7303: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7304:     }
 7305: 
 7306:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7307: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7308: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7309: 	&check_for_error($r,&scantron_remove_scan_data());
 7310: 	$env{'form.scantron_options_ignore'}='done';
 7311:     }
 7312: 
 7313:     if ($env{'form.scantron_corrections'}) {
 7314: 	&scantron_process_corrections($r);
 7315:     }
 7316:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7317:     #get the student pick code ready
 7318:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7319:     my $nav_error;
 7320:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7321:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7322:     if ($nav_error) {
 7323:         $r->print(&navmap_errormsg());
 7324:         return '';
 7325:     }
 7326:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7327:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7328:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7329:     }
 7330:     $r->print($result);
 7331:     
 7332:     my @validate_phases=( 'sequence',
 7333: 			  'ID',
 7334: 			  'CODE',
 7335: 			  'doublebubble',
 7336: 			  'missingbubbles');
 7337:     if (!$env{'form.validatepass'}) {
 7338: 	$env{'form.validatepass'} = 0;
 7339:     }
 7340:     my $currentphase=$env{'form.validatepass'};
 7341: 
 7342: 
 7343:     my $stop=0;
 7344:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7345: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7346: 	$r->rflush();
 7347: 
 7348: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7349: 	{
 7350: 	    no strict 'refs';
 7351: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7352: 	}
 7353:     }
 7354:     if (!$stop) {
 7355: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7356: 	$r->print(&mt('Validation process complete.').'<br />'.
 7357:                   $warning.
 7358:                   &mt('Perform verification for each student after storage of submissions?').
 7359:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7360:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7361:                   ('&nbsp;'x3).'<label>'.
 7362:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7363:                   '</label></span><br />'.
 7364:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7365:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7366:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7367:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7368:     } else {
 7369: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7370: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7371:     }
 7372:     if ($stop) {
 7373: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7374: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7375: 	    $r->print(' '.&mt('this error').' <br />');
 7376: 
 7377:             $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>');
 7378: 	} else {
 7379:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7380: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7381:             } else {
 7382:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7383:             }
 7384: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7385: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7386: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7387: 	}
 7388:     }
 7389:     $r->print(" </form><br />");
 7390:     return '';
 7391: }
 7392: 
 7393: 
 7394: =pod
 7395: 
 7396: =item scantron_remove_file
 7397: 
 7398:    Removes the requested bubblesheet data file, makes sure that
 7399:    scantron_original_<filename> is never removed
 7400: 
 7401: 
 7402: =cut
 7403: 
 7404: sub scantron_remove_file {
 7405:     my ($which)=@_;
 7406:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7407:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7408:     my $file='scantron_';
 7409:     if ($which eq 'corrected' || $which eq 'skipped') {
 7410: 	$file.=$which.'_';
 7411:     } else {
 7412: 	return 'refused';
 7413:     }
 7414:     $file.=$env{'form.scantron_selectfile'};
 7415:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7416: }
 7417: 
 7418: 
 7419: =pod
 7420: 
 7421: =item scantron_remove_scan_data
 7422: 
 7423:    Removes all scan_data correction for the requested bubblesheet
 7424:    data file.  (In the case that both the are doing skipped records we need
 7425:    to remember the old skipped lines for the time being so that element
 7426:    persists for a while.)
 7427: 
 7428: =cut
 7429: 
 7430: sub scantron_remove_scan_data {
 7431:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7432:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7433:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7434:     my @todelete;
 7435:     my $filename=$env{'form.scantron_selectfile'};
 7436:     foreach my $key (@keys) {
 7437: 	if ($key=~/^\Q$filename\E_/) {
 7438: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7439: 		$key=~/remember_skipping/) {
 7440: 		next;
 7441: 	    }
 7442: 	    push(@todelete,$key);
 7443: 	}
 7444:     }
 7445:     my $result;
 7446:     if (@todelete) {
 7447: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7448: 				       \@todelete,$cdom,$cname);
 7449:     } else {
 7450: 	$result = 'ok';
 7451:     }
 7452:     return $result;
 7453: }
 7454: 
 7455: 
 7456: =pod
 7457: 
 7458: =item scantron_getfile
 7459: 
 7460:     Fetches the requested bubblesheet data file (all 3 versions), and
 7461:     the scan_data hash
 7462:   
 7463:   Arguments:
 7464:     None
 7465: 
 7466:   Returns:
 7467:     2 hash references
 7468: 
 7469:      - first one has 
 7470:          orig      -
 7471:          corrected -
 7472:          skipped   -  each of which points to an array ref of the specified
 7473:                       file broken up into individual lines
 7474:          count     - number of scanlines
 7475:  
 7476:      - second is the scan_data hash possible keys are
 7477:        ($number refers to scanline numbered $number and thus the key affects
 7478:         only that scanline
 7479:         $bubline refers to the specific bubble line element and the aspects
 7480:         refers to that specific bubble line element)
 7481: 
 7482:        $number.user - username:domain to use
 7483:        $number.CODE_ignore_dup 
 7484:                     - ignore the duplicate CODE error 
 7485:        $number.useCODE
 7486:                     - use the CODE in the scanline as is
 7487:        $number.no_bubble.$bubline
 7488:                     - it is valid that there is no bubbled in bubble
 7489:                       at $number $bubline
 7490:        remember_skipping
 7491:                     - a frozen hash containing keys of $number and values
 7492:                       of either 
 7493:                         1 - we are on a 'do skipped records pass' and plan
 7494:                             on processing this line
 7495:                         2 - we are on a 'do skipped records pass' and this
 7496:                             scanline has been marked to skip yet again
 7497: 
 7498: =cut
 7499: 
 7500: sub scantron_getfile {
 7501:     #FIXME really would prefer a scantron directory
 7502:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7503:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7504:     my $lines;
 7505:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7506: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7507:     my %scanlines;
 7508:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7509:     my $temp=$scanlines{'orig'};
 7510:     $scanlines{'count'}=$#$temp;
 7511: 
 7512:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7513: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7514:     if ($lines eq '-1') {
 7515: 	$scanlines{'corrected'}=[];
 7516:     } else {
 7517: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7518:     }
 7519:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7520: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7521:     if ($lines eq '-1') {
 7522: 	$scanlines{'skipped'}=[];
 7523:     } else {
 7524: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7525:     }
 7526:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7527:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7528:     my %scan_data = @tmp;
 7529:     return (\%scanlines,\%scan_data);
 7530: }
 7531: 
 7532: =pod
 7533: 
 7534: =item lonnet_putfile
 7535: 
 7536:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7537: 
 7538:  Arguments:
 7539:    $contents - data to store
 7540:    $filename - filename to store $contents into
 7541: 
 7542:  Returns:
 7543:    result value from &Apache::lonnet::finishuserfileupload
 7544: 
 7545: =cut
 7546: 
 7547: sub lonnet_putfile {
 7548:     my ($contents,$filename)=@_;
 7549:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7550:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7551:     $env{'form.sillywaytopassafilearound'}=$contents;
 7552:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7553: 
 7554: }
 7555: 
 7556: =pod
 7557: 
 7558: =item scantron_putfile
 7559: 
 7560:     Stores the current version of the bubblesheet data files, and the
 7561:     scan_data hash. (Does not modify the original version only the
 7562:     corrected and skipped versions.
 7563: 
 7564:  Arguments:
 7565:     $scanlines - hash ref that looks like the first return value from
 7566:                  &scantron_getfile()
 7567:     $scan_data - hash ref that looks like the second return value from
 7568:                  &scantron_getfile()
 7569: 
 7570: =cut
 7571: 
 7572: sub scantron_putfile {
 7573:     my ($scanlines,$scan_data) = @_;
 7574:     #FIXME really would prefer a scantron directory
 7575:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7576:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7577:     if ($scanlines) {
 7578: 	my $prefix='scantron_';
 7579: # no need to update orig, shouldn't change
 7580: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7581: #		    $env{'form.scantron_selectfile'});
 7582: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7583: 			$prefix.'corrected_'.
 7584: 			$env{'form.scantron_selectfile'});
 7585: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7586: 			$prefix.'skipped_'.
 7587: 			$env{'form.scantron_selectfile'});
 7588:     }
 7589:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7590: }
 7591: 
 7592: =pod
 7593: 
 7594: =item scantron_get_line
 7595: 
 7596:    Returns the correct version of the scanline
 7597: 
 7598:  Arguments:
 7599:     $scanlines - hash ref that looks like the first return value from
 7600:                  &scantron_getfile()
 7601:     $scan_data - hash ref that looks like the second return value from
 7602:                  &scantron_getfile()
 7603:     $i         - number of the requested line (starts at 0)
 7604: 
 7605:  Returns:
 7606:    A scanline, (either the original or the corrected one if it
 7607:    exists), or undef if the requested scanline should be
 7608:    skipped. (Either because it's an skipped scanline, or it's an
 7609:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7610:    pass.
 7611: 
 7612: =cut
 7613: 
 7614: sub scantron_get_line {
 7615:     my ($scanlines,$scan_data,$i)=@_;
 7616:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7617:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7618:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7619:     return $scanlines->{'orig'}[$i]; 
 7620: }
 7621: 
 7622: =pod
 7623: 
 7624: =item scantron_todo_count
 7625: 
 7626:     Counts the number of scanlines that need processing.
 7627: 
 7628:  Arguments:
 7629:     $scanlines - hash ref that looks like the first return value from
 7630:                  &scantron_getfile()
 7631:     $scan_data - hash ref that looks like the second return value from
 7632:                  &scantron_getfile()
 7633: 
 7634:  Returns:
 7635:     $count - number of scanlines to process
 7636: 
 7637: =cut
 7638: 
 7639: sub get_todo_count {
 7640:     my ($scanlines,$scan_data)=@_;
 7641:     my $count=0;
 7642:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7643: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7644: 	if ($line=~/^[\s\cz]*$/) { next; }
 7645: 	$count++;
 7646:     }
 7647:     return $count;
 7648: }
 7649: 
 7650: =pod
 7651: 
 7652: =item scantron_put_line
 7653: 
 7654:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7655:     data file.
 7656: 
 7657:  Arguments:
 7658:     $scanlines - hash ref that looks like the first return value from
 7659:                  &scantron_getfile()
 7660:     $scan_data - hash ref that looks like the second return value from
 7661:                  &scantron_getfile()
 7662:     $i         - line number to update
 7663:     $newline   - contents of the updated scanline
 7664:     $skip      - if true make the line for skipping and update the
 7665:                  'skipped' file
 7666: 
 7667: =cut
 7668: 
 7669: sub scantron_put_line {
 7670:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7671:     if ($skip) {
 7672: 	$scanlines->{'skipped'}[$i]=$newline;
 7673: 	&start_skipping($scan_data,$i);
 7674: 	return;
 7675:     }
 7676:     $scanlines->{'corrected'}[$i]=$newline;
 7677: }
 7678: 
 7679: =pod
 7680: 
 7681: =item scantron_clear_skip
 7682: 
 7683:    Remove a line from the 'skipped' file
 7684: 
 7685:  Arguments:
 7686:     $scanlines - hash ref that looks like the first return value from
 7687:                  &scantron_getfile()
 7688:     $scan_data - hash ref that looks like the second return value from
 7689:                  &scantron_getfile()
 7690:     $i         - line number to update
 7691: 
 7692: =cut
 7693: 
 7694: sub scantron_clear_skip {
 7695:     my ($scanlines,$scan_data,$i)=@_;
 7696:     if (exists($scanlines->{'skipped'}[$i])) {
 7697: 	undef($scanlines->{'skipped'}[$i]);
 7698: 	return 1;
 7699:     }
 7700:     return 0;
 7701: }
 7702: 
 7703: =pod
 7704: 
 7705: =item scantron_filter_not_exam
 7706: 
 7707:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7708:    filter out resources that are not marked as 'exam' mode
 7709: 
 7710: =cut
 7711: 
 7712: sub scantron_filter_not_exam {
 7713:     my ($curres)=@_;
 7714:     
 7715:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7716: 	# if the user has asked to not have either hidden
 7717: 	# or 'randomout' controlled resources to be graded
 7718: 	# don't include them
 7719: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7720: 	    && $curres->randomout) {
 7721: 	    return 0;
 7722: 	}
 7723: 	return 1;
 7724:     }
 7725:     return 0;
 7726: }
 7727: 
 7728: =pod
 7729: 
 7730: =item scantron_validate_sequence
 7731: 
 7732:     Validates the selected sequence, checking for resource that are
 7733:     not set to exam mode.
 7734: 
 7735: =cut
 7736: 
 7737: sub scantron_validate_sequence {
 7738:     my ($r,$currentphase) = @_;
 7739: 
 7740:     my $navmap=Apache::lonnavmaps::navmap->new();
 7741:     unless (ref($navmap)) {
 7742:         $r->print(&navmap_errormsg());
 7743:         return (1,$currentphase);
 7744:     }
 7745:     my (undef,undef,$sequence)=
 7746: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7747: 
 7748:     my $map=$navmap->getResourceByUrl($sequence);
 7749: 
 7750:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7751:                                     value="ignore" />');
 7752:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7753: 	my @resources=
 7754: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7755: 	if (@resources) {
 7756: 	    $r->print('<p class="LC_warning">'
 7757:                .&mt('Some resources in the sequence currently are not set to'
 7758:                    .' exam mode. Grading these resources currently may not'
 7759:                    .' work correctly.')
 7760:                .'</p>'
 7761:             );
 7762: 	    return (1,$currentphase);
 7763: 	}
 7764:     }
 7765: 
 7766:     return (0,$currentphase+1);
 7767: }
 7768: 
 7769: 
 7770: 
 7771: sub scantron_validate_ID {
 7772:     my ($r,$currentphase) = @_;
 7773:     
 7774:     #get student info
 7775:     my $classlist=&Apache::loncoursedata::get_classlist();
 7776:     my %idmap=&username_to_idmap($classlist);
 7777: 
 7778:     #get scantron line setup
 7779:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7780:     my ($scanlines,$scan_data)=&scantron_getfile();
 7781: 
 7782:     my $nav_error;
 7783:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7784:     if ($nav_error) {
 7785:         $r->print(&navmap_errormsg());
 7786:         return(1,$currentphase);
 7787:     }
 7788: 
 7789:     my %found=('ids'=>{},'usernames'=>{});
 7790:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7791: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7792: 	if ($line=~/^[\s\cz]*$/) { next; }
 7793: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7794: 						 $scan_data);
 7795: 	my $id=$$scan_record{'scantron.ID'};
 7796: 	my $found;
 7797: 	foreach my $checkid (keys(%idmap)) {
 7798: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7799: 	}
 7800: 	if ($found) {
 7801: 	    my $username=$idmap{$found};
 7802: 	    if ($found{'ids'}{$found}) {
 7803: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7804: 					 $line,'duplicateID',$found);
 7805: 		return(1,$currentphase);
 7806: 	    } elsif ($found{'usernames'}{$username}) {
 7807: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7808: 					 $line,'duplicateID',$username);
 7809: 		return(1,$currentphase);
 7810: 	    }
 7811: 	    #FIXME store away line we previously saw the ID on to use above
 7812: 	    $found{'ids'}{$found}++;
 7813: 	    $found{'usernames'}{$username}++;
 7814: 	} else {
 7815: 	    if ($id =~ /^\s*$/) {
 7816: 		my $username=&scan_data($scan_data,"$i.user");
 7817: 		if (defined($username) && $found{'usernames'}{$username}) {
 7818: 		    &scantron_get_correction($r,$i,$scan_record,
 7819: 					     \%scantron_config,
 7820: 					     $line,'duplicateID',$username);
 7821: 		    return(1,$currentphase);
 7822: 		} elsif (!defined($username)) {
 7823: 		    &scantron_get_correction($r,$i,$scan_record,
 7824: 					     \%scantron_config,
 7825: 					     $line,'incorrectID');
 7826: 		    return(1,$currentphase);
 7827: 		}
 7828: 		$found{'usernames'}{$username}++;
 7829: 	    } else {
 7830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7831: 					 $line,'incorrectID');
 7832: 		return(1,$currentphase);
 7833: 	    }
 7834: 	}
 7835:     }
 7836: 
 7837:     return (0,$currentphase+1);
 7838: }
 7839: 
 7840: 
 7841: sub scantron_get_correction {
 7842:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7843:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7844: #FIXME in the case of a duplicated ID the previous line, probably need
 7845: #to show both the current line and the previous one and allow skipping
 7846: #the previous one or the current one
 7847: 
 7848:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7849:         $r->print(
 7850:             '<p class="LC_warning">'
 7851:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7852:                 "<b>$error</b>",
 7853:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7854:            ."</p> \n");
 7855:     } else {
 7856:         $r->print(
 7857:             '<p class="LC_warning">'
 7858:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7859:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7860:            ."</p> \n");
 7861:     }
 7862:     my $message =
 7863:         '<p>'
 7864:        .&mt('The ID on the form is [_1]',
 7865:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7866:        .'<br />'
 7867:        .&mt('The name on the paper is [_1], [_2]',
 7868:             $$scan_record{'scantron.LastName'},
 7869:             $$scan_record{'scantron.FirstName'})
 7870:        .'</p>';
 7871: 
 7872:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7873:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7874:                            # Array populated for doublebubble or
 7875:     my @lines_to_correct;  # missingbubble errors to build javascript
 7876:                            # to validate radio button checking   
 7877: 
 7878:     if ($error =~ /ID$/) {
 7879: 	if ($error eq 'incorrectID') {
 7880: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7881: 		      "</p>\n");
 7882: 	} elsif ($error eq 'duplicateID') {
 7883: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7884: 	}
 7885: 	$r->print($message);
 7886: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7887: 	$r->print("\n<ul><li> ");
 7888: 	#FIXME it would be nice if this sent back the user ID and
 7889: 	#could do partial userID matches
 7890: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7891: 				       'scantron_username','scantron_domain'));
 7892: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7893: 	$r->print("\n:\n".
 7894: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7895: 
 7896: 	$r->print('</li>');
 7897:     } elsif ($error =~ /CODE$/) {
 7898: 	if ($error eq 'incorrectCODE') {
 7899: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7900: 	} elsif ($error eq 'duplicateCODE') {
 7901: 	    $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");
 7902: 	}
 7903:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7904:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7905:                  ."</p>\n");
 7906: 	$r->print($message);
 7907: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7908: 	$r->print("\n<br /> ");
 7909: 	my $i=0;
 7910: 	if ($error eq 'incorrectCODE' 
 7911: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7912: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7913: 	    if ($closest > 0) {
 7914: 		foreach my $testcode (@{$closest}) {
 7915: 		    my $checked='';
 7916: 		    if (!$i) { $checked=' checked="checked"'; }
 7917: 		    $r->print("
 7918:    <label>
 7919:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7920:        ".&mt("Use the similar CODE [_1] instead.",
 7921: 	    "<b><tt>".$testcode."</tt></b>")."
 7922:     </label>
 7923:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7924: 		    $r->print("\n<br />");
 7925: 		    $i++;
 7926: 		}
 7927: 	    }
 7928: 	}
 7929: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7930: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7931: 	    $r->print("
 7932:     <label>
 7933:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7934:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7935: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7936:     </label>");
 7937: 	    $r->print("\n<br />");
 7938: 	}
 7939: 
 7940: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7941: function change_radio(field) {
 7942:     var slct=document.scantronupload.scantron_CODE_resolution;
 7943:     var i;
 7944:     for (i=0;i<slct.length;i++) {
 7945:         if (slct[i].value==field) { slct[i].checked=true; }
 7946:     }
 7947: }
 7948: ENDSCRIPT
 7949: 	my $href="/adm/pickcode?".
 7950: 	   "form=".&escape("scantronupload").
 7951: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7952: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7953: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7954: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7955: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7956: 	    $r->print("
 7957:     <label>
 7958:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7959:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7960: 	     "<a target='_blank' href='$href'>","</a>")."
 7961:     </label> 
 7962:     ".&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\')" />'));
 7963: 	    $r->print("\n<br />");
 7964: 	}
 7965: 	$r->print("
 7966:     <label>
 7967:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7968:        ".&mt("Use [_1] as the CODE.",
 7969: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7970: 	$r->print("\n<br /><br />");
 7971:     } elsif ($error eq 'doublebubble') {
 7972: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7973: 
 7974: 	# The form field scantron_questions is acutally a list of line numbers.
 7975: 	# represented by this form so:
 7976: 
 7977: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7978:                                                 $respnumlookup,$startline);
 7979: 
 7980: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7981: 		  $line_list.'" />');
 7982: 	$r->print($message);
 7983: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7984: 	foreach my $question (@{$arg}) {
 7985: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7986:                                                    $scan_record, $error,
 7987:                                                    $randomorder,$randompick,
 7988:                                                    $respnumlookup,$startline);
 7989:             push(@lines_to_correct,@linenums);
 7990: 	}
 7991:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7992:     } elsif ($error eq 'missingbubble') {
 7993: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7994: 	$r->print($message);
 7995: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7996: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7997: 
 7998: 	# The form field scantron_questions is actually a list of line numbers not
 7999: 	# a list of question numbers. Therefore:
 8000: 	#
 8001: 	
 8002: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8003:                                                 $respnumlookup,$startline);
 8004: 
 8005: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8006: 		  $line_list.'" />');
 8007: 	foreach my $question (@{$arg}) {
 8008: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8009:                                                    $scan_record, $error,
 8010:                                                    $randomorder,$randompick,
 8011:                                                    $respnumlookup,$startline);
 8012:             push(@lines_to_correct,@linenums);
 8013: 	}
 8014:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8015:     } else {
 8016: 	$r->print("\n<ul>");
 8017:     }
 8018:     $r->print("\n</li></ul>");
 8019: }
 8020: 
 8021: sub verify_bubbles_checked {
 8022:     my (@ansnums) = @_;
 8023:     my $ansnumstr = join('","',@ansnums);
 8024:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8025:     &js_escape(\$warning);
 8026:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8027: function verify_bubble_radio(form) {
 8028:     var ansnumArray = new Array ("$ansnumstr");
 8029:     var need_bubble_count = 0;
 8030:     for (var i=0; i<ansnumArray.length; i++) {
 8031:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8032:             var bubble_picked = 0; 
 8033:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8034:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8035:                     bubble_picked = 1;
 8036:                 }
 8037:             }
 8038:             if (bubble_picked == 0) {
 8039:                 need_bubble_count ++;
 8040:             }
 8041:         }
 8042:     }
 8043:     if (need_bubble_count) {
 8044:         alert("$warning");
 8045:         return;
 8046:     }
 8047:     form.submit(); 
 8048: }
 8049: ENDSCRIPT
 8050:     return $output;
 8051: }
 8052: 
 8053: =pod
 8054: 
 8055: =item  questions_to_line_list
 8056: 
 8057: Converts a list of questions into a string of comma separated
 8058: line numbers in the answer sheet used by the questions.  This is
 8059: used to fill in the scantron_questions form field.
 8060: 
 8061:   Arguments:
 8062:      questions    - Reference to an array of questions.
 8063:      randomorder  - True if randomorder in use.
 8064:      randompick   - True if randompick in use.
 8065:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8066:                      for current line to question number used for same question
 8067:                      in "Master Seqence" (as seen by Course Coordinator).
 8068:      startline    - Reference to hash where key is question number (0 is first)
 8069:                     and key is number of first bubble line for current student
 8070:                     or code-based randompick and/or randomorder.
 8071: 
 8072: =cut
 8073: 
 8074: 
 8075: sub questions_to_line_list {
 8076:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8077:     my @lines;
 8078: 
 8079:     foreach my $item (@{$questions}) {
 8080:         my $question = $item;
 8081:         my ($first,$count,$last);
 8082:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8083:             $question = $1;
 8084:             my $subquestion = $2;
 8085:             my $responsenum = $question-1;
 8086:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8087:                 $responsenum = $respnumlookup->{$question-1};
 8088:                 if (ref($startline) eq 'HASH') {
 8089:                     $first = $startline->{$question-1} + 1;
 8090:                 }
 8091:             } else {
 8092:                 $first = $first_bubble_line{$responsenum} + 1;
 8093:             }
 8094:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8095:             my $subcount = 1;
 8096:             while ($subcount<$subquestion) {
 8097:                 $first += $subans[$subcount-1];
 8098:                 $subcount ++;
 8099:             }
 8100:             $count = $subans[$subquestion-1];
 8101:         } else {
 8102:             my $responsenum = $question-1;
 8103:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8104:                 $responsenum = $respnumlookup->{$question-1};
 8105:                 if (ref($startline) eq 'HASH') {
 8106:                     $first = $startline->{$question-1} + 1;
 8107:                 }
 8108:             } else {
 8109:                 $first = $first_bubble_line{$responsenum} + 1;
 8110:             }
 8111:             $count   = $bubble_lines_per_response{$responsenum};
 8112:         }
 8113:         $last = $first+$count-1;
 8114:         push(@lines, ($first..$last));
 8115:     }
 8116:     return join(',', @lines);
 8117: }
 8118: 
 8119: =pod 
 8120: 
 8121: =item prompt_for_corrections
 8122: 
 8123: Prompts for a potentially multiline correction to the
 8124: user's bubbling (factors out common code from scantron_get_correction
 8125: for multi and missing bubble cases).
 8126: 
 8127:  Arguments:
 8128:    $r           - Apache request object.
 8129:    $question    - The question number to prompt for.
 8130:    $scan_config - The scantron file configuration hash.
 8131:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8132:    $error       - Type of error
 8133:    $randomorder - True if randomorder in use.
 8134:    $randompick  - True if randompick in use.
 8135:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8136:                     for current line to question number used for same question
 8137:                     in "Master Seqence" (as seen by Course Coordinator).
 8138:    $startline   - Reference to hash where key is question number (0 is first)
 8139:                   and value is number of first bubble line for current student
 8140:                   or code-based randompick and/or randomorder.
 8141: 
 8142:  Implicit inputs:
 8143:    %bubble_lines_per_response   - Starting line numbers for each question.
 8144:                                   Numbered from 0 (but question numbers are from
 8145:                                   1.
 8146:    %first_bubble_line           - Starting bubble line for each question.
 8147:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8148:                                   type problems render as separate sub-questions, 
 8149:                                   in exam mode. This hash contains a 
 8150:                                   comma-separated list of the lines per 
 8151:                                   sub-question.
 8152:    %responsetype_per_response   - essayresponse, formularesponse,
 8153:                                   stringresponse, imageresponse, reactionresponse,
 8154:                                   and organicresponse type problem parts can have
 8155:                                   multiple lines per response if the weight
 8156:                                   assigned exceeds 10.  In this case, only
 8157:                                   one bubble per line is permitted, but more 
 8158:                                   than one line might contain bubbles, e.g.
 8159:                                   bubbling of: line 1 - J, line 2 - J, 
 8160:                                   line 3 - B would assign 22 points.  
 8161: 
 8162: =cut
 8163: 
 8164: sub prompt_for_corrections {
 8165:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8166:         $randompick, $respnumlookup, $startline) = @_;
 8167:     my ($current_line,$lines);
 8168:     my @linenums;
 8169:     my $questionnum = $question;
 8170:     my ($first,$responsenum);
 8171:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8172:         $question = $1;
 8173:         my $subquestion = $2;
 8174:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8175:             $responsenum = $respnumlookup->{$question-1};
 8176:             if (ref($startline) eq 'HASH') {
 8177:                 $first = $startline->{$question-1};
 8178:             }
 8179:         } else {
 8180:             $responsenum = $question-1;
 8181:             $first = $first_bubble_line{$responsenum};
 8182:         }
 8183:         $current_line = $first + 1 ;
 8184:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8185:         my $subcount = 1;
 8186:         while ($subcount<$subquestion) {
 8187:             $current_line += $subans[$subcount-1];
 8188:             $subcount ++;
 8189:         }
 8190:         $lines = $subans[$subquestion-1];
 8191:     } else {
 8192:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8193:             $responsenum = $respnumlookup->{$question-1};
 8194:             if (ref($startline) eq 'HASH') {
 8195:                 $first = $startline->{$question-1};
 8196:             }
 8197:         } else {
 8198:             $responsenum = $question-1;
 8199:             $first = $first_bubble_line{$responsenum};
 8200:         }
 8201:         $current_line = $first + 1;
 8202:         $lines        = $bubble_lines_per_response{$responsenum};
 8203:     }
 8204:     if ($lines > 1) {
 8205:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8206:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8207:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8208:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8209:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8210:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8211:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8212:             $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 />');
 8213:         } else {
 8214:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8215:         }
 8216:     }
 8217:     for (my $i =0; $i < $lines; $i++) {
 8218:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8219: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8220: 	        		  $questionnum,$error,split('', $selected));
 8221:         push(@linenums,$current_line);
 8222: 	$current_line++;
 8223:     }
 8224:     if ($lines > 1) {
 8225: 	$r->print("<hr /><br />");
 8226:     }
 8227:     return @linenums;
 8228: }
 8229: 
 8230: =pod
 8231: 
 8232: =item scantron_bubble_selector
 8233:   
 8234:    Generates the html radiobuttons to correct a single bubble line
 8235:    possibly showing the existing the selected bubbles if known
 8236: 
 8237:  Arguments:
 8238:     $r           - Apache request object
 8239:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8240:     $line        - Number of the line being displayed.
 8241:     $questionnum - Question number (may include subquestion)
 8242:     $error       - Type of error.
 8243:     @selected    - Array of bubbles picked on this line.
 8244: 
 8245: =cut
 8246: 
 8247: sub scantron_bubble_selector {
 8248:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8249:     my $max=$$scan_config{'Qlength'};
 8250: 
 8251:     my $scmode=$$scan_config{'Qon'};
 8252:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8253:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8254:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8255:             $max=$$scan_config{'BubblesPerRow'};
 8256:             if (($scmode eq 'number') && ($max > 10)) {
 8257:                 $max = 10;
 8258:             } elsif (($scmode eq 'letter') && $max > 26) {
 8259:                 $max = 26;
 8260:             }
 8261:         } else {
 8262:             $max = 10;
 8263:         }
 8264:     }
 8265: 
 8266:     my @alphabet=('A'..'Z');
 8267:     $r->print(&Apache::loncommon::start_data_table().
 8268:               &Apache::loncommon::start_data_table_row());
 8269:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8270:     for (my $i=0;$i<$max+1;$i++) {
 8271: 	$r->print("\n".'<td align="center">');
 8272: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8273: 	else { $r->print('&nbsp;'); }
 8274: 	$r->print('</td>');
 8275:     }
 8276:     $r->print(&Apache::loncommon::end_data_table_row().
 8277:               &Apache::loncommon::start_data_table_row());
 8278:     for (my $i=0;$i<$max;$i++) {
 8279: 	$r->print("\n".
 8280: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8281: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8282:     }
 8283:     my $nobub_checked = ' ';
 8284:     if ($error eq 'missingbubble') {
 8285:         $nobub_checked = ' checked = "checked" ';
 8286:     }
 8287:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8288: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8289:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8290:               $line.'" value="'.$questionnum.'" /></td>');
 8291:     $r->print(&Apache::loncommon::end_data_table_row().
 8292:               &Apache::loncommon::end_data_table());
 8293: }
 8294: 
 8295: =pod
 8296: 
 8297: =item num_matches
 8298: 
 8299:    Counts the number of characters that are the same between the two arguments.
 8300: 
 8301:  Arguments:
 8302:    $orig - CODE from the scanline
 8303:    $code - CODE to match against
 8304: 
 8305:  Returns:
 8306:    $count - integer count of the number of same characters between the
 8307:             two arguments
 8308: 
 8309: =cut
 8310: 
 8311: sub num_matches {
 8312:     my ($orig,$code) = @_;
 8313:     my @code=split(//,$code);
 8314:     my @orig=split(//,$orig);
 8315:     my $same=0;
 8316:     for (my $i=0;$i<scalar(@code);$i++) {
 8317: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8318:     }
 8319:     return $same;
 8320: }
 8321: 
 8322: =pod
 8323: 
 8324: =item scantron_get_closely_matching_CODEs
 8325: 
 8326:    Cycles through all CODEs and finds the set that has the greatest
 8327:    number of same characters as the provided CODE
 8328: 
 8329:  Arguments:
 8330:    $allcodes - hash ref returned by &get_codes()
 8331:    $CODE     - CODE from the current scanline
 8332: 
 8333:  Returns:
 8334:    2 element list
 8335:     - first elements is number of how closely matching the best fit is 
 8336:       (5 means best set has 5 matching characters)
 8337:     - second element is an arrary ref containing the set of valid CODEs
 8338:       that best fit the passed in CODE
 8339: 
 8340: =cut
 8341: 
 8342: sub scantron_get_closely_matching_CODEs {
 8343:     my ($allcodes,$CODE)=@_;
 8344:     my @CODEs;
 8345:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8346: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8347:     }
 8348: 
 8349:     return ($#CODEs,$CODEs[-1]);
 8350: }
 8351: 
 8352: =pod
 8353: 
 8354: =item get_codes
 8355: 
 8356:    Builds a hash which has keys of all of the valid CODEs from the selected
 8357:    set of remembered CODEs.
 8358: 
 8359:  Arguments:
 8360:   $old_name - name of the set of remembered CODEs
 8361:   $cdom     - domain of the course
 8362:   $cnum     - internal course name
 8363: 
 8364:  Returns:
 8365:   %allcodes - keys are the valid CODEs, values are all 1
 8366: 
 8367: =cut
 8368: 
 8369: sub get_codes {
 8370:     my ($old_name, $cdom, $cnum) = @_;
 8371:     if (!$old_name) {
 8372: 	$old_name=$env{'form.scantron_CODElist'};
 8373:     }
 8374:     if (!$cdom) {
 8375: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8376:     }
 8377:     if (!$cnum) {
 8378: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8379:     }
 8380:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8381: 				    $cdom,$cnum);
 8382:     my %allcodes;
 8383:     if ($result{"type\0$old_name"} eq 'number') {
 8384: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8385:     } else {
 8386: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8387:     }
 8388:     return %allcodes;
 8389: }
 8390: 
 8391: =pod
 8392: 
 8393: =item scantron_validate_CODE
 8394: 
 8395:    Validates all scanlines in the selected file to not have any
 8396:    invalid or underspecified CODEs and that none of the codes are
 8397:    duplicated if this was requested.
 8398: 
 8399: =cut
 8400: 
 8401: sub scantron_validate_CODE {
 8402:     my ($r,$currentphase) = @_;
 8403:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8404:     if ($scantron_config{'CODElocation'} &&
 8405: 	$scantron_config{'CODEstart'} &&
 8406: 	$scantron_config{'CODElength'}) {
 8407: 	if (!defined($env{'form.scantron_CODElist'})) {
 8408: 	    &FIXME_blow_up()
 8409: 	}
 8410:     } else {
 8411: 	return (0,$currentphase+1);
 8412:     }
 8413:     
 8414:     my %usedCODEs;
 8415: 
 8416:     my %allcodes=&get_codes();
 8417: 
 8418:     my $nav_error;
 8419:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8420:     if ($nav_error) {
 8421:         $r->print(&navmap_errormsg());
 8422:         return(1,$currentphase);
 8423:     }
 8424: 
 8425:     my ($scanlines,$scan_data)=&scantron_getfile();
 8426:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8427: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8428: 	if ($line=~/^[\s\cz]*$/) { next; }
 8429: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8430: 						 $scan_data);
 8431: 	my $CODE=$$scan_record{'scantron.CODE'};
 8432: 	my $error=0;
 8433: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8434: 	    &scantron_get_correction($r,$i,$scan_record,
 8435: 				     \%scantron_config,
 8436: 				     $line,'incorrectCODE',\%allcodes);
 8437: 	    return(1,$currentphase);
 8438: 	}
 8439: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8440: 	    && !$$scan_record{'scantron.useCODE'}) {
 8441: 	    &scantron_get_correction($r,$i,$scan_record,
 8442: 				     \%scantron_config,
 8443: 				     $line,'incorrectCODE',\%allcodes);
 8444: 	    return(1,$currentphase);
 8445: 	}
 8446: 	if (exists($usedCODEs{$CODE}) 
 8447: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8448: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8449: 	    &scantron_get_correction($r,$i,$scan_record,
 8450: 				     \%scantron_config,
 8451: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8452: 	    return(1,$currentphase);
 8453: 	}
 8454: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8455:     }
 8456:     return (0,$currentphase+1);
 8457: }
 8458: 
 8459: =pod
 8460: 
 8461: =item scantron_validate_doublebubble
 8462: 
 8463:    Validates all scanlines in the selected file to not have any
 8464:    bubble lines with multiple bubbles marked.
 8465: 
 8466: =cut
 8467: 
 8468: sub scantron_validate_doublebubble {
 8469:     my ($r,$currentphase) = @_;
 8470:     #get student info
 8471:     my $classlist=&Apache::loncoursedata::get_classlist();
 8472:     my %idmap=&username_to_idmap($classlist);
 8473:     my (undef,undef,$sequence)=
 8474:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8475: 
 8476:     #get scantron line setup
 8477:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8478:     my ($scanlines,$scan_data)=&scantron_getfile();
 8479: 
 8480:     my $navmap = Apache::lonnavmaps::navmap->new();
 8481:     unless (ref($navmap)) {
 8482:         $r->print(&navmap_errormsg());
 8483:         return(1,$currentphase);
 8484:     }
 8485:     my $map=$navmap->getResourceByUrl($sequence);
 8486:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8487:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8488:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8489:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8490: 
 8491:     my $nav_error;
 8492:     if (ref($map)) {
 8493:         $randomorder = $map->randomorder();
 8494:         $randompick = $map->randompick();
 8495:         if ($randomorder || $randompick) {
 8496:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8497:             if ($nav_error) {
 8498:                 $r->print(&navmap_errormsg());
 8499:                 return(1,$currentphase);
 8500:             }
 8501:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8502:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8503:         }
 8504:     } else {
 8505:         $r->print(&navmap_errormsg());
 8506:         return(1,$currentphase);
 8507:     }
 8508: 
 8509:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8510:     if ($nav_error) {
 8511:         $r->print(&navmap_errormsg());
 8512:         return(1,$currentphase);
 8513:     }
 8514: 
 8515:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8516: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8517: 	if ($line=~/^[\s\cz]*$/) { next; }
 8518: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8519: 						 $scan_data,undef,\%idmap,$randomorder,
 8520:                                                  $randompick,$sequence,\@master_seq,
 8521:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8522:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8523: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8524: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8525: 				 'doublebubble',
 8526: 				 $$scan_record{'scantron.doubleerror'},
 8527:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8528:     	return (1,$currentphase);
 8529:     }
 8530:     return (0,$currentphase+1);
 8531: }
 8532: 
 8533: 
 8534: sub scantron_get_maxbubble {
 8535:     my ($nav_error,$scantron_config) = @_;
 8536:     if (defined($env{'form.scantron_maxbubble'}) &&
 8537: 	$env{'form.scantron_maxbubble'}) {
 8538: 	&restore_bubble_lines();
 8539: 	return $env{'form.scantron_maxbubble'};
 8540:     }
 8541: 
 8542:     my (undef, undef, $sequence) =
 8543: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8544: 
 8545:     my $navmap=Apache::lonnavmaps::navmap->new();
 8546:     unless (ref($navmap)) {
 8547:         if (ref($nav_error)) {
 8548:             $$nav_error = 1;
 8549:         }
 8550:         return;
 8551:     }
 8552:     my $map=$navmap->getResourceByUrl($sequence);
 8553:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8554:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8555: 
 8556:     &Apache::lonxml::clear_problem_counter();
 8557: 
 8558:     my $uname       = $env{'user.name'};
 8559:     my $udom        = $env{'user.domain'};
 8560:     my $cid         = $env{'request.course.id'};
 8561:     my $total_lines = 0;
 8562:     %bubble_lines_per_response = ();
 8563:     %first_bubble_line         = ();
 8564:     %subdivided_bubble_lines   = ();
 8565:     %responsetype_per_response = ();
 8566:     %masterseq_id_responsenum  = ();
 8567: 
 8568:     my $response_number = 0;
 8569:     my $bubble_line     = 0;
 8570:     foreach my $resource (@resources) {
 8571:         my $resid = $resource->id();
 8572:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8573:                                                           $udom,undef,$bubbles_per_row);
 8574:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8575: 	    foreach my $part_id (@{$parts}) {
 8576:                 my $lines;
 8577: 
 8578: 	        # TODO - make this a persistent hash not an array.
 8579: 
 8580:                 # optionresponse, matchresponse and rankresponse type items 
 8581:                 # render as separate sub-questions in exam mode.
 8582:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8583:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8584:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8585:                     my ($numbub,$numshown);
 8586:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8587:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8588:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8589:                         }
 8590:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8591:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8592:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8593:                         }
 8594:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8595:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8596:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8597:                         }
 8598:                     }
 8599:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8600:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8601:                     }
 8602:                     my $bubbles_per_row =
 8603:                         &bubblesheet_bubbles_per_row($scantron_config);
 8604:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8605:                     if (($numbub % $bubbles_per_row) != 0) {
 8606:                         $inner_bubble_lines++;
 8607:                     }
 8608:                     for (my $i=0; $i<$numshown; $i++) {
 8609:                         $subdivided_bubble_lines{$response_number} .= 
 8610:                             $inner_bubble_lines.',';
 8611:                     }
 8612:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8613:                     $lines = $numshown * $inner_bubble_lines;
 8614:                 } else {
 8615:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8616:                 }
 8617: 
 8618:                 $first_bubble_line{$response_number} = $bubble_line;
 8619: 	        $bubble_lines_per_response{$response_number} = $lines;
 8620:                 $responsetype_per_response{$response_number} = 
 8621:                     $analysis->{$part_id.'.type'};
 8622:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8623: 	        $response_number++;
 8624: 
 8625: 	        $bubble_line +=  $lines;
 8626: 	        $total_lines +=  $lines;
 8627: 	    }
 8628:         }
 8629:     }
 8630:     &Apache::lonnet::delenv('scantron.');
 8631: 
 8632:     &save_bubble_lines();
 8633:     $env{'form.scantron_maxbubble'} =
 8634: 	$total_lines;
 8635:     return $env{'form.scantron_maxbubble'};
 8636: }
 8637: 
 8638: sub bubblesheet_bubbles_per_row {
 8639:     my ($scantron_config) = @_;
 8640:     my $bubbles_per_row;
 8641:     if (ref($scantron_config) eq 'HASH') {
 8642:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8643:     }
 8644:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8645:         $bubbles_per_row = 10;
 8646:     }
 8647:     return $bubbles_per_row;
 8648: }
 8649: 
 8650: sub scantron_validate_missingbubbles {
 8651:     my ($r,$currentphase) = @_;
 8652:     #get student info
 8653:     my $classlist=&Apache::loncoursedata::get_classlist();
 8654:     my %idmap=&username_to_idmap($classlist);
 8655:     my (undef,undef,$sequence)=
 8656:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8657: 
 8658:     #get scantron line setup
 8659:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8660:     my ($scanlines,$scan_data)=&scantron_getfile();
 8661: 
 8662:     my $navmap = Apache::lonnavmaps::navmap->new();
 8663:     unless (ref($navmap)) {
 8664:         $r->print(&navmap_errormsg());
 8665:         return(1,$currentphase);
 8666:     }
 8667: 
 8668:     my $map=$navmap->getResourceByUrl($sequence);
 8669:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8670:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8671:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8672:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8673: 
 8674:     my $nav_error;
 8675:     if (ref($map)) {
 8676:         $randomorder = $map->randomorder();
 8677:         $randompick = $map->randompick();
 8678:         if ($randomorder || $randompick) {
 8679:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8680:             if ($nav_error) {
 8681:                 $r->print(&navmap_errormsg());
 8682:                 return(1,$currentphase);
 8683:             }
 8684:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8685:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8686:         }
 8687:     } else {
 8688:         $r->print(&navmap_errormsg());
 8689:         return(1,$currentphase);
 8690:     }
 8691: 
 8692: 
 8693:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8694:     if ($nav_error) {
 8695:         $r->print(&navmap_errormsg());
 8696:         return(1,$currentphase);
 8697:     }
 8698: 
 8699:     if (!$max_bubble) { $max_bubble=2**31; }
 8700:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8701: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8702: 	if ($line=~/^[\s\cz]*$/) { next; }
 8703:         my $scan_record =
 8704:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8705:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8706:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8707:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8708: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8709: 	my @to_correct;
 8710: 	
 8711: 	# Probably here's where the error is...
 8712: 
 8713: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8714:             my $lastbubble;
 8715:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8716:                 my $question = $1;
 8717:                 my $subquestion = $2;
 8718:                 my ($first,$responsenum);
 8719:                 if ($randomorder || $randompick) {
 8720:                     $responsenum = $respnumlookup{$question-1};
 8721:                     $first = $startline{$question-1};
 8722:                 } else {
 8723:                     $responsenum = $question-1;
 8724:                     $first = $first_bubble_line{$responsenum};
 8725:                 }
 8726:                 if (!defined($first)) { next; }
 8727:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8728:                 my $subcount = 1;
 8729:                 while ($subcount<$subquestion) {
 8730:                     $first += $subans[$subcount-1];
 8731:                     $subcount ++;
 8732:                 }
 8733:                 my $count = $subans[$subquestion-1];
 8734:                 $lastbubble = $first + $count;
 8735:             } else {
 8736:                 my ($first,$responsenum);
 8737:                 if ($randomorder || $randompick) {
 8738:                     $responsenum = $respnumlookup{$missing-1};
 8739:                     $first = $startline{$missing-1};
 8740:                 } else {
 8741:                     $responsenum = $missing-1;
 8742:                     $first = $first_bubble_line{$responsenum};
 8743:                 }
 8744:                 if (!defined($first)) { next; }
 8745:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8746:             }
 8747:             if ($lastbubble > $max_bubble) { next; }
 8748: 	    push(@to_correct,$missing);
 8749: 	}
 8750: 	if (@to_correct) {
 8751: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8752: 				     $line,'missingbubble',\@to_correct,
 8753:                                      $randomorder,$randompick,\%respnumlookup,
 8754:                                      \%startline);
 8755: 	    return (1,$currentphase);
 8756: 	}
 8757: 
 8758:     }
 8759:     return (0,$currentphase+1);
 8760: }
 8761: 
 8762: sub hand_bubble_option {
 8763:     my (undef, undef, $sequence) =
 8764:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8765:     return if ($sequence eq '');
 8766:     my $navmap = Apache::lonnavmaps::navmap->new();
 8767:     unless (ref($navmap)) {
 8768:         return;
 8769:     }
 8770:     my $needs_hand_bubbles;
 8771:     my $map=$navmap->getResourceByUrl($sequence);
 8772:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8773:     foreach my $res (@resources) {
 8774:         if (ref($res)) {
 8775:             if ($res->is_problem()) {
 8776:                 my $partlist = $res->parts();
 8777:                 foreach my $part (@{ $partlist }) {
 8778:                     my @types = $res->responseType($part);
 8779:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8780:                         $needs_hand_bubbles = 1;
 8781:                         last;
 8782:                     }
 8783:                 }
 8784:             }
 8785:         }
 8786:     }
 8787:     if ($needs_hand_bubbles) {
 8788:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8789:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8790:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8791:                &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 />').
 8792:                '<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;'.
 8793:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8794:     }
 8795:     return;
 8796: }
 8797: 
 8798: sub scantron_process_students {
 8799:     my ($r,$symb) = @_;
 8800: 
 8801:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8802:     if (!$symb) {
 8803: 	return '';
 8804:     }
 8805:     my $default_form_data=&defaultFormData($symb);
 8806: 
 8807:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8808:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8809:     my ($scanlines,$scan_data)=&scantron_getfile();
 8810:     my $classlist=&Apache::loncoursedata::get_classlist();
 8811:     my %idmap=&username_to_idmap($classlist);
 8812:     my $navmap=Apache::lonnavmaps::navmap->new();
 8813:     unless (ref($navmap)) {
 8814:         $r->print(&navmap_errormsg());
 8815:         return '';
 8816:     }
 8817:     my $map=$navmap->getResourceByUrl($sequence);
 8818:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8819:         %grader_randomlists_by_symb);
 8820:     if (ref($map)) {
 8821:         $randomorder = $map->randomorder();
 8822:         $randompick = $map->randompick();
 8823:     } else {
 8824:         $r->print(&navmap_errormsg());
 8825:         return '';
 8826:     }
 8827:     my $nav_error;
 8828:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8829:     if ($randomorder || $randompick) {
 8830:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8831:         if ($nav_error) {
 8832:             $r->print(&navmap_errormsg());
 8833:             return '';
 8834:         }
 8835:     }
 8836:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8837:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8838: 
 8839:     my ($uname,$udom);
 8840:     my $result= <<SCANTRONFORM;
 8841: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8842:   <input type="hidden" name="command" value="scantron_configphase" />
 8843:   $default_form_data
 8844: SCANTRONFORM
 8845:     $r->print($result);
 8846: 
 8847:     my @delayqueue;
 8848:     my (%completedstudents,%scandata);
 8849:     
 8850:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8851:     my $count=&get_todo_count($scanlines,$scan_data);
 8852:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8853:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8854:     $r->print('<br />');
 8855:     my $start=&Time::HiRes::time();
 8856:     my $i=-1;
 8857:     my $started;
 8858: 
 8859:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8860:     if ($nav_error) {
 8861:         $r->print(&navmap_errormsg());
 8862:         return '';
 8863:     }
 8864: 
 8865:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8866:     # the user and return.
 8867: 
 8868:     if ($ssi_error) {
 8869: 	$r->print("</form>");
 8870: 	&ssi_print_error($r);
 8871:         &Apache::lonnet::remove_lock($lock);
 8872: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8873:     }
 8874: 
 8875:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8876:     my $numletts = scalar(keys(%lettdig));
 8877:     my %orderedforcode;
 8878: 
 8879:     while ($i<$scanlines->{'count'}) {
 8880:  	($uname,$udom)=('','');
 8881:  	$i++;
 8882:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8883:  	if ($line=~/^[\s\cz]*$/) { next; }
 8884: 	if ($started) {
 8885: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8886: 	}
 8887: 	$started=1;
 8888:         my %respnumlookup = ();
 8889:         my %startline = ();
 8890:         my $total;
 8891:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8892:  						 $scan_data,undef,\%idmap,$randomorder,
 8893:                                                  $randompick,$sequence,\@master_seq,
 8894:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8895:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8896:                                                  \$total);
 8897:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8898:  					      \%idmap,$i)) {
 8899:   	    &scantron_add_delay(\@delayqueue,$line,
 8900:  				'Unable to find a student that matches',1);
 8901:  	    next;
 8902:   	}
 8903:  	if (exists $completedstudents{$uname}) {
 8904:  	    &scantron_add_delay(\@delayqueue,$line,
 8905:  				'Student '.$uname.' has multiple sheets',2);
 8906:  	    next;
 8907:  	}
 8908:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8909:         my $user = $uname.':'.$usec;
 8910:   	($uname,$udom)=split(/:/,$uname);
 8911: 
 8912:         my $scancode;
 8913:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8914:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8915:             $scancode = $scan_record->{'scantron.CODE'};
 8916:         } else {
 8917:             $scancode = '';
 8918:         }
 8919: 
 8920:         my @mapresources = @resources;
 8921:         if ($randomorder || $randompick) {
 8922:             @mapresources =
 8923:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8924:                              \%orderedforcode);
 8925:         }
 8926:         my (%partids_by_symb,$res_error);
 8927:         foreach my $resource (@mapresources) {
 8928:             my $ressymb;
 8929:             if (ref($resource)) {
 8930:                 $ressymb = $resource->symb();
 8931:             } else {
 8932:                 $res_error = 1;
 8933:                 last;
 8934:             }
 8935:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8936:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8937:                 my $currcode;
 8938:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8939:                     $currcode = $scancode;
 8940:                 }
 8941:                 my ($analysis,$parts) =
 8942:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8943:                                               $uname,$udom,undef,$bubbles_per_row,
 8944:                                               $currcode);
 8945:                 $partids_by_symb{$ressymb} = $parts;
 8946:             } else {
 8947:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8948:             }
 8949:         }
 8950: 
 8951:         if ($res_error) {
 8952:             &scantron_add_delay(\@delayqueue,$line,
 8953:                                 'An error occurred while grading student '.$uname,2);
 8954:             next;
 8955:         }
 8956: 
 8957: 	&Apache::lonxml::clear_problem_counter();
 8958:   	&Apache::lonnet::appenv($scan_record);
 8959: 
 8960: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8961: 	    &scantron_putfile($scanlines,$scan_data);
 8962: 	}
 8963: 	
 8964:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8965:                                    \@mapresources,\%partids_by_symb,
 8966:                                    $bubbles_per_row,$randomorder,$randompick,
 8967:                                    \%respnumlookup,\%startline) 
 8968:             eq 'ssi_error') {
 8969:             $ssi_error = 0; # So end of handler error message does not trigger.
 8970:             $r->print("</form>");
 8971:             &ssi_print_error($r);
 8972:             &Apache::lonnet::remove_lock($lock);
 8973:             return '';      # Why return ''?  Beats me.
 8974:         }
 8975: 
 8976:         if (($scancode) && ($randomorder || $randompick)) {
 8977:             my $parmresult =
 8978:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8979:                                                        '0_examcode',2,$scancode,
 8980:                                                        'string_examcode',$uname,
 8981:                                                        $udom);
 8982:         }
 8983: 	$completedstudents{$uname}={'line'=>$line};
 8984:         if ($env{'form.verifyrecord'}) {
 8985:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8986:             if ($randompick) {
 8987:                 if ($total) {
 8988:                     $lastpos = $total*$scantron_config{'Qlength'};
 8989:                 }
 8990:             }
 8991: 
 8992:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8993:             chomp($studentdata);
 8994:             $studentdata =~ s/\r$//;
 8995:             my $studentrecord = '';
 8996:             my $counter = -1;
 8997:             foreach my $resource (@mapresources) {
 8998:                 my $ressymb = $resource->symb();
 8999:                 ($counter,my $recording) =
 9000:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9001:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9002:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9003:                                              $randompick,\%respnumlookup,\%startline);
 9004:                 $studentrecord .= $recording;
 9005:             }
 9006:             if ($studentrecord ne $studentdata) {
 9007:                 &Apache::lonxml::clear_problem_counter();
 9008:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9009:                                            \@mapresources,\%partids_by_symb,
 9010:                                            $bubbles_per_row,$randomorder,$randompick,
 9011:                                            \%respnumlookup,\%startline)
 9012:                     eq 'ssi_error') {
 9013:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9014:                     $r->print("</form>");
 9015:                     &ssi_print_error($r);
 9016:                     &Apache::lonnet::remove_lock($lock);
 9017:                     delete($completedstudents{$uname});
 9018:                     return '';
 9019:                 }
 9020:                 $counter = -1;
 9021:                 $studentrecord = '';
 9022:                 foreach my $resource (@mapresources) {
 9023:                     my $ressymb = $resource->symb();
 9024:                     ($counter,my $recording) =
 9025:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9026:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9027:                                                  \%scantron_config,\%lettdig,$numletts,
 9028:                                                  $randomorder,$randompick,\%respnumlookup,
 9029:                                                  \%startline);
 9030:                     $studentrecord .= $recording;
 9031:                 }
 9032:                 if ($studentrecord ne $studentdata) {
 9033:                     $r->print('<p><span class="LC_warning">');
 9034:                     if ($scancode eq '') {
 9035:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9036:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9037:                     } else {
 9038:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9039:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9040:                     }
 9041:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9042:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9043:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9044:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9045:                               &Apache::loncommon::start_data_table_row().
 9046:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9047:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9048:                               &Apache::loncommon::end_data_table_row().
 9049:                               &Apache::loncommon::start_data_table_row().
 9050:                               '<td>'.&mt('Stored submissions').'</td>'.
 9051:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9052:                               &Apache::loncommon::end_data_table_row().
 9053:                               &Apache::loncommon::end_data_table().'</p>');
 9054:                 } else {
 9055:                     $r->print('<br /><span class="LC_warning">'.
 9056:                              &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 />'.
 9057:                              &mt("As a consequence, this user's submission history records two tries.").
 9058:                                  '</span><br />');
 9059:                 }
 9060:             }
 9061:         }
 9062:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9063:     } continue {
 9064: 	&Apache::lonxml::clear_problem_counter();
 9065: 	&Apache::lonnet::delenv('scantron.');
 9066:     }
 9067:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9068:     &Apache::lonnet::remove_lock($lock);
 9069: #    my $lasttime = &Time::HiRes::time()-$start;
 9070: #    $r->print("<p>took $lasttime</p>");
 9071: 
 9072:     $r->print("</form>");
 9073:     return '';
 9074: }
 9075: 
 9076: sub graders_resources_pass {
 9077:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9078:         $bubbles_per_row) = @_;
 9079:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9080:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9081:         foreach my $resource (@{$resources}) {
 9082:             my $ressymb = $resource->symb();
 9083:             my ($analysis,$parts) =
 9084:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9085:                                           $env{'user.name'},$env{'user.domain'},
 9086:                                           1,$bubbles_per_row);
 9087:             $grader_partids_by_symb->{$ressymb} = $parts;
 9088:             if (ref($analysis) eq 'HASH') {
 9089:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9090:                     $grader_randomlists_by_symb->{$ressymb} =
 9091:                         $analysis->{'parts_withrandomlist'};
 9092:                 }
 9093:             }
 9094:         }
 9095:     }
 9096:     return;
 9097: }
 9098: 
 9099: =pod
 9100: 
 9101: =item users_order
 9102: 
 9103:   Returns array of resources in current map, ordered based on either CODE,
 9104:   if this is a CODEd exam, or based on student's identity if this is a
 9105:   "NAMEd" exam.
 9106: 
 9107:   Should be used when randomorder and/or randompick applied when the 
 9108:   corresponding exam was printed, prior to students completing bubblesheets 
 9109:   for the version of the exam the student received.
 9110: 
 9111: =cut
 9112: 
 9113: sub users_order  {
 9114:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9115:     my @mapresources;
 9116:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9117:         return @mapresources;
 9118:     }
 9119:     if ($scancode) {
 9120:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9121:             @mapresources = @{$orderedforcode->{$scancode}};
 9122:         } else {
 9123:             $env{'form.CODE'} = $scancode;
 9124:             my $actual_seq =
 9125:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9126:                                                                $master_seq,
 9127:                                                                $user,$scancode,1);
 9128:             if (ref($actual_seq) eq 'ARRAY') {
 9129:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9130:                 if (ref($orderedforcode) eq 'HASH') {
 9131:                     if (@mapresources > 0) {
 9132:                         $orderedforcode->{$scancode} = \@mapresources;
 9133:                     }
 9134:                 }
 9135:             }
 9136:             delete($env{'form.CODE'});
 9137:         }
 9138:     } else {
 9139:         my $actual_seq =
 9140:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9141:                                                            $master_seq,
 9142:                                                            $user,undef,1);
 9143:         if (ref($actual_seq) eq 'ARRAY') {
 9144:             @mapresources =
 9145:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9146:         }
 9147:     }
 9148:     return @mapresources;
 9149: }
 9150: 
 9151: sub grade_student_bubbles {
 9152:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9153:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9154:     my $uselookup = 0;
 9155:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9156:         (ref($startline) eq 'HASH')) {
 9157:         $uselookup = 1;
 9158:     }
 9159: 
 9160:     if (ref($resources) eq 'ARRAY') {
 9161:         my $count = 0;
 9162:         foreach my $resource (@{$resources}) {
 9163:             my $ressymb = $resource->symb();
 9164:             my %form = ('submitted'      => 'scantron',
 9165:                         'grade_target'   => 'grade',
 9166:                         'grade_username' => $uname,
 9167:                         'grade_domain'   => $udom,
 9168:                         'grade_courseid' => $env{'request.course.id'},
 9169:                         'grade_symb'     => $ressymb,
 9170:                         'CODE'           => $scancode
 9171:                        );
 9172:             if ($bubbles_per_row ne '') {
 9173:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9174:             }
 9175:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9176:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9177:             }
 9178:             if (ref($parts) eq 'HASH') {
 9179:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9180:                     foreach my $part (@{$parts->{$ressymb}}) {
 9181:                         if ($uselookup) {
 9182:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9183:                         } else {
 9184:                             $form{'scantron_questnum_start.'.$part} =
 9185:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9186:                         }
 9187:                         $count++;
 9188:                     }
 9189:                 }
 9190:             }
 9191:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9192:             return 'ssi_error' if ($ssi_error);
 9193:             last if (&Apache::loncommon::connection_aborted($r));
 9194:         }
 9195:     }
 9196:     return;
 9197: }
 9198: 
 9199: sub scantron_upload_scantron_data {
 9200:     my ($r,$symb) = @_;
 9201:     my $dom = $env{'request.role.domain'};
 9202:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9203:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9204:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9205:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9206: 							  'domainid',
 9207: 							  'coursename',$dom);
 9208:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9209:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9210:     my $default_form_data=&defaultFormData($symb);
 9211:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9212:     &js_escape(\$nofile_alert);
 9213:     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.");
 9214:     &js_escape(\$nocourseid_alert);
 9215:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9216:     function checkUpload(formname) {
 9217: 	if (formname.upfile.value == "") {
 9218: 	    alert("'.$nofile_alert.'");
 9219: 	    return false;
 9220: 	}
 9221:         if (formname.courseid.value == "") {
 9222:             alert("'.$nocourseid_alert.'");
 9223:             return false;
 9224:         }
 9225: 	formname.submit();
 9226:     }
 9227: 
 9228:     function ToSyllabus() {
 9229:         var cdom = '."'$dom'".';
 9230:         var cnum = document.rules.courseid.value;
 9231:         if (cdom == "" || cdom == null) {
 9232:             return;
 9233:         }
 9234:         if (cnum == "" || cnum == null) {
 9235:            return;
 9236:         }
 9237:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9238:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9239:         return;
 9240:     }
 9241: 
 9242:     '.$formatjs.'
 9243: '));
 9244:     $r->print('
 9245: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9246: 
 9247: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9248: '.$default_form_data.
 9249:   &Apache::lonhtmlcommon::start_pick_box().
 9250:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9251:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9252:   &Apache::lonhtmlcommon::row_closure().
 9253:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9254:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9255:   &Apache::lonhtmlcommon::row_closure().
 9256:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9257:   '<input name="domainid" type="hidden" />'.$domdesc.
 9258:   &Apache::lonhtmlcommon::row_closure());
 9259:     if ($formatoptions) {
 9260:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9261:                   &Apache::lonhtmlcommon::row_closure());
 9262:     }
 9263:     $r->print(
 9264:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9265:   '<input type="file" name="upfile" size="50" />'.
 9266:   &Apache::lonhtmlcommon::row_closure(1).
 9267:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9268: 
 9269: <input name="command" value="scantronupload_save" type="hidden" />
 9270: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9271: </form>
 9272: ');
 9273:     return '';
 9274: }
 9275: 
 9276: sub scantron_upload_dataformat {
 9277:     my ($dom) = @_;
 9278:     my ($formatoptions,$formattitle,$formatjs);
 9279:     $formatjs = <<'END';
 9280: function toggleScantab(form) {
 9281:    return;
 9282: }
 9283: END
 9284:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9285:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9286:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9287:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9288:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9289:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9290:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9291:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9292:                             my ($onclick,$formatextra,$singleline);
 9293:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9294:                             my $count = 0;
 9295:                             foreach my $line (@lines) {
 9296:                                 next if ($line =~ /^#/);
 9297:                                 $singleline = $line;
 9298:                                 $count ++;
 9299:                             }
 9300:                             if ($count > 1) {
 9301:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9302:                                                '<span class="LC_nobreak">'.
 9303:                                                &mt('Bubblesheet type').':&nbsp;'.
 9304:                                                &scantron_scantab().'</span></div>';
 9305:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9306:                                 $formatjs = <<"END";
 9307: function toggleScantab(form) {
 9308:     var divid = 'bubbletype';
 9309:     if (document.getElementById(divid)) {
 9310:         var radioname = 'fileformat';
 9311:         var num = form.elements[radioname].length;
 9312:         if (num) {
 9313:             for (var i=0; i<num; i++) {
 9314:                 if (form.elements[radioname][i].checked) {
 9315:                     var chosen = form.elements[radioname][i].value;
 9316:                     if (chosen == 'dat') {
 9317:                         document.getElementById(divid).style.display = 'none';
 9318:                     } else if (chosen == 'csv') {
 9319:                         document.getElementById(divid).style.display = 'block';
 9320:                     }
 9321:                 }
 9322:             }
 9323:         }
 9324:     }
 9325:     return;
 9326: }
 9327: 
 9328: END
 9329:                             } elsif ($count == 1) {
 9330:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9331:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9332:                             }
 9333:                             $formattitle = &mt('File format');
 9334:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9335:                                              &mt('Plain Text (no delimiters)').
 9336:                                              '</label>'.('&nbsp;'x2).
 9337:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9338:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9339:                         }
 9340:                     }
 9341:                 }
 9342:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9343:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9344:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9345:                         $formattitle = &mt('Bubblesheet type');
 9346:                         $formatoptions = &scantron_scantab();
 9347:                     }
 9348:                 }
 9349:             }
 9350:         }
 9351:     }
 9352:     return ($formatoptions,$formattitle,$formatjs);
 9353: }
 9354: 
 9355: sub scantron_upload_scantron_data_save {
 9356:     my ($r,$symb) = @_;
 9357:     my $doanotherupload=
 9358: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9359: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9360: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9361: 	'</form>'."\n";
 9362:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9363: 	!&Apache::lonnet::allowed('usc',
 9364: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9365: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9366:         unless ($symb) {
 9367: 	    $r->print($doanotherupload);
 9368: 	}
 9369: 	return '';
 9370:     }
 9371:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9372:     my $uploadedfile;
 9373:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9374:     if (length($env{'form.upfile'}) < 2) {
 9375:         $r->print(
 9376:             &Apache::lonhtmlcommon::confirm_success(
 9377:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9378:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9379:     } else {
 9380:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9381:         my $parser;
 9382:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9383:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9384:                 my $is_csv;
 9385:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9386:                 if (@possibles > 1) {
 9387:                     if ($env{'form.fileformat'} eq 'csv') {
 9388:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9389:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9390:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9391:                                     $is_csv = 1;
 9392:                                 }
 9393:                             }
 9394:                         }
 9395:                     }
 9396:                 } elsif (@possibles == 1) {
 9397:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9398:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9399:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9400:                                 $is_csv = 1;
 9401:                             }
 9402:                         }
 9403:                     }
 9404:                 }
 9405:                 if ($is_csv) {
 9406:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9407:                 }
 9408:             }
 9409:         }
 9410:         my $result =
 9411:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9412:                                             $env{'form.courseid'},$env{'form.domainid'});
 9413: 	if ($result =~ m{^/uploaded/}) {
 9414:             $r->print(
 9415:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9416:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9417:                         (length($env{'form.upfile'})-1),
 9418:                         '<span class="LC_filename">'.$result.'</span>'));
 9419:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9420:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9421:                                                        $env{'form.courseid'},$uploadedfile));
 9422: 	} else {
 9423:             $r->print(
 9424:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9425:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9426:                           $result,
 9427: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9428: 	}
 9429:     }
 9430:     if ($symb) {
 9431: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9432:     } else {
 9433: 	$r->print($doanotherupload);
 9434:     }
 9435:     return '';
 9436: }
 9437: 
 9438: sub validate_uploaded_scantron_file {
 9439:     my ($cdom,$cname,$fname) = @_;
 9440:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9441:     my @lines;
 9442:     if ($scanlines ne '-1') {
 9443:         @lines=split("\n",$scanlines,-1);
 9444:     }
 9445:     my $output;
 9446:     if (@lines) {
 9447:         my (%counts,$max_match_format);
 9448:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9449:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9450:         my %idmap = &username_to_idmap($classlist);
 9451:         foreach my $key (keys(%idmap)) {
 9452:             my $lckey = lc($key);
 9453:             $idmap{$lckey} = $idmap{$key};
 9454:         }
 9455:         my %unique_formats;
 9456:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9457:         foreach my $line (@formatlines) {
 9458:             chomp($line);
 9459:             my @config = split(/:/,$line);
 9460:             my $idstart = $config[5];
 9461:             my $idlength = $config[6];
 9462:             if (($idstart ne '') && ($idlength > 0)) {
 9463:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9464:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9465:                 } else {
 9466:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9467:                 }
 9468:             }
 9469:         }
 9470:         foreach my $key (keys(%unique_formats)) {
 9471:             my ($idstart,$idlength) = split(':',$key);
 9472:             %{$counts{$key}} = (
 9473:                                'found'   => 0,
 9474:                                'total'   => 0,
 9475:                               );
 9476:             foreach my $line (@lines) {
 9477:                 next if ($line =~ /^#/);
 9478:                 next if ($line =~ /^[\s\cz]*$/);
 9479:                 my $id = substr($line,$idstart-1,$idlength);
 9480:                 $id = lc($id);
 9481:                 if (exists($idmap{$id})) {
 9482:                     $counts{$key}{'found'} ++;
 9483:                 }
 9484:                 $counts{$key}{'total'} ++;
 9485:             }
 9486:             if ($counts{$key}{'total'}) {
 9487:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9488:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9489:                     $max_match_pct = $percent_match;
 9490:                     $max_match_format = $key;
 9491:                     $found_match_count = $counts{$key}{'found'};
 9492:                     $max_match_count = $counts{$key}{'total'};
 9493:                 }
 9494:             }
 9495:         }
 9496:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9497:             my $format_descs;
 9498:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9499:             for (my $i=0; $i<$numwithformat; $i++) {
 9500:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9501:                 if ($i<$numwithformat-2) {
 9502:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9503:                 } elsif ($i==$numwithformat-2) {
 9504:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9505:                 } elsif ($i==$numwithformat-1) {
 9506:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9507:                 }
 9508:             }
 9509:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9510:             $output .= '<br />';
 9511:             if ($found_match_count == $max_match_count) {
 9512:                 # 100% matching entries
 9513:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9514:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9515:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9516:                 &mt('Comparison of student IDs in the uploaded file with'.
 9517:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9518:                     ' in the file (for the format defined for [_3]).',
 9519:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9520:             } else {
 9521:                 # Not all entries matching? -> Show warning and additional info
 9522:                 $output .=
 9523:                     &Apache::lonhtmlcommon::confirm_success(
 9524:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9525:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9526:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9527:                     &mt('Comparison of student IDs in the uploaded file with'.
 9528:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9529:                         ' in the file (for the format defined for [_3]).',
 9530:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9531:                     '<p class="LC_info">'.
 9532:                     &mt('A low percentage of matches results from one of the following:').
 9533:                     '</p><ul>'.
 9534:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9535:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9536:                                '<i>'.$cdom.'</i>').'</li>'.
 9537:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9538:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9539:                     '</ul>';
 9540:             }
 9541:         }
 9542:     } else {
 9543:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9544:     }
 9545:     return $output;
 9546: }
 9547: 
 9548: sub valid_file {
 9549:     my ($requested_file)=@_;
 9550:     foreach my $filename (sort(&scantron_filenames())) {
 9551: 	if ($requested_file eq $filename) { return 1; }
 9552:     }
 9553:     return 0;
 9554: }
 9555: 
 9556: sub scantron_download_scantron_data {
 9557:     my ($r,$symb) = @_;
 9558:     my $default_form_data=&defaultFormData($symb);
 9559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9561:     my $file=$env{'form.scantron_selectfile'};
 9562:     if (! &valid_file($file)) {
 9563: 	$r->print('
 9564: 	<p>
 9565: 	    '.&mt('The requested filename was invalid.').'
 9566:         </p>
 9567: ');
 9568: 	return;
 9569:     }
 9570:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9571:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9572:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9573:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9574:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9575:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9576:     $r->print('
 9577:     <p>
 9578: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9579: 	      '<a href="'.$orig.'">','</a>').'
 9580:     </p>
 9581:     <p>
 9582: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9583: 	      '<a href="'.$corrected.'">','</a>').'
 9584:     </p>
 9585:     <p>
 9586: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9587: 	      '<a href="'.$skipped.'">','</a>').'
 9588:     </p>
 9589: ');
 9590:     return '';
 9591: }
 9592: 
 9593: sub checkscantron_results {
 9594:     my ($r,$symb) = @_;
 9595:     if (!$symb) {return '';}
 9596:     my $cid = $env{'request.course.id'};
 9597:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9598:     my $numletts = scalar(keys(%lettdig));
 9599:     my $cnum = $env{'course.'.$cid.'.num'};
 9600:     my $cdom = $env{'course.'.$cid.'.domain'};
 9601:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9602:     my %record;
 9603:     my %scantron_config =
 9604:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9605:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9606:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9607:     my $classlist=&Apache::loncoursedata::get_classlist();
 9608:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9609:     my $navmap=Apache::lonnavmaps::navmap->new();
 9610:     unless (ref($navmap)) {
 9611:         $r->print(&navmap_errormsg());
 9612:         return '';
 9613:     }
 9614:     my $map=$navmap->getResourceByUrl($sequence);
 9615:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9616:         %grader_randomlists_by_symb,%orderedforcode);
 9617:     if (ref($map)) {
 9618:         $randomorder=$map->randomorder();
 9619:         $randompick=$map->randompick();
 9620:     }
 9621:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9622:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9623:     if ($nav_error) {
 9624:         $r->print(&navmap_errormsg());
 9625:         return '';
 9626:     }
 9627:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9628:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9629:     my ($uname,$udom);
 9630:     my (%scandata,%lastname,%bylast);
 9631:     $r->print('
 9632: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9633: 
 9634:     my @delayqueue;
 9635:     my %completedstudents;
 9636: 
 9637:     my $count=&get_todo_count($scanlines,$scan_data);
 9638:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9639:     my ($username,$domain,$started);
 9640:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9641:     if ($nav_error) {
 9642:         $r->print(&navmap_errormsg());
 9643:         return '';
 9644:     }
 9645: 
 9646:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9647:                                           'Processing first student');
 9648:     my $start=&Time::HiRes::time();
 9649:     my $i=-1;
 9650: 
 9651:     while ($i<$scanlines->{'count'}) {
 9652:         ($username,$domain,$uname)=('','','');
 9653:         $i++;
 9654:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9655:         if ($line=~/^[\s\cz]*$/) { next; }
 9656:         if ($started) {
 9657:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9658:                                                      'last student');
 9659:         }
 9660:         $started=1;
 9661:         my $scan_record=
 9662:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9663:                                                      $scan_data);
 9664:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9665:                                               \%idmap,$i)) {
 9666:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9667:                                 'Unable to find a student that matches',1);
 9668:             next;
 9669:         }
 9670:         if (exists $completedstudents{$uname}) {
 9671:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9672:                                 'Student '.$uname.' has multiple sheets',2);
 9673:             next;
 9674:         }
 9675:         my $pid = $scan_record->{'scantron.ID'};
 9676:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9677:         push(@{$bylast{$lastname{$pid}}},$pid);
 9678:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9679:         my $user = $uname.':'.$usec;
 9680:         ($username,$domain)=split(/:/,$uname);
 9681: 
 9682:         my $scancode;
 9683:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9684:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9685:             $scancode = $scan_record->{'scantron.CODE'};
 9686:         } else {
 9687:             $scancode = '';
 9688:         }
 9689: 
 9690:         my @mapresources = @resources;
 9691:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9692:         my %respnumlookup=();
 9693:         my %startline=();
 9694:         if ($randomorder || $randompick) {
 9695:             @mapresources =
 9696:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9697:                              \%orderedforcode);
 9698:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9699:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9700:                                              \%grader_partids_by_symb,\%orderedforcode,
 9701:                                              \%respnumlookup,\%startline);
 9702:             if ($randompick && $total) {
 9703:                 $lastpos = $total*$scantron_config{'Qlength'};
 9704:             }
 9705:         }
 9706:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9707:         chomp($scandata{$pid});
 9708:         $scandata{$pid} =~ s/\r$//;
 9709: 
 9710:         my $counter = -1;
 9711:         foreach my $resource (@mapresources) {
 9712:             my $parts;
 9713:             my $ressymb = $resource->symb();
 9714:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9715:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9716:                 my $currcode;
 9717:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9718:                     $currcode = $scancode;
 9719:                 }
 9720:                 (my $analysis,$parts) =
 9721:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9722:                                               $username,$domain,undef,
 9723:                                               $bubbles_per_row,$currcode);
 9724:             } else {
 9725:                 $parts = $grader_partids_by_symb{$ressymb};
 9726:             }
 9727:             ($counter,my $recording) =
 9728:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9729:                                          $scandata{$pid},$parts,
 9730:                                          \%scantron_config,\%lettdig,$numletts,
 9731:                                          $randomorder,$randompick,
 9732:                                          \%respnumlookup,\%startline);
 9733:             $record{$pid} .= $recording;
 9734:         }
 9735:     }
 9736:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9737:     $r->print('<br />');
 9738:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9739:     $passed = 0;
 9740:     $failed = 0;
 9741:     $numstudents = 0;
 9742:     foreach my $last (sort(keys(%bylast))) {
 9743:         if (ref($bylast{$last}) eq 'ARRAY') {
 9744:             foreach my $pid (sort(@{$bylast{$last}})) {
 9745:                 my $showscandata = $scandata{$pid};
 9746:                 my $showrecord = $record{$pid};
 9747:                 $showscandata =~ s/\s/&nbsp;/g;
 9748:                 $showrecord =~ s/\s/&nbsp;/g;
 9749:                 if ($scandata{$pid} eq $record{$pid}) {
 9750:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9751:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9752: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9753: '</tr>'."\n".
 9754: '<tr class="'.$css_class.'">'."\n".
 9755: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9756:                     $passed ++;
 9757:                 } else {
 9758:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9759:                     $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".
 9760: '</tr>'."\n".
 9761: '<tr class="'.$css_class.'">'."\n".
 9762: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9763: '</tr>'."\n";
 9764:                     $failed ++;
 9765:                 }
 9766:                 $numstudents ++;
 9767:             }
 9768:         }
 9769:     }
 9770:     $r->print('<p>'.
 9771:               &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).',
 9772:                   '<b>',
 9773:                   $numstudents,
 9774:                   '</b>',
 9775:                   $env{'form.scantron_maxbubble'}).
 9776:               '</p>'
 9777:     );
 9778:     $r->print('<p>'
 9779:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9780:              .'<br />'
 9781:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9782:              .'</p>');
 9783:     if ($passed) {
 9784:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9785:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9786:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9787:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9788:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9789:                  $okstudents."\n".
 9790:                  &Apache::loncommon::end_data_table().'<br />');
 9791:     }
 9792:     if ($failed) {
 9793:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9794:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9795:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9796:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9797:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9798:                  $badstudents."\n".
 9799:                  &Apache::loncommon::end_data_table()).'<br />'.
 9800:                  &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.');  
 9801:     }
 9802:     $r->print('</form><br />');
 9803:     return;
 9804: }
 9805: 
 9806: sub verify_scantron_grading {
 9807:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9808:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9809:         $respnumlookup,$startline) = @_;
 9810:     my ($record,%expected,%startpos);
 9811:     return ($counter,$record) if (!ref($resource));
 9812:     return ($counter,$record) if (!$resource->is_problem());
 9813:     my $symb = $resource->symb();
 9814:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9815:     foreach my $part_id (@{$partids}) {
 9816:         $counter ++;
 9817:         $expected{$part_id} = 0;
 9818:         my $respnum = $counter;
 9819:         if ($randomorder || $randompick) {
 9820:             $respnum = $respnumlookup->{$counter};
 9821:             $startpos{$part_id} = $startline->{$counter} + 1;
 9822:         } else {
 9823:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9824:         }
 9825:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9826:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9827:             foreach my $item (@sub_lines) {
 9828:                 $expected{$part_id} += $item;
 9829:             }
 9830:         } else {
 9831:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9832:         }
 9833:     }
 9834:     if ($symb) {
 9835:         my %recorded;
 9836:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9837:         if ($returnhash{'version'}) {
 9838:             my %lasthash=();
 9839:             my $version;
 9840:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9841:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9842:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9843:                 }
 9844:             }
 9845:             foreach my $key (keys(%lasthash)) {
 9846:                 if ($key =~ /\.scantron$/) {
 9847:                     my $value = &unescape($lasthash{$key});
 9848:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9849:                     if ($value eq '') {
 9850:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9851:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9852:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9853:                             }
 9854:                         }
 9855:                     } else {
 9856:                         my @tocheck;
 9857:                         my @items = split(//,$value);
 9858:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9859:                             ($scantron_config->{'Qon'} eq 'number')) {
 9860:                             if (@items < $expected{$part_id}) {
 9861:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9862:                                 my @singles = split(//,$fragment);
 9863:                                 foreach my $pos (@singles) {
 9864:                                     if ($pos eq ' ') {
 9865:                                         push(@tocheck,$pos);
 9866:                                     } else {
 9867:                                         my $next = shift(@items);
 9868:                                         push(@tocheck,$next);
 9869:                                     }
 9870:                                 }
 9871:                             } else {
 9872:                                 @tocheck = @items;
 9873:                             }
 9874:                             foreach my $letter (@tocheck) {
 9875:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9876:                                     if ($letter !~ /^[A-J]$/) {
 9877:                                         $letter = $scantron_config->{'Qoff'};
 9878:                                     }
 9879:                                     $recorded{$part_id} .= $letter;
 9880:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9881:                                     my $digit;
 9882:                                     if ($letter !~ /^[A-J]$/) {
 9883:                                         $digit = $scantron_config->{'Qoff'};
 9884:                                     } else {
 9885:                                         $digit = $lettdig->{$letter};
 9886:                                     }
 9887:                                     $recorded{$part_id} .= $digit;
 9888:                                 }
 9889:                             }
 9890:                         } else {
 9891:                             @tocheck = @items;
 9892:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9893:                                 my $curr_sub = shift(@tocheck);
 9894:                                 my $digit;
 9895:                                 if ($curr_sub =~ /^[A-J]$/) {
 9896:                                     $digit = $lettdig->{$curr_sub}-1;
 9897:                                 }
 9898:                                 if ($curr_sub eq 'J') {
 9899:                                     $digit += scalar($numletts);
 9900:                                 }
 9901:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9902:                                     if ($j == $digit) {
 9903:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9904:                                     } else {
 9905:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9906:                                     }
 9907:                                 }
 9908:                             }
 9909:                         }
 9910:                     }
 9911:                 }
 9912:             }
 9913:         }
 9914:         foreach my $part_id (@{$partids}) {
 9915:             if ($recorded{$part_id} eq '') {
 9916:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9917:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9918:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9919:                     }
 9920:                 }
 9921:             }
 9922:             $record .= $recorded{$part_id};
 9923:         }
 9924:     }
 9925:     return ($counter,$record);
 9926: }
 9927: 
 9928: #-------- end of section for handling grading scantron forms -------
 9929: #
 9930: #-------------------------------------------------------------------
 9931: 
 9932: #-------------------------- Menu interface -------------------------
 9933: #
 9934: #--- Href with symb and command ---
 9935: 
 9936: sub href_symb_cmd {
 9937:     my ($symb,$cmd)=@_;
 9938:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9939: }
 9940: 
 9941: sub grading_menu {
 9942:     my ($request,$symb) = @_;
 9943:     if (!$symb) {return '';}
 9944: 
 9945:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9946:                   'command'=>'individual');
 9947: 
 9948:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9949: 
 9950:     $fields{'command'}='ungraded';
 9951:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9952: 
 9953:     $fields{'command'}='table';
 9954:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9955: 
 9956:     $fields{'command'}='all_for_one';
 9957:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9958: 
 9959:     $fields{'command'}='downloadfilesselect';
 9960:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9961:     
 9962:     $fields{'command'} = 'csvform';
 9963:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9964:     
 9965:     $fields{'command'} = 'processclicker';
 9966:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9967:     
 9968:     $fields{'command'} = 'scantron_selectphase';
 9969:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9970: 
 9971:     $fields{'command'} = 'initialverifyreceipt';
 9972:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9973: 
 9974:     my %permissions;
 9975:     if ($perm{'mgr'}) {
 9976:         $permissions{'either'} = 'F';
 9977:         $permissions{'mgr'} = 'F';
 9978:     }
 9979:     if ($perm{'vgr'}) {
 9980:         $permissions{'either'} = 'F';
 9981:         $permissions{'vgr'} = 'F';
 9982:     }
 9983: 
 9984:     my @menu = ({	categorytitle=>'Hand Grading',
 9985:             items =>[
 9986:                         {       linktext => 'Select individual students to grade',
 9987:                                 url => $url1a,
 9988:                                 permission => $permissions{'either'},
 9989:                                 icon => 'grade_students.png',
 9990:                                 linktitle => 'Grade current resource for a selection of students.'
 9991:                         },
 9992:                         {       linktext => 'Grade ungraded submissions',
 9993:                                 url => $url1b,
 9994:                                 permission => $permissions{'either'},
 9995:                                 icon => 'ungrade_sub.png',
 9996:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9997:                         },
 9998: 
 9999:                         {       linktext => 'Grading table',
10000:                                 url => $url1c,
10001:                                 permission => $permissions{'either'},
10002:                                 icon => 'grading_table.png',
10003:                                 linktitle => 'Grade current resource for all students.'
10004:                         },
10005:                         {       linktext => 'Grade page/folder for one student',
10006:                                 url => $url1d,
10007:                                 permission => $permissions{'either'},
10008:                                 icon => 'grade_PageFolder.png',
10009:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10010:                         },
10011:                         {       linktext => 'Download submitted files',
10012:                                 url => $url1e,
10013:                                 permission => $permissions{'either'},
10014:                                 icon => 'download_sub.png',
10015:                                 linktitle => 'Download all files submitted by students.'
10016:                         }]},
10017:                          { categorytitle=>'Automated Grading',
10018:                items =>[
10019: 
10020:                 	    {	linktext => 'Upload Scores',
10021:                     		url => $url2,
10022:                     		permission => $permissions{'mgr'},
10023:                     		icon => 'uploadscores.png',
10024:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10025:                 	    },
10026:                 	    {	linktext => 'Process Clicker',
10027:                     		url => $url3,
10028:                     		permission => $permissions{'mgr'},
10029:                     		icon => 'addClickerInfoFile.png',
10030:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10031:                 	    },
10032:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10033:                     		url => $url4,
10034:                     		permission => $permissions{'mgr'},
10035:                     		icon => 'bubblesheet.png',
10036:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10037:                 	    },
10038:                             {   linktext => 'Verify Receipt Number',
10039:                                 url => $url5,
10040:                                 permission => $permissions{'either'},
10041:                                 icon => 'receipt_number.png',
10042:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10043:                             }
10044: 
10045:                     ]
10046:             });
10047: 
10048:     # Create the menu
10049:     my $Str;
10050:     $Str .= '<form method="post" action="" name="gradingMenu">';
10051:     $Str .= '<input type="hidden" name="command" value="" />'.
10052:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10053: 
10054:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10055:     return $Str;    
10056: }
10057: 
10058: sub ungraded {
10059:     my ($request)=@_;
10060:     &submit_options($request);
10061: }
10062: 
10063: sub submit_options_sequence {
10064:     my ($request,$symb) = @_;
10065:     if (!$symb) {return '';}
10066:     &commonJSfunctions($request);
10067:     my $result;
10068: 
10069:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10070:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10071:     $result.=&selectfield(0).
10072:             '<input type="hidden" name="command" value="pickStudentPage" />
10073:             <div>
10074:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10075:             </div>
10076:         </div>
10077:   </form>';
10078:     return $result;
10079: }
10080: 
10081: sub submit_options_table {
10082:     my ($request,$symb) = @_;
10083:     if (!$symb) {return '';}
10084:     &commonJSfunctions($request);
10085:     my $result;
10086: 
10087:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10088:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10089: 
10090:     $result.=&selectfield(1).
10091:             '<input type="hidden" name="command" value="viewgrades" />
10092:             <div>
10093:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10094:             </div>
10095:         </div>
10096:   </form>';
10097:     return $result;
10098: }
10099: 
10100: sub submit_options_download {
10101:     my ($request,$symb) = @_;
10102:     if (!$symb) {return '';}
10103: 
10104:     my $res_error;
10105:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10106:         &response_type($symb,\$res_error);
10107:     if ($res_error) {
10108:         $request->print(&mt('An error occurred retrieving response types'));
10109:         return;
10110:     }
10111:     unless ($numessay) {
10112:         $request->print(&mt('No essayresponse items found'));
10113:         return;
10114:     }
10115:     my $table;
10116:     if (ref($partlist) eq 'ARRAY') {
10117:         if (scalar(@$partlist) > 1 ) {
10118:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10119:         }
10120:     }
10121: 
10122:     &commonJSfunctions($request);
10123: 
10124:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10125:         $table."\n".
10126:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10127:     $result.='
10128: <h2>
10129:   '.&mt('Select Students for whom to Download Submitted Files').'
10130: </h2>'.&selectfield(1).'
10131:                 <input type="hidden" name="command" value="downloadfileslink" />
10132:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10133:             </div>
10134:           </div>
10135: 
10136: 
10137:   </form>';
10138:     return $result;
10139: }
10140: 
10141: #--- Displays the submissions first page -------
10142: sub submit_options {
10143:     my ($request,$symb) = @_;
10144:     if (!$symb) {return '';}
10145: 
10146:     &commonJSfunctions($request);
10147:     my $result;
10148: 
10149:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10150: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10151:     $result.=&selectfield(1).'
10152:                 <input type="hidden" name="command" value="submission" />
10153:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10154:             </div>
10155:           </div>
10156:   </form>';
10157:     return $result;
10158: }
10159: 
10160: sub selectfield {
10161:    my ($full)=@_;
10162:    my %options =
10163:        (&substatus_options,
10164:         'select_form_order' => ['yes','queued','graded','incorrect','all']);
10165: 
10166:   #
10167:   # PrepareClasslist() needs to be called to avoid getting a sections list
10168:   # for a different course from the @Sections global in lonstatistics.pm,
10169:   # populated by an earlier request.
10170:   #
10171:    &Apache::lonstatistics::PrepareClasslist();
10172: 
10173:    my $result='<div class="LC_columnSection">
10174: 
10175:     <fieldset>
10176:       <legend>
10177:        '.&mt('Sections').'
10178:       </legend>
10179:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10180:     </fieldset>
10181: 
10182:     <fieldset>
10183:       <legend>
10184:         '.&mt('Groups').'
10185:       </legend>
10186:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10187:     </fieldset>
10188:  
10189:     <fieldset>
10190:       <legend>
10191:         '.&mt('Access Status').'
10192:       </legend>
10193:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10194:     </fieldset>';
10195:     if ($full) {
10196:         $result.='
10197:     <fieldset>
10198:       <legend>
10199:         '.&mt('Submission Status').'
10200:       </legend>'.
10201:        &Apache::loncommon::select_form('all','submitonly',\%options).
10202:    '</fieldset>';
10203:     }
10204:     $result.='</div><br />';
10205:     return $result;
10206: }
10207: 
10208: sub substatus_options {
10209:     return &Apache::lonlocal::texthash(
10210:                                       'yes'       => 'with submissions',
10211:                                       'queued'    => 'in grading queue',
10212:                                       'graded'    => 'with ungraded submissions',
10213:                                       'incorrect' => 'with incorrect submissions',
10214:                                       'all'       => 'with any status',
10215:                                       );
10216: }
10217: 
10218: sub transtatus_options {
10219:     return &Apache::lonlocal::texthash(
10220:                                        'yes'       => 'with score transactions',
10221:                                        'incorrect' => 'with less than full credit',
10222:                                        'all'       => 'with any status',
10223:                                       );
10224: }
10225: 
10226: sub reset_perm {
10227:     undef(%perm);
10228: }
10229: 
10230: sub init_perm {
10231:     &reset_perm();
10232:     foreach my $test_perm ('vgr','mgr','opa') {
10233: 
10234: 	my $scope = $env{'request.course.id'};
10235: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10236: 
10237: 	    $scope .= '/'.$env{'request.course.sec'};
10238: 	    if ( $perm{$test_perm}=
10239: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10240: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10241: 	    } else {
10242: 		delete($perm{$test_perm});
10243: 	    }
10244: 	}
10245:     }
10246: }
10247: 
10248: sub init_old_essays {
10249:     my ($symb,$apath,$adom,$aname) = @_;
10250:     if ($symb ne '') {
10251:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10252:         if (keys(%essays) > 0) {
10253:             $old_essays{$symb} = \%essays;
10254:         }
10255:     }
10256:     return;
10257: }
10258: 
10259: sub reset_old_essays {
10260:     undef(%old_essays);
10261: }
10262: 
10263: sub gather_clicker_ids {
10264:     my %clicker_ids;
10265: 
10266:     my $classlist = &Apache::loncoursedata::get_classlist();
10267: 
10268:     # Set up a couple variables.
10269:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10270:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10271:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10272: 
10273:     foreach my $student (keys(%$classlist)) {
10274:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10275:         my $username = $classlist->{$student}->[$username_idx];
10276:         my $domain   = $classlist->{$student}->[$domain_idx];
10277:         my $clickers =
10278: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10279:         foreach my $id (split(/\,/,$clickers)) {
10280:             $id=~s/^[\#0]+//;
10281:             $id=~s/[\-\:]//g;
10282:             if (exists($clicker_ids{$id})) {
10283: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10284:             } else {
10285: 		$clicker_ids{$id}=$username.':'.$domain;
10286:             }
10287:         }
10288:     }
10289:     return %clicker_ids;
10290: }
10291: 
10292: sub gather_adv_clicker_ids {
10293:     my %clicker_ids;
10294:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10295:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10296:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10297:     foreach my $element (sort(keys(%coursepersonnel))) {
10298:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10299:             my ($puname,$pudom)=split(/\:/,$person);
10300:             my $clickers =
10301: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10302:             foreach my $id (split(/\,/,$clickers)) {
10303: 		$id=~s/^[\#0]+//;
10304:                 $id=~s/[\-\:]//g;
10305: 		if (exists($clicker_ids{$id})) {
10306: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10307: 		} else {
10308: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10309: 		}
10310:             }
10311:         }
10312:     }
10313:     return %clicker_ids;
10314: }
10315: 
10316: sub clicker_grading_parameters {
10317:     return ('gradingmechanism' => 'scalar',
10318:             'upfiletype' => 'scalar',
10319:             'specificid' => 'scalar',
10320:             'pcorrect' => 'scalar',
10321:             'pincorrect' => 'scalar');
10322: }
10323: 
10324: sub process_clicker {
10325:     my ($r,$symb)=@_;
10326:     if (!$symb) {return '';}
10327:     my $result=&checkforfile_js();
10328:     $result.=&Apache::loncommon::start_data_table().
10329:              &Apache::loncommon::start_data_table_header_row().
10330:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10331:              &Apache::loncommon::end_data_table_header_row().
10332:              &Apache::loncommon::start_data_table_row()."<td>\n";
10333: # Attempt to restore parameters from last session, set defaults if not present
10334:     my %Saveable_Parameters=&clicker_grading_parameters();
10335:     &Apache::loncommon::restore_course_settings('grades_clicker',
10336:                                                  \%Saveable_Parameters);
10337:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10338:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10339:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10340:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10341: 
10342:     my %checked;
10343:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10344:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10345:           $checked{$gradingmechanism}=' checked="checked"';
10346:        }
10347:     }
10348: 
10349:     my $upload=&mt("Evaluate File");
10350:     my $type=&mt("Type");
10351:     my $attendance=&mt("Award points just for participation");
10352:     my $personnel=&mt("Correctness determined from response by course personnel");
10353:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10354:     my $given=&mt("Correctness determined from given list of answers").' '.
10355:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10356:     my $pcorrect=&mt("Percentage points for correct solution");
10357:     my $pincorrect=&mt("Percentage points for incorrect solution");
10358:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10359:                                                    {'iclicker' => 'i>clicker',
10360:                                                     'interwrite' => 'interwrite PRS',
10361:                                                     'turning' => 'Turning Technologies'});
10362:     $symb = &Apache::lonenc::check_encrypt($symb);
10363:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10364: function sanitycheck() {
10365: // Accept only integer percentages
10366:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10367:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10368: // Find out grading choice
10369:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10370:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10371:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10372:       }
10373:    }
10374: // By default, new choice equals user selection
10375:    newgradingchoice=gradingchoice;
10376: // Not good to give more points for false answers than correct ones
10377:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10378:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10379:    }
10380: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10381:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10382:       document.forms.gradesupload.pcorrect.value=100;
10383:       document.forms.gradesupload.pincorrect.value=100;
10384:    }
10385: // If the values are different, cannot be attendance only
10386:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10387:        (gradingchoice=='attendance')) {
10388:        newgradingchoice='personnel';
10389:    }
10390: // Change grading choice to new one
10391:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10392:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10393:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10394:       } else {
10395:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10396:       }
10397:    }
10398: // Remember the old state
10399:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10400: }
10401: ENDUPFORM
10402:     $result.= <<ENDUPFORM;
10403: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10404: <input type="hidden" name="symb" value="$symb" />
10405: <input type="hidden" name="command" value="processclickerfile" />
10406: <input type="file" name="upfile" size="50" />
10407: <br /><label>$type: $selectform</label>
10408: ENDUPFORM
10409:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10410:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10411:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10412: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10413: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10414: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10415: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10416: <br />&nbsp;&nbsp;&nbsp;
10417: <input type="text" name="givenanswer" size="50" />
10418: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10419: ENDGRADINGFORM
10420:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10421:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10422:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10423: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10424: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10425: </form>
10426: ENDPERCFORM
10427:     $result.='</td>'.
10428:              &Apache::loncommon::end_data_table_row().
10429:              &Apache::loncommon::end_data_table();
10430:     return $result;
10431: }
10432: 
10433: sub process_clicker_file {
10434:     my ($r,$symb) = @_;
10435:     if (!$symb) {return '';}
10436: 
10437:     my %Saveable_Parameters=&clicker_grading_parameters();
10438:     &Apache::loncommon::store_course_settings('grades_clicker',
10439:                                               \%Saveable_Parameters);
10440:     my $result='';
10441:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10442: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10443: 	return $result;
10444:     }
10445:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10446:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10447:         return $result;
10448:     }
10449:     my $foundgiven=0;
10450:     if ($env{'form.gradingmechanism'} eq 'given') {
10451:         $env{'form.givenanswer'}=~s/^\s*//gs;
10452:         $env{'form.givenanswer'}=~s/\s*$//gs;
10453:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10454:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10455:         my @answers=split(/\,/,$env{'form.givenanswer'});
10456:         $foundgiven=$#answers+1;
10457:     }
10458:     my %clicker_ids=&gather_clicker_ids();
10459:     my %correct_ids;
10460:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10461: 	%correct_ids=&gather_adv_clicker_ids();
10462:     }
10463:     if ($env{'form.gradingmechanism'} eq 'specific') {
10464: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10465: 	   $correct_id=~tr/a-z/A-Z/;
10466: 	   $correct_id=~s/\s//gs;
10467: 	   $correct_id=~s/^[\#0]+//;
10468:            $correct_id=~s/[\-\:]//g;
10469:            if ($correct_id) {
10470: 	      $correct_ids{$correct_id}='specified';
10471:            }
10472:         }
10473:     }
10474:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10475: 	$result.=&mt('Score based on attendance only');
10476:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10477:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10478:     } else {
10479: 	my $number=0;
10480: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10481: 	foreach my $id (sort(keys(%correct_ids))) {
10482: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10483: 	    if ($correct_ids{$id} eq 'specified') {
10484: 		$result.=&mt('specified');
10485: 	    } else {
10486: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10487: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10488: 	    }
10489: 	    $number++;
10490: 	}
10491:         $result.="</p>\n";
10492:         if ($number==0) {
10493:             $result .=
10494:                  &Apache::lonhtmlcommon::confirm_success(
10495:                      &mt('No IDs found to determine correct answer'),1);
10496:             return $result;
10497:         }
10498:     }
10499:     if (length($env{'form.upfile'}) < 2) {
10500:         $result .=
10501:             &Apache::lonhtmlcommon::confirm_success(
10502:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10503:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10504:         return $result;
10505:     }
10506:     my $mimetype;
10507:     if ($env{'form.upfiletype'} eq 'iclicker') {
10508:         my $mm = new File::MMagic;
10509:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10510:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10511:             $result.= '<p>'.
10512:                 &Apache::lonhtmlcommon::confirm_success(
10513:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10514:             return $result;
10515:         }
10516:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10517:         $result .= '<p>'.
10518:             &Apache::lonhtmlcommon::confirm_success(
10519:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10520:         return $result;
10521:     }
10522: 
10523: # Were able to get all the info needed, now analyze the file
10524: 
10525:     $result.=&Apache::loncommon::studentbrowser_javascript();
10526:     $symb = &Apache::lonenc::check_encrypt($symb);
10527:     $result.=&Apache::loncommon::start_data_table().
10528:              &Apache::loncommon::start_data_table_header_row().
10529:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10530:              &Apache::loncommon::end_data_table_header_row().
10531:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10532: <td>
10533: <form method="post" action="/adm/grades" name="clickeranalysis">
10534: <input type="hidden" name="symb" value="$symb" />
10535: <input type="hidden" name="command" value="assignclickergrades" />
10536: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10537: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10538: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10539: ENDHEADER
10540:     if ($env{'form.gradingmechanism'} eq 'given') {
10541:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10542:     } 
10543:     my %responses;
10544:     my @questiontitles;
10545:     my $errormsg='';
10546:     my $number=0;
10547:     if ($env{'form.upfiletype'} eq 'iclicker') {
10548:         if ($mimetype eq 'text/plain') {
10549:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10550:         } elsif ($mimetype eq 'text/html') {
10551:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10552:         }
10553:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10554:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10555:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10556:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10557:     }
10558:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10559:              '<input type="hidden" name="number" value="'.$number.'" />'.
10560:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10561:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10562:              '<br />';
10563:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10564:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10565:        return $result;
10566:     } 
10567: # Remember Question Titles
10568: # FIXME: Possibly need delimiter other than ":"
10569:     for (my $i=0;$i<$number;$i++) {
10570:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10571:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10572:     }
10573:     my $correct_count=0;
10574:     my $student_count=0;
10575:     my $unknown_count=0;
10576: # Match answers with usernames
10577: # FIXME: Possibly need delimiter other than ":"
10578:     foreach my $id (keys(%responses)) {
10579:        if ($correct_ids{$id}) {
10580:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10581:           $correct_count++;
10582:        } elsif ($clicker_ids{$id}) {
10583:           if ($clicker_ids{$id}=~/\,/) {
10584: # More than one user with the same clicker!
10585:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10586:                            &Apache::loncommon::start_data_table_row()."<td>".
10587:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10588:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10589:                            "<select name='multi".$id."'>";
10590:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10591:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10592:              }
10593:              $result.='</select>';
10594:              $unknown_count++;
10595:           } else {
10596: # Good: found one and only one user with the right clicker
10597:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10598:              $student_count++;
10599:           }
10600:        } else {
10601:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10602:                            &Apache::loncommon::start_data_table_row()."<td>".
10603:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10604:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10605:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10606:                    "\n".&mt("Domain").": ".
10607:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10608:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10609:           $unknown_count++;
10610:        }
10611:     }
10612:     $result.='<hr />'.
10613:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10614:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10615:        if ($correct_count==0) {
10616:           $errormsg.="Found no correct answers for grading!";
10617:        } elsif ($correct_count>1) {
10618:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10619:        }
10620:     }
10621:     if ($number<1) {
10622:        $errormsg.="Found no questions.";
10623:     }
10624:     if ($errormsg) {
10625:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10626:     } else {
10627:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10628:     }
10629:     $result.='</form></td>'.
10630:              &Apache::loncommon::end_data_table_row().
10631:              &Apache::loncommon::end_data_table();
10632:     return $result;
10633: }
10634: 
10635: sub iclicker_eval {
10636:     my ($questiontitles,$responses)=@_;
10637:     my $number=0;
10638:     my $errormsg='';
10639:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10640:         my %components=&Apache::loncommon::record_sep($line);
10641:         my @entries=map {$components{$_}} (sort(keys(%components)));
10642: 	if ($entries[0] eq 'Question') {
10643: 	    for (my $i=3;$i<$#entries;$i+=6) {
10644: 		$$questiontitles[$number]=$entries[$i];
10645: 		$number++;
10646: 	    }
10647: 	}
10648: 	if ($entries[0]=~/^\#/) {
10649: 	    my $id=$entries[0];
10650: 	    my @idresponses;
10651: 	    $id=~s/^[\#0]+//;
10652: 	    for (my $i=0;$i<$number;$i++) {
10653: 		my $idx=3+$i*6;
10654:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10655: 		push(@idresponses,$entries[$idx]);
10656: 	    }
10657: 	    $$responses{$id}=join(',',@idresponses);
10658: 	}
10659:     }
10660:     return ($errormsg,$number);
10661: }
10662: 
10663: sub iclickerxml_eval {
10664:     my ($questiontitles,$responses)=@_;
10665:     my $number=0;
10666:     my $errormsg='';
10667:     my @state;
10668:     my %respbyid;
10669:     my $p = HTML::Parser->new
10670:     (
10671:         xml_mode => 1,
10672:         start_h =>
10673:             [sub {
10674:                  my ($tagname,$attr) = @_;
10675:                  push(@state,$tagname);
10676:                  if ("@state" eq "ssn p") {
10677:                      my $title = $attr->{qn};
10678:                      $title =~ s/(^\s+|\s+$)//g;
10679:                      $questiontitles->[$number]=$title;
10680:                  } elsif ("@state" eq "ssn p v") {
10681:                      my $id = $attr->{id};
10682:                      my $entry = $attr->{ans};
10683:                      $id=~s/^[\#0]+//;
10684:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10685:                      $respbyid{$id}[$number] = $entry;
10686:                  }
10687:             }, "tagname, attr"],
10688:          end_h =>
10689:                [sub {
10690:                    my ($tagname) = @_;
10691:                    if ("@state" eq "ssn p") {
10692:                        $number++;
10693:                    }
10694:                    pop(@state);
10695:                 }, "tagname"],
10696:     );
10697: 
10698:     $p->parse($env{'form.upfile'});
10699:     $p->eof;
10700:     foreach my $id (keys(%respbyid)) {
10701:         $responses->{$id}=join(',',@{$respbyid{$id}});
10702:     }
10703:     return ($errormsg,$number);
10704: }
10705: 
10706: sub interwrite_eval {
10707:     my ($questiontitles,$responses)=@_;
10708:     my $number=0;
10709:     my $errormsg='';
10710:     my $skipline=1;
10711:     my $questionnumber=0;
10712:     my %idresponses=();
10713:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10714:         my %components=&Apache::loncommon::record_sep($line);
10715:         my @entries=map {$components{$_}} (sort(keys(%components)));
10716:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10717:         if ($entries[1] eq 'Response') { $skipline=1; }
10718:         next if $skipline;
10719:         if ($entries[0]!=$questionnumber) {
10720:            $questionnumber=$entries[0];
10721:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10722:            $number++;
10723:         }
10724:         my $id=$entries[4];
10725:         $id=~s/^[\#0]+//;
10726:         $id=~s/^v\d*\://i;
10727:         $id=~s/[\-\:]//g;
10728:         $idresponses{$id}[$number]=$entries[6];
10729:     }
10730:     foreach my $id (keys(%idresponses)) {
10731:        $$responses{$id}=join(',',@{$idresponses{$id}});
10732:        $$responses{$id}=~s/^\s*\,//;
10733:     }
10734:     return ($errormsg,$number);
10735: }
10736: 
10737: sub turning_eval {
10738:     my ($questiontitles,$responses)=@_;
10739:     my $number=0;
10740:     my $errormsg='';
10741:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10742:         my %components=&Apache::loncommon::record_sep($line);
10743:         my @entries=map {$components{$_}} (sort(keys(%components)));
10744:         if ($#entries>$number) { $number=$#entries; }
10745:         my $id=$entries[0];
10746:         my @idresponses;
10747:         $id=~s/^[\#0]+//;
10748:         unless ($id) { next; }
10749:         for (my $idx=1;$idx<=$#entries;$idx++) {
10750:             $entries[$idx]=~s/\,/\;/g;
10751:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10752:             push(@idresponses,$entries[$idx]);
10753:         }
10754:         $$responses{$id}=join(',',@idresponses);
10755:     }
10756:     for (my $i=1; $i<=$number; $i++) {
10757:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10758:     }
10759:     return ($errormsg,$number);
10760: }
10761: 
10762: sub assign_clicker_grades {
10763:     my ($r,$symb) = @_;
10764:     if (!$symb) {return '';}
10765: # See which part we are saving to
10766:     my $res_error;
10767:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10768:     if ($res_error) {
10769:         return &navmap_errormsg();
10770:     }
10771: # FIXME: This should probably look for the first handgradeable part
10772:     my $part=$$partlist[0];
10773: # Start screen output
10774:     my $result = &Apache::loncommon::start_data_table(). 
10775:                  &Apache::loncommon::start_data_table_header_row().
10776:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10777:                  &Apache::loncommon::end_data_table_header_row().
10778:                  &Apache::loncommon::start_data_table_row().'<td>';
10779: # Get correct result
10780: # FIXME: Possibly need delimiter other than ":"
10781:     my @correct=();
10782:     my $gradingmechanism=$env{'form.gradingmechanism'};
10783:     my $number=$env{'form.number'};
10784:     if ($gradingmechanism ne 'attendance') {
10785:        foreach my $key (keys(%env)) {
10786:           if ($key=~/^form\.correct\:/) {
10787:              my @input=split(/\,/,$env{$key});
10788:              for (my $i=0;$i<=$#input;$i++) {
10789:                  if (($correct[$i]) && ($input[$i]) &&
10790:                      ($correct[$i] ne $input[$i])) {
10791:                     $result.='<br /><span class="LC_warning">'.
10792:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10793:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10794:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10795:                     $correct[$i]=$input[$i];
10796:                  }
10797:              }
10798:           }
10799:        }
10800:        for (my $i=0;$i<$number;$i++) {
10801:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10802:              $result.='<br /><span class="LC_error">'.
10803:                       &mt('No correct result given for question "[_1]"!',
10804:                           $env{'form.question:'.$i}).'</span>';
10805:           }
10806:        }
10807:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10808:     }
10809: # Start grading
10810:     my $pcorrect=$env{'form.pcorrect'};
10811:     my $pincorrect=$env{'form.pincorrect'};
10812:     my $storecount=0;
10813:     my %users=();
10814:     foreach my $key (keys(%env)) {
10815:        my $user='';
10816:        if ($key=~/^form\.student\:(.*)$/) {
10817:           $user=$1;
10818:        }
10819:        if ($key=~/^form\.unknown\:(.*)$/) {
10820:           my $id=$1;
10821:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10822:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10823:           } elsif ($env{'form.multi'.$id}) {
10824:              $user=$env{'form.multi'.$id};
10825:           }
10826:        }
10827:        if ($user) {
10828:           if ($users{$user}) {
10829:              $result.='<br /><span class="LC_warning">'.
10830:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10831:                       '</span><br />';
10832:           }
10833:           $users{$user}=1;
10834:           my @answer=split(/\,/,$env{$key});
10835:           my $sum=0;
10836:           my $realnumber=$number;
10837:           for (my $i=0;$i<$number;$i++) {
10838:              if  ($correct[$i] eq '-') {
10839:                 $realnumber--;
10840:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10841:                 if ($gradingmechanism eq 'attendance') {
10842:                    $sum+=$pcorrect;
10843:                 } elsif ($correct[$i] eq '*') {
10844:                    $sum+=$pcorrect;
10845:                 } else {
10846: # We actually grade if correct or not
10847:                    my $increment=$pincorrect;
10848: # Special case: numerical answer "0"
10849:                    if ($correct[$i] eq '0') {
10850:                       if ($answer[$i]=~/^[0\.]+$/) {
10851:                          $increment=$pcorrect;
10852:                       }
10853: # General numerical answer, both evaluate to something non-zero
10854:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10855:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10856:                          $increment=$pcorrect;
10857:                       }
10858: # Must be just alphanumeric
10859:                    } elsif ($answer[$i] eq $correct[$i]) {
10860:                       $increment=$pcorrect;
10861:                    }
10862:                    $sum+=$increment;
10863:                 }
10864:              }
10865:           }
10866:           my $ave=$sum/(100*$realnumber);
10867: # Store
10868:           my ($username,$domain)=split(/\:/,$user);
10869:           my %grades=();
10870:           $grades{"resource.$part.solved"}='correct_by_override';
10871:           $grades{"resource.$part.awarded"}=$ave;
10872:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10873:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10874:                                                  $env{'request.course.id'},
10875:                                                  $domain,$username);
10876:           if ($returncode ne 'ok') {
10877:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10878:           } else {
10879:              $storecount++;
10880:           }
10881:        }
10882:     }
10883: # We are done
10884:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10885:              '</td>'.
10886:              &Apache::loncommon::end_data_table_row().
10887:              &Apache::loncommon::end_data_table();
10888:     return $result;
10889: }
10890: 
10891: sub navmap_errormsg {
10892:     return '<div class="LC_error">'.
10893:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10894:            &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>').
10895:            '</div>';
10896: }
10897: 
10898: sub startpage {
10899:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
10900:     my %args;
10901:     if ($onload) {
10902:          my %loaditems = (
10903:                         'onload' => $onload,
10904:                       );
10905:          $args{'add_entries'} = \%loaditems;
10906:     }
10907:     if ($nomenu) {
10908:         $args{'only_body'} = 1;
10909:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
10910:     } else {
10911:         if ($env{'request.course.id'}) {
10912:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10913:         }
10914:         $args{'bread_crumbs'} = $crumbs;
10915:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
10916:     }
10917:     unless ($nodisplayflag) {
10918:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
10919:     }
10920: }
10921: 
10922: sub select_problem {
10923:     my ($r)=@_;
10924:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10925:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
10926:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10927:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10928: }
10929: 
10930: sub handler {
10931:     my $request=$_[0];
10932:     &reset_caches();
10933:     if ($request->header_only) {
10934:         &Apache::loncommon::content_type($request,'text/html');
10935:         $request->send_http_header;
10936:         return OK;
10937:     }
10938:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10939: 
10940: # see what command we need to execute
10941:  
10942:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10943:     my $command=$commands[0];
10944: 
10945:     &init_perm();
10946:     if (!$env{'request.course.id'}) {
10947:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10948:                 ($command =~ /^scantronupload/)) {
10949:             # Not in a course.
10950:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10951:             return HTTP_NOT_ACCEPTABLE;
10952:         }
10953:     } elsif (!%perm) {
10954:         $request->internal_redirect('/adm/quickgrades');
10955:         return OK;
10956:     }
10957:     &Apache::loncommon::content_type($request,'text/html');
10958:     $request->send_http_header;
10959: 
10960:     if ($#commands > 0) {
10961: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10962:     }
10963: 
10964: # see what the symb is
10965: 
10966:     my $symb=$env{'form.symb'};
10967:     unless ($symb) {
10968:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10969:        $symb=&Apache::lonnet::symbread($url);
10970:     }
10971:     &Apache::lonenc::check_decrypt(\$symb);
10972: 
10973:     $ssi_error = 0;
10974:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10975: #
10976: # Not called from a resource, but inside a course
10977: #
10978:         &startpage($request,undef,[],1,1);
10979:         &select_problem($request);
10980:     } else {
10981:         if ($command eq 'submission' && $perm{'vgr'}) {
10982:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
10983:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10984:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10985:                     &choose_task_version_form($symb,$env{'form.student'},
10986:                                               $env{'form.userdom'});
10987:             }
10988:             my $divforres;
10989:             if ($env{'form.student'} eq '') {
10990:                 $js .= &part_selector_js();
10991:                 $onload = "toggleParts('gradesub');";
10992:             } else {
10993:                 $divforres = 1;
10994:             }
10995:             my $head_extra = $js;
10996:             unless ($env{'form.vProb'} eq 'no') {
10997:                 my $csslinks = &Apache::loncommon::css_links($symb);
10998:                 if ($csslinks) {
10999:                     $head_extra .= "\n$csslinks";
11000:                 }
11001:             }
11002:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11003:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11004:             if ($versionform) {
11005:                 if ($divforres) {
11006:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11007:                 }
11008:                 $request->print($versionform);
11009:             }
11010:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11011:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11012:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11013:                 &choose_task_version_form($symb,$env{'form.student'},
11014:                                           $env{'form.userdom'},
11015:                                           $env{'form.inhibitmenu'});
11016:             my $head_extra = $js;
11017:             unless ($env{'form.vProb'} eq 'no') {
11018:                 my $csslinks = &Apache::loncommon::css_links($symb);
11019:                 if ($csslinks) {
11020:                     $head_extra .= "\n$csslinks";
11021:                 }
11022:             }
11023:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11024:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11025:             if ($versionform) {
11026:                 $request->print($versionform);
11027:             }
11028:             $request->print('<br clear="all" />');
11029:             $request->print(&show_previous_task_version($request,$symb));
11030:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11031:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11032:                                        {href=>'',text=>'Select student'}],1,1);
11033:             &pickStudentPage($request,$symb);
11034:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11035:             my $csslinks;
11036:             unless ($env{'form.vProb'} eq 'no') {
11037:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11038:             }
11039:             &startpage($request,$symb,
11040:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11041:                                        {href=>'',text=>'Select student'},
11042:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11043:             &displayPage($request,$symb);
11044:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11045:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11046:                                        {href=>'',text=>'Select student'},
11047:                                        {href=>'',text=>'Grade student'},
11048:                                        {href=>'',text=>'Store grades'}],1,1);
11049:             &updateGradeByPage($request,$symb);
11050:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11051:             my $csslinks;
11052:             unless ($env{'form.vProb'} eq 'no') {
11053:                 $csslinks = &Apache::loncommon::css_links($symb);
11054:             }
11055:             &startpage($request,$symb,[{href=>'',text=>'...'},
11056:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11057:             &processGroup($request,$symb);
11058:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11059:             &startpage($request,$symb);
11060:             $request->print(&grading_menu($request,$symb));
11061:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
11062:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11063:             $request->print(&submit_options($request,$symb));
11064:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11065:             my $js = &part_selector_js();
11066:             my $onload = "toggleParts('gradesub');";
11067:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11068:                        undef,undef,undef,undef,undef,$js,$onload);
11069:             $request->print(&listStudents($request,$symb,'graded'));
11070:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11071:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11072:             $request->print(&submit_options_table($request,$symb));
11073:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11074:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11075:             $request->print(&submit_options_sequence($request,$symb));
11076:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11077:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11078:             $request->print(&viewgrades($request,$symb));
11079:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11080:             &startpage($request,$symb,[{href=>'',text=>'...'},
11081:                                        {href=>'',text=>'Store grades'}]);
11082:             $request->print(&processHandGrade($request,$symb));
11083:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11084:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11085:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11086:                                                                              text=>"Modify grades"},
11087:                                        {href=>'', text=>"Store grades"}]);
11088:             $request->print(&editgrades($request,$symb));
11089:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11090:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11091:             $request->print(&initialverifyreceipt($request,$symb));
11092:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
11093:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11094:                                        {href=>'',text=>'Verification Result'}]);
11095:             $request->print(&verifyreceipt($request,$symb));
11096:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11097:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11098:             $request->print(&process_clicker($request,$symb));
11099:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11100:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11101:                                        {href=>'', text=>'Process clicker file'}]);
11102:             $request->print(&process_clicker_file($request,$symb));
11103:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11104:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11105:                                        {href=>'', text=>'Process clicker file'},
11106:                                        {href=>'', text=>'Store grades'}]);
11107:             $request->print(&assign_clicker_grades($request,$symb));
11108:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
11109:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11110:             $request->print(&upcsvScores_form($request,$symb));
11111:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11112:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11113:             $request->print(&csvupload($request,$symb));
11114:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11115:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11116:             $request->print(&csvuploadmap($request,$symb));
11117:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11118:             if ($env{'form.associate'} ne 'Reverse Association') {
11119:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11120:                 $request->print(&csvuploadoptions($request,$symb));
11121:             } else {
11122:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11123:                     $env{'form.upfile_associate'} = 'reverse';
11124:                 } else {
11125:                     $env{'form.upfile_associate'} = 'forward';
11126:                 }
11127:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11128:                 $request->print(&csvuploadmap($request,$symb));
11129:             }
11130:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11131:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11132:             $request->print(&csvuploadassign($request,$symb));
11133:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11134:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11135:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11136:             $request->print(&scantron_selectphase($request,undef,$symb));
11137:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11138:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11139:             $request->print(&scantron_do_warning($request,$symb));
11140:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11141:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11142:             $request->print(&scantron_validate_file($request,$symb));
11143:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11144:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11145:             $request->print(&scantron_process_students($request,$symb));
11146:         } elsif ($command eq 'scantronupload' &&
11147:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11148:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11149:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11150:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11151:             $request->print(&scantron_upload_scantron_data($request,$symb));
11152:         } elsif ($command eq 'scantronupload_save' &&
11153:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11154:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11155:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11156:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11157:         } elsif ($command eq 'scantron_download' &&
11158:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11159:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11160:             $request->print(&scantron_download_scantron_data($request,$symb));
11161:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11162:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11163:             $request->print(&checkscantron_results($request,$symb));
11164:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11165:             my $js = &part_selector_js();
11166:             my $onload = "toggleParts('gradingMenu');";
11167:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11168:                        undef,undef,undef,undef,undef,$js,$onload);
11169:             $request->print(&submit_options_download($request,$symb));
11170:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11171:             &startpage($request,$symb,
11172:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11173:     {href=>'', text=>'Download submitted files'}],
11174:                undef,undef,undef,undef,undef,undef,undef,1);
11175:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11176:             &submit_download_link($request,$symb);
11177:         } elsif ($command) {
11178:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11179:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11180:         }
11181:     }
11182:     if ($ssi_error) {
11183: 	&ssi_print_error($request);
11184:     }
11185:     $request->print(&Apache::loncommon::end_page());
11186:     &reset_caches();
11187:     return OK;
11188: }
11189: 
11190: 1;
11191: 
11192: __END__;
11193: 
11194: 
11195: =head1 NAME
11196: 
11197: Apache::grades
11198: 
11199: =head1 SYNOPSIS
11200: 
11201: Handles the viewing of grades.
11202: 
11203: This is part of the LearningOnline Network with CAPA project
11204: described at http://www.lon-capa.org.
11205: 
11206: =head1 OVERVIEW
11207: 
11208: Do an ssi with retries:
11209: While I'd love to factor out this with the vesrion in lonprintout,
11210: 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
11211: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11212: 
11213: At least the logic that drives this has been pulled out into loncommon.
11214: 
11215: 
11216: 
11217: ssi_with_retries - Does the server side include of a resource.
11218:                      if the ssi call returns an error we'll retry it up to
11219:                      the number of times requested by the caller.
11220:                      If we still have a problem, no text is appended to the
11221:                      output and we set some global variables.
11222:                      to indicate to the caller an SSI error occurred.  
11223:                      All of this is supposed to deal with the issues described
11224:                      in LON-CAPA BZ 5631 see:
11225:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11226:                      by informing the user that this happened.
11227: 
11228: Parameters:
11229:   resource   - The resource to include.  This is passed directly, without
11230:                interpretation to lonnet::ssi.
11231:   form       - The form hash parameters that guide the interpretation of the resource
11232:                
11233:   retries    - Number of retries allowed before giving up completely.
11234: Returns:
11235:   On success, returns the rendered resource identified by the resource parameter.
11236: Side Effects:
11237:   The following global variables can be set:
11238:    ssi_error                - If an unrecoverable error occurred this becomes true.
11239:                               It is up to the caller to initialize this to false
11240:                               if desired.
11241:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11242:                               of the resource that could not be rendered by the ssi
11243:                               call.
11244:    ssi_error_message   - The error string fetched from the ssi response
11245:                               in the event of an error.
11246: 
11247: 
11248: =head1 HANDLER SUBROUTINE
11249: 
11250: ssi_with_retries()
11251: 
11252: =head1 SUBROUTINES
11253: 
11254: =over
11255: 
11256: =item scantron_get_correction() : 
11257: 
11258:    Builds the interface screen to interact with the operator to fix a
11259:    specific error condition in a specific scanline
11260: 
11261:  Arguments:
11262:     $r           - Apache request object
11263:     $i           - number of the current scanline
11264:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11265:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11266:     $line        - full contents of the current scanline
11267:     $error       - error condition, valid values are
11268:                    'incorrectCODE', 'duplicateCODE',
11269:                    'doublebubble', 'missingbubble',
11270:                    'duplicateID', 'incorrectID'
11271:     $arg         - extra information needed
11272:        For errors:
11273:          - duplicateID   - paper number that this studentID was seen before on
11274:          - duplicateCODE - array ref of the paper numbers this CODE was
11275:                            seen on before
11276:          - incorrectCODE - current incorrect CODE 
11277:          - doublebubble  - array ref of the bubble lines that have double
11278:                            bubble errors
11279:          - missingbubble - array ref of the bubble lines that have missing
11280:                            bubble errors
11281: 
11282:    $randomorder - True if exam folder has randomorder set
11283:    $randompick  - True if exam folder has randompick set
11284:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11285:                      for current line to question number used for same question
11286:                      in "Master Seqence" (as seen by Course Coordinator).
11287:    $startline   - Reference to hash where key is question number (0 is first)
11288:                   and value is number of first bubble line for current student
11289:                   or code-based randompick and/or randomorder.
11290: 
11291: 
11292: =item  scantron_get_maxbubble() : 
11293: 
11294:    Arguments:
11295:        $nav_error  - Reference to scalar which is a flag to indicate a
11296:                       failure to retrieve a navmap object.
11297:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11298:        calling routine should trap the error condition and display the warning
11299:        found in &navmap_errormsg().
11300: 
11301:        $scantron_config - Reference to bubblesheet format configuration hash.
11302: 
11303:    Returns the maximum number of bubble lines that are expected to
11304:    occur. Does this by walking the selected sequence rendering the
11305:    resource and then checking &Apache::lonxml::get_problem_counter()
11306:    for what the current value of the problem counter is.
11307: 
11308:    Caches the results to $env{'form.scantron_maxbubble'},
11309:    $env{'form.scantron.bubble_lines.n'}, 
11310:    $env{'form.scantron.first_bubble_line.n'} and
11311:    $env{"form.scantron.sub_bubblelines.n"}
11312:    which are the total number of bubble lines, the number of bubble
11313:    lines for response n and number of the first bubble line for response n,
11314:    and a comma separated list of numbers of bubble lines for sub-questions
11315:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11316: 
11317: 
11318: =item  scantron_validate_missingbubbles() : 
11319: 
11320:    Validates all scanlines in the selected file to not have any
11321:     answers that don't have bubbles that have not been verified
11322:     to be bubble free.
11323: 
11324: =item  scantron_process_students() : 
11325: 
11326:    Routine that does the actual grading of the bubblesheet information.
11327: 
11328:    The parsed scanline hash is added to %env 
11329: 
11330:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11331:    foreach resource , with the form data of
11332: 
11333: 	'submitted'     =>'scantron' 
11334: 	'grade_target'  =>'grade',
11335: 	'grade_username'=> username of student
11336: 	'grade_domain'  => domain of student
11337: 	'grade_courseid'=> of course
11338: 	'grade_symb'    => symb of resource to grade
11339: 
11340:     This triggers a grading pass. The problem grading code takes care
11341:     of converting the bubbled letter information (now in %env) into a
11342:     valid submission.
11343: 
11344: =item  scantron_upload_scantron_data() :
11345: 
11346:     Creates the screen for adding a new bubblesheet data file to a course.
11347: 
11348: =item  scantron_upload_scantron_data_save() : 
11349: 
11350:    Adds a provided bubble information data file to the course if user
11351:    has the correct privileges to do so. 
11352: 
11353: =item  valid_file() :
11354: 
11355:    Validates that the requested bubble data file exists in the course.
11356: 
11357: =item  scantron_download_scantron_data() : 
11358: 
11359:    Shows a list of the three internal files (original, corrected,
11360:    skipped) for a specific bubblesheet data file that exists in the
11361:    course.
11362: 
11363: =item  scantron_validate_ID() : 
11364: 
11365:    Validates all scanlines in the selected file to not have any
11366:    invalid or underspecified student/employee IDs
11367: 
11368: =item navmap_errormsg() :
11369: 
11370:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11371:    Should be called whenever the request to instantiate a navmap object fails.  
11372: 
11373: =back
11374: 
11375: =cut

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