File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.774: download - view: text, annotated - select for diffs
Mon Aug 31 01:14:06 2020 UTC (3 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- White space changes only.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.774 2020/08/31 01:14:06 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::lonquickgrades;
   48: use Apache::bridgetask();
   49: use Apache::lontexconvert();
   50: use String::Similarity;
   51: use HTML::Parser();
   52: use File::MMagic;
   53: use LONCAPA;
   54: 
   55: use POSIX qw(floor);
   56: 
   57: 
   58: 
   59: my %perm=();
   60: my %old_essays=();
   61: 
   62: #  These variables are used to recover from ssi errors
   63: 
   64: my $ssi_retries = 5;
   65: my $ssi_error;
   66: my $ssi_error_resource;
   67: my $ssi_error_message;
   68: 
   69: 
   70: sub ssi_with_retries {
   71:     my ($resource, $retries, %form) = @_;
   72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   73:     if ($response->is_error) {
   74: 	$ssi_error          = 1;
   75: 	$ssi_error_resource = $resource;
   76: 	$ssi_error_message  = $response->code . " " . $response->message;
   77:     }
   78: 
   79:     return $content;
   80: 
   81: }
   82: #
   83: #  Prodcuces an ssi retry failure error message to the user:
   84: #
   85: 
   86: sub ssi_print_error {
   87:     my ($r) = @_;
   88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   89:     $r->print('
   90: <br />
   91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   92: <p>
   93: '.&mt('Unable to retrieve a resource from a server:').'<br />
   94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   95: '.&mt('Error:').' '.$ssi_error_message.'
   96: </p>
   97: <p>'.
   98: &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 />'.
   99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  100: '</p>');
  101:     return;
  102: }
  103: 
  104: #
  105: # --- Retrieve the parts from the metadata file.---
  106: # Returns an array of everything that the resources stores away
  107: #
  108: 
  109: sub getpartlist {
  110:     my ($symb,$errorref) = @_;
  111: 
  112:     my $navmap   = Apache::lonnavmaps::navmap->new();
  113:     unless (ref($navmap)) {
  114:         if (ref($errorref)) { 
  115:             $$errorref = 'navmap';
  116:             return;
  117:         }
  118:     }
  119:     my $res      = $navmap->getBySymb($symb);
  120:     my $partlist = $res->parts();
  121:     my $url      = $res->src();
  122:     my $toolsymb;
  123:     if ($url =~ /ext\.tool$/) {
  124:         $toolsymb = $symb;
  125:     }
  126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  127: 
  128:     my @stores;
  129:     foreach my $part (@{ $partlist }) {
  130: 	foreach my $key (@metakeys) {
  131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  132: 	}
  133:     }
  134:     return @stores;
  135: }
  136: 
  137: #--- Format fullname, username:domain if different for display
  138: #--- Use anywhere where the student names are listed
  139: sub nameUserString {
  140:     my ($type,$fullname,$uname,$udom) = @_;
  141:     if ($type eq 'header') {
  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  143:     } else {
  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  146:     }
  147: }
  148: 
  149: #--- Get the partlist and the response type for a given problem. ---
  150: #--- Count responseIDs, essayresponse items, and dropbox items ---
  151: #--- Sets response_error pointer to "1" if navmaps object broken ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  169:     my %vPart = 
  170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  171:     my (%response_types,%handgrade);
  172:     foreach my $part (@{ $partlist }) {
  173: 	next if (%vPart && !exists($vPart{$part}));
  174: 
  175: 	my @types = $res->responseType($part);
  176: 	my @ids = $res->responseIds($part);
  177: 	for (my $i=0; $i < scalar(@ids); $i++) {
  178:             $numresp ++;
  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  180:             if ($types[$i] eq 'essay') {
  181:                 $numessay ++;
  182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  183:                     $numdropbox ++;
  184:                 }
  185:             }
  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
  187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  188: 				     '.handgrade',$symb);
  189: 	}
  190:     }
  191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  192: }
  193: 
  194: sub flatten_responseType {
  195:     my ($responseType) = @_;
  196:     my @part_response_id =
  197: 	map { 
  198: 	    my $part = $_;
  199: 	    map {
  200: 		[$part,$_]
  201: 		} sort(keys(%{ $responseType->{$part} }));
  202: 	} sort(keys(%$responseType));
  203:     return @part_response_id;
  204: }
  205: 
  206: sub get_display_part {
  207:     my ($partID,$symb)=@_;
  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  209:     if (defined($display) and $display ne '') {
  210:         $display.= ' (<span class="LC_internal_info">'
  211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  212:     } else {
  213: 	$display=$partID;
  214:     }
  215:     return $display;
  216: }
  217: 
  218: #--- Show parts and response type
  219: sub showResourceInfo {
  220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  222:         return '<br clear="all">';
  223:     }
  224:     my $coltitle = &mt('Problem Part Shown');
  225:     if ($checkboxes) {
  226:         $coltitle = &mt('Problem Part');
  227:     } else {
  228:         my $checkedparts = 0;
  229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  231:                 $checkedparts ++;
  232:             }
  233:         }
  234:         if ($checkedparts == scalar(@{$partlist})) {
  235:             return '<br clear="all">';
  236:         }
  237:         if ($uploads) {
  238:             $coltitle = &mt('Problem Part Selected');
  239:         }
  240:     }
  241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  242:     if ($checkboxes) {
  243:         my $legend = &mt('Parts to display');
  244:         if ($uploads) {
  245:             $legend = &mt('Part(s) with dropbox');
  246:         }
  247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  248:                    '<span class="LC_nobreak">'.
  249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  252:                    &mt('Selected parts').'</label></span>'.
  253:                    '<div id="LC_partselector" style="display:none">';
  254:     }
  255:     $result .= &Apache::loncommon::start_data_table()
  256:               .&Apache::loncommon::start_data_table_header_row();
  257:     if ($checkboxes) {
  258:         $result .= '<th>'.&mt('Display?').'</th>';
  259:     }
  260:     $result .= '<th>'.$coltitle.'</th>'
  261:               .'<th>'.&mt('Res. ID').'</th>'
  262:               .'<th>'.&mt('Type').'</th>'
  263:               .&Apache::loncommon::end_data_table_header_row();
  264:     my %partsseen;
  265:     foreach my $partID (sort(keys(%$responseType))) {
  266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  267:             my $responsetype = $responseType->{$partID}->{$resID};
  268:             if ($uploads) {
  269:                 next unless ($responsetype eq 'essay');
  270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  271:             }
  272:             my $display_part=&get_display_part($partID,$symb);
  273:             if (exists($partsseen{$partID})) {
  274:                 $result.=&Apache::loncommon::continue_data_table_row();
  275:             } else {
  276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  277:                 $result.=&Apache::loncommon::start_data_table_row().
  278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  279:                 if ($checkboxes) {
  280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  282:                 } else {
  283:                     $result.=$display_part.'</td>';
  284:                 }
  285:             }
  286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  287:                     .'<td>'.&mt($responsetype).'</td>'
  288:                     .&Apache::loncommon::end_data_table_row();
  289:         }
  290:     }
  291:     $result.=&Apache::loncommon::end_data_table();
  292:     if ($checkboxes) {
  293:         $result .= '</div></fieldset>';
  294:     }
  295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  296:     return $result;
  297: }
  298: 
  299: sub part_selector_js {
  300:     my $js = <<"END";
  301: function toggleParts(formname) {
  302:     if (document.getElementById('LC_partselector')) {
  303:         var index = '';
  304:         if (document.forms.length) {
  305:             for (var i=0; i<document.forms.length; i++) {
  306:                 if (document.forms[i].name == formname) {
  307:                     index = i;
  308:                     break;
  309:                 }
  310:             }
  311:         }
  312:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  313:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  314:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  315:                    var val = document.forms[index].elements['chooseparts'][i].value;
  316:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  317:                         document.getElementById('LC_partselector').style.display = 'block';
  318:                     } else {
  319:                         document.getElementById('LC_partselector').style.display = 'none';
  320:                     }
  321:                 }
  322:             }
  323:         }
  324:     }
  325: }
  326: END
  327:     return &Apache::lonhtmlcommon::scripttag($js);
  328: }
  329: 
  330: sub reset_caches {
  331:     &reset_analyze_cache();
  332:     &reset_perm();
  333:     &reset_old_essays();
  334: }
  335: 
  336: {
  337:     my %analyze_cache;
  338:     my %analyze_cache_formkeys;
  339: 
  340:     sub reset_analyze_cache {
  341: 	undef(%analyze_cache);
  342:         undef(%analyze_cache_formkeys);
  343:     }
  344: 
  345:     sub get_analyze {
  346: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  347: 	my $key = "$symb\0$uname\0$udom";
  348:         if ($type eq 'randomizetry') {
  349:             if ($trial ne '') {
  350:                 $key .= "\0".$trial;
  351:             }
  352:         }
  353: 	if (exists($analyze_cache{$key})) {
  354:             my $getupdate = 0;
  355:             if (ref($add_to_hash) eq 'HASH') {
  356:                 foreach my $item (keys(%{$add_to_hash})) {
  357:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  358:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  359:                             $getupdate = 1;
  360:                             last;
  361:                         }
  362:                     } else {
  363:                         $getupdate = 1;
  364:                     }
  365:                 }
  366:             }
  367:             if (!$getupdate) {
  368:                 return $analyze_cache{$key};
  369:             }
  370:         }
  371: 
  372: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  373: 	$url=&Apache::lonnet::clutter($url);
  374:         my %form = ('grade_target'      => 'analyze',
  375:                     'grade_domain'      => $udom,
  376:                     'grade_symb'        => $symb,
  377:                     'grade_courseid'    =>  $env{'request.course.id'},
  378:                     'grade_username'    => $uname,
  379:                     'grade_noincrement' => $no_increment);
  380:         if ($bubbles_per_row ne '') {
  381:             $form{'bubbles_per_row'} = $bubbles_per_row;
  382:         }
  383:         if ($type eq 'randomizetry') {
  384:             $form{'grade_questiontype'} = $type;
  385:             if ($rndseed ne '') {
  386:                 $form{'grade_rndseed'} = $rndseed;
  387:             }
  388:         }
  389:         if (ref($add_to_hash)) {
  390:             %form = (%form,%{$add_to_hash});
  391:         }
  392: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  393: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  394: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  395:         if (ref($add_to_hash) eq 'HASH') {
  396:             $analyze_cache_formkeys{$key} = $add_to_hash;
  397:         } else {
  398:             $analyze_cache_formkeys{$key} = {};
  399:         }
  400: 	return $analyze_cache{$key} = \%analyze;
  401:     }
  402: 
  403:     sub get_order {
  404: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  405: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  406: 	return $analyze->{"$partid.$respid.shown"};
  407:     }
  408: 
  409:     sub get_radiobutton_correct_foil {
  410: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  411: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  412:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  413:         if (ref($foils) eq 'ARRAY') {
  414: 	    foreach my $foil (@{$foils}) {
  415: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  416: 		    return $foil;
  417: 	        }
  418: 	    }
  419: 	}
  420:     }
  421: 
  422:     sub scantron_partids_tograde {
  423:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  424:         my (%analysis,@parts);
  425:         if (ref($resource)) {
  426:             my $symb = $resource->symb();
  427:             my $add_to_form;
  428:             if ($check_for_randomlist) {
  429:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  430:             }
  431:             if ($scancode) {
  432:                 if (ref($add_to_form) eq 'HASH') {
  433:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  434:                 } else {
  435:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  436:                 }
  437:             }
  438:             my $analyze =
  439:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  440:                              undef,undef,undef,$bubbles_per_row);
  441:             if (ref($analyze) eq 'HASH') {
  442:                 %analysis = %{$analyze};
  443:             }
  444:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  445:                 foreach my $part (@{$analysis{'parts'}}) {
  446:                     my ($id,$respid) = split(/\./,$part);
  447:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  448:                         push(@parts,$part);
  449:                     }
  450:                 }
  451:             }
  452:         }
  453:         return (\%analysis,\@parts);
  454:     }
  455: 
  456: }
  457: 
  458: #--- Clean response type for display
  459: #--- Currently filters option/rank/radiobutton/match/essay/Task
  460: #        response types only.
  461: sub cleanRecord {
  462:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  463: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  464:     my $grayFont = '<span class="LC_internal_info">';
  465:     if ($response =~ /^(option|rank)$/) {
  466: 	my %answer=&Apache::lonnet::str2hash($answer);
  467:         my @answer = %answer;
  468:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  469: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  470: 	my ($toprow,$bottomrow);
  471: 	foreach my $foil (@$order) {
  472: 	    if ($grading{$foil} == 1) {
  473: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  474: 	    } else {
  475: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  476: 	    }
  477: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  478: 	}
  479: 	return '<blockquote><table border="1">'.
  480: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  481: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  482: 	    $bottomrow.'</tr></table></blockquote>';
  483:     } elsif ($response eq 'match') {
  484: 	my %answer=&Apache::lonnet::str2hash($answer);
  485:         my @answer = %answer;
  486:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  487: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  488: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  489: 	my ($toprow,$middlerow,$bottomrow);
  490: 	foreach my $foil (@$order) {
  491: 	    my $item=shift(@items);
  492: 	    if ($grading{$foil} == 1) {
  493: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  494: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  495: 	    } else {
  496: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  497: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  498: 	    }
  499: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  500: 	}
  501: 	return '<blockquote><table border="1">'.
  502: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  503: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  504: 	    $middlerow.'</tr>'.
  505: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  506: 	    $bottomrow.'</tr></table></blockquote>';
  507:     } elsif ($response eq 'radiobutton') {
  508: 	my %answer=&Apache::lonnet::str2hash($answer);
  509:         my @answer = %answer;
  510:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  511: 	my ($toprow,$bottomrow);
  512: 	my $correct = 
  513: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  514: 	foreach my $foil (@$order) {
  515: 	    if (exists($answer{$foil})) {
  516: 		if ($foil eq $correct) {
  517: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  518: 		} else {
  519: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  520: 		}
  521: 	    } else {
  522: 		$toprow.='<td>'.&mt('false').'</td>';
  523: 	    }
  524: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  525: 	}
  526: 	return '<blockquote><table border="1">'.
  527: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  528: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  529: 	    $bottomrow.'</tr></table></blockquote>';
  530:     } elsif ($response eq 'essay') {
  531: 	if (! exists ($env{'form.'.$symb})) {
  532: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  533: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  534: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  535: 
  536: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  537: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  538: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  539: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  540: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  541: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  542: 	}
  543:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  544: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  545:     } elsif ( $response eq 'organic') {
  546:         my $result=&mt('Smile representation: [_1]',
  547:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  548: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  549: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  550: 	return $result;
  551:     } elsif ( $response eq 'Task') {
  552: 	if ( $answer eq 'SUBMITTED') {
  553: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  554: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  555: 	    return $result;
  556: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  557: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  558: 			       keys(%{$record}));
  559: 	    return join('<br />',($version,@matches));
  560: 			       
  561: 			       
  562: 	} else {
  563: 	    my $result =
  564: 		'<p>'
  565: 		.&mt('Overall result: [_1]',
  566: 		     $record->{$version."resource.$respid.$partid.status"})
  567: 		.'</p>';
  568: 	    
  569: 	    $result .= '<ul>';
  570: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  571: 			     keys(%{$record}));
  572: 	    foreach my $grade (sort(@grade)) {
  573: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  574: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  575: 				     $dim, $record->{$grade}).
  576: 			  '</li>';
  577: 	    }
  578: 	    $result.='</ul>';
  579: 	    return $result;
  580: 	}
  581:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  582:         # Respect multiple input fields, see Bug #5409
  583: 	$answer = 
  584: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  585: 							      $answer);
  586: 	return $answer;
  587:     }
  588:     return &HTML::Entities::encode($answer, '"<>&');
  589: }
  590: 
  591: #-- A couple of common js functions
  592: sub commonJSfunctions {
  593:     my $request = shift;
  594:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  595:     function radioSelection(radioButton) {
  596: 	var selection=null;
  597: 	if (radioButton.length > 1) {
  598: 	    for (var i=0; i<radioButton.length; i++) {
  599: 		if (radioButton[i].checked) {
  600: 		    return radioButton[i].value;
  601: 		}
  602: 	    }
  603: 	} else {
  604: 	    if (radioButton.checked) return radioButton.value;
  605: 	}
  606: 	return selection;
  607:     }
  608: 
  609:     function pullDownSelection(selectOne) {
  610: 	var selection="";
  611: 	if (selectOne.length > 1) {
  612: 	    for (var i=0; i<selectOne.length; i++) {
  613: 		if (selectOne[i].selected) {
  614: 		    return selectOne[i].value;
  615: 		}
  616: 	    }
  617: 	} else {
  618:             // only one value it must be the selected one
  619: 	    return selectOne.value;
  620: 	}
  621:     }
  622: COMMONJSFUNCTIONS
  623: }
  624: 
  625: #--- Dumps the class list with usernames,list of sections,
  626: #--- section, ids and fullnames for each user.
  627: sub getclasslist {
  628:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  629:     my @getsec;
  630:     my @getgroup;
  631:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  632:     if (!ref($getsec)) {
  633: 	if ($getsec ne '' && $getsec ne 'all') {
  634: 	    @getsec=($getsec);
  635: 	}
  636:     } else {
  637: 	@getsec=@{$getsec};
  638:     }
  639:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  640:     if (!ref($getgroup)) {
  641: 	if ($getgroup ne '' && $getgroup ne 'all') {
  642: 	    @getgroup=($getgroup);
  643: 	}
  644:     } else {
  645: 	@getgroup=@{$getgroup};
  646:     }
  647:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  648: 
  649:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  650:     # Bail out if we were unable to get the classlist
  651:     return if (! defined($classlist));
  652:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  653:     #
  654:     my %sections;
  655:     my %fullnames;
  656:     my ($cdom,$cnum,$partlist);
  657:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  658:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  659:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  660:         my $res_error;
  661:         ($partlist) = &response_type($symb,\$res_error);
  662:     }
  663:     foreach my $student (keys(%$classlist)) {
  664:         my $end      = 
  665:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  666:         my $start    = 
  667:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  668:         my $id       = 
  669:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  670:         my $section  = 
  671:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  672:         my $fullname = 
  673:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  674:         my $status   = 
  675:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  676:         my $group   = 
  677:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  678: 	# filter students according to status selected
  679: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  680: 	    if (!($stu_status =~ $status)) {
  681: 		delete($classlist->{$student});
  682: 		next;
  683: 	    }
  684: 	}
  685: 	# filter students according to groups selected
  686: 	my @stu_groups = split(/,/,$group);
  687: 	if (@getgroup) {
  688: 	    my $exclude = 1;
  689: 	    foreach my $grp (@getgroup) {
  690: 	        foreach my $stu_group (@stu_groups) {
  691: 	            if ($stu_group eq $grp) {
  692: 	                $exclude = 0;
  693:     	            } 
  694: 	        }
  695:     	        if (($grp eq 'none') && !$group) {
  696:         	    $exclude = 0;
  697:         	}
  698: 	    }
  699: 	    if ($exclude) {
  700: 	        delete($classlist->{$student});
  701: 		next;
  702: 	    }
  703: 	}
  704:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  705:             my $udom =
  706:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  707:             my $uname =
  708:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  709:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  710:                 if ($submitonly eq 'queued') {
  711:                     my %queue_status =
  712:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  713:                                                                 $udom,$uname);
  714:                     if (!defined($queue_status{'gradingqueue'})) {
  715:                         delete($classlist->{$student});
  716:                         next;
  717:                     }
  718:                 } else {
  719:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  720:                     my $submitted = 0;
  721:                     my $graded = 0;
  722:                     my $incorrect = 0;
  723:                     foreach (keys(%status)) {
  724:                         $submitted = 1 if ($status{$_} ne 'nothing');
  725:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  726:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  727: 
  728:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  729:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  730:                             $submitted = 0;
  731:                         }
  732:                     }
  733:                     if (!$submitted && ($submitonly eq 'yes' ||
  734:                                         $submitonly eq 'incorrect' ||
  735:                                         $submitonly eq 'graded')) {
  736:                         delete($classlist->{$student});
  737:                         next;
  738:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  739:                         delete($classlist->{$student});
  740:                         next;
  741:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  742:                         delete($classlist->{$student});
  743:                         next;
  744:                     }
  745:                 }
  746:             }
  747:         }
  748: 	$section = ($section ne '' ? $section : 'none');
  749: 	if (&canview($section)) {
  750: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  751: 		$sections{$section}++;
  752: 		if ($classlist->{$student}) {
  753: 		    $fullnames{$student}=$fullname;
  754: 		}
  755: 	    } else {
  756: 		delete($classlist->{$student});
  757: 	    }
  758: 	} else {
  759: 	    delete($classlist->{$student});
  760: 	}
  761:     }
  762:     my @sections = sort(keys(%sections));
  763:     return ($classlist,\@sections,\%fullnames);
  764: }
  765: 
  766: sub canmodify {
  767:     my ($sec)=@_;
  768:     if ($perm{'mgr'}) {
  769: 	if (!defined($perm{'mgr_section'})) {
  770: 	    # can modify whole class
  771: 	    return 1;
  772: 	} else {
  773: 	    if ($sec eq $perm{'mgr_section'}) {
  774: 		#can modify the requested section
  775: 		return 1;
  776: 	    } else {
  777: 		# can't modify the requested section
  778: 		return 0;
  779: 	    }
  780: 	}
  781:     }
  782:     #can't modify
  783:     return 0;
  784: }
  785: 
  786: sub canview {
  787:     my ($sec)=@_;
  788:     if ($perm{'vgr'}) {
  789: 	if (!defined($perm{'vgr_section'})) {
  790: 	    # can view whole class
  791: 	    return 1;
  792: 	} else {
  793: 	    if ($sec eq $perm{'vgr_section'}) {
  794: 		#can view the requested section
  795: 		return 1;
  796: 	    } else {
  797: 		# can't view the requested section
  798: 		return 0;
  799: 	    }
  800: 	}
  801:     }
  802:     #can't view
  803:     return 0;
  804: }
  805: 
  806: #--- Retrieve the grade status of a student for all the parts
  807: sub student_gradeStatus {
  808:     my ($symb,$udom,$uname,$partlist) = @_;
  809:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  810:     my %partstatus = ();
  811:     foreach (@$partlist) {
  812: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  813: 	$status              = 'nothing' if ($status eq '');
  814: 	$partstatus{$_}      = $status;
  815: 	my $subkey           = "resource.$_.submitted_by";
  816: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  817:     }
  818:     return %partstatus;
  819: }
  820: 
  821: # hidden form and javascript that calls the form
  822: # Use by verifyscript and viewgrades
  823: # Shows a student's view of problem and submission
  824: sub jscriptNform {
  825:     my ($symb) = @_;
  826:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  827:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  828: 	'    function viewOneStudent(user,domain) {'."\n".
  829: 	'	document.onestudent.student.value = user;'."\n".
  830: 	'	document.onestudent.userdom.value = domain;'."\n".
  831: 	'	document.onestudent.submit();'."\n".
  832: 	'    }'."\n".
  833: 	"\n");
  834:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  835: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  836: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  837: 	'<input type="hidden" name="command" value="submission" />'."\n".
  838: 	'<input type="hidden" name="student" value="" />'."\n".
  839: 	'<input type="hidden" name="userdom" value="" />'."\n".
  840: 	'</form>'."\n";
  841:     return $jscript;
  842: }
  843: 
  844: 
  845: 
  846: # Given the score (as a number [0-1] and the weight) what is the final
  847: # point value? This function will round to the nearest tenth, third,
  848: # or quarter if one of those is within the tolerance of .00001.
  849: sub compute_points {
  850:     my ($score, $weight) = @_;
  851:     
  852:     my $tolerance = .00001;
  853:     my $points = $score * $weight;
  854: 
  855:     # Check for nearness to 1/x.
  856:     my $check_for_nearness = sub {
  857:         my ($factor) = @_;
  858:         my $num = ($points * $factor) + $tolerance;
  859:         my $floored_num = floor($num);
  860:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  861:             return $floored_num / $factor;
  862:         }
  863:         return $points;
  864:     };
  865: 
  866:     $points = $check_for_nearness->(10);
  867:     $points = $check_for_nearness->(3);
  868:     $points = $check_for_nearness->(4);
  869:     
  870:     return $points;
  871: }
  872: 
  873: #------------------ End of general use routines --------------------
  874: 
  875: #
  876: # Find most similar essay
  877: #
  878: 
  879: sub most_similar {
  880:     my ($uname,$udom,$symb,$uessay)=@_;
  881: 
  882:     unless ($symb) { return ''; }
  883: 
  884:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  885: 
  886: # ignore spaces and punctuation
  887: 
  888:     $uessay=~s/\W+/ /gs;
  889: 
  890: # ignore empty submissions (occuring when only files are sent)
  891: 
  892:     unless ($uessay=~/\w+/s) { return ''; }
  893: 
  894: # these will be returned. Do not care if not at least 50 percent similar
  895:     my $limit=0.6;
  896:     my $sname='';
  897:     my $sdom='';
  898:     my $scrsid='';
  899:     my $sessay='';
  900: # go through all essays ...
  901:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  902: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  903: # ... except the same student
  904:         next if (($tname eq $uname) && ($tdom eq $udom));
  905: 	my $tessay=$old_essays{$symb}{$tkey};
  906: 	$tessay=~s/\W+/ /gs;
  907: # String similarity gives up if not even limit
  908: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  909: # Found one
  910: 	if ($tsimilar>$limit) {
  911: 	    $limit=$tsimilar;
  912: 	    $sname=$tname;
  913: 	    $sdom=$tdom;
  914: 	    $scrsid=$tcrsid;
  915: 	    $sessay=$old_essays{$symb}{$tkey};
  916: 	}
  917:     }
  918:     if ($limit>0.6) {
  919:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  920:     } else {
  921:        return ('','','','',0);
  922:     }
  923: }
  924: 
  925: #-------------------------------------------------------------------
  926: 
  927: #------------------------------------ Receipt Verification Routines
  928: #
  929: 
  930: sub initialverifyreceipt {
  931:    my ($request,$symb) = @_;
  932:    &commonJSfunctions($request);
  933:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  934:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  935:         '-<input type="text" name="receipt" size="4" />'.
  936:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  937:         '<input type="hidden" name="command" value="verify" />'.
  938:         "</form>\n";
  939: }
  940: 
  941: #--- Check whether a receipt number is valid.---
  942: sub verifyreceipt {
  943:     my ($request,$symb) = @_;
  944: 
  945:     my $courseid = $env{'request.course.id'};
  946:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  947: 	$env{'form.receipt'};
  948:     $receipt     =~ s/[^\-\d]//g;
  949: 
  950:     my $title =
  951: 	'<h3><span class="LC_info">'.
  952: 	&mt('Verifying Receipt Number [_1]',$receipt).
  953: 	'</span></h3>'."\n";
  954: 
  955:     my ($string,$contents,$matches) = ('','',0);
  956:     my (undef,undef,$fullname) = &getclasslist('all','0');
  957:     
  958:     my $receiptparts=0;
  959:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  960: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  961:     my $parts=['0'];
  962:     if ($receiptparts) {
  963:         my $res_error; 
  964:         ($parts)=&response_type($symb,\$res_error);
  965:         if ($res_error) {
  966:             return &navmap_errormsg();
  967:         } 
  968:     }
  969:     
  970:     my $header = 
  971: 	&Apache::loncommon::start_data_table().
  972: 	&Apache::loncommon::start_data_table_header_row().
  973: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  974: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  975: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  976:     if ($receiptparts) {
  977: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  978:     }
  979:     $header.=
  980: 	&Apache::loncommon::end_data_table_header_row();
  981: 
  982:     foreach (sort 
  983: 	     {
  984: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  985: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  986: 		 }
  987: 		 return $a cmp $b;
  988: 	     } (keys(%$fullname))) {
  989: 	my ($uname,$udom)=split(/\:/);
  990: 	foreach my $part (@$parts) {
  991: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  992: 		$contents.=
  993: 		    &Apache::loncommon::start_data_table_row().
  994: 		    '<td>&nbsp;'."\n".
  995: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  996: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  997: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  998: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  999: 		if ($receiptparts) {
 1000: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1001: 		}
 1002: 		$contents.= 
 1003: 		    &Apache::loncommon::end_data_table_row()."\n";
 1004: 		
 1005: 		$matches++;
 1006: 	    }
 1007: 	}
 1008:     }
 1009:     if ($matches == 0) {
 1010:         $string = $title
 1011:                  .'<p class="LC_warning">'
 1012:                  .&mt('No match found for the above receipt number.')
 1013:                  .'</p>';
 1014:     } else {
 1015: 	$string = &jscriptNform($symb).$title.
 1016: 	    '<p>'.
 1017: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1018: 	    '</p>'.
 1019: 	    $header.
 1020: 	    $contents.
 1021: 	    &Apache::loncommon::end_data_table()."\n";
 1022:     }
 1023:     return $string;
 1024: }
 1025: 
 1026: #--- This is called by a number of programs.
 1027: #--- Called from the Grading Menu - View/Grade an individual student
 1028: #--- Also called directly when one clicks on the subm button 
 1029: #    on the problem page.
 1030: sub listStudents {
 1031:     my ($request,$symb,$submitonly,$divforres) = @_;
 1032: 
 1033:     my $is_tool   = ($symb =~ /ext\.tool$/);
 1034:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1035:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1036:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1037:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1038:     unless ($submitonly) {
 1039:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1040:     }
 1041: 
 1042:     my $result='';
 1043:     my $res_error;
 1044:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1045: 
 1046:     my $table;
 1047:     if (ref($partlist) eq 'ARRAY') {
 1048:         if (scalar(@$partlist) > 1 ) {
 1049:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1050:         } elsif ($divforres) {
 1051:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1052:         } else {
 1053:             $table = '<br clear="all" />';
 1054:         }
 1055:     }
 1056: 
 1057:     my %js_lt = &Apache::lonlocal::texthash (
 1058: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1059: 		'single'   => 'Please select the student before clicking on the Next button.',
 1060: 	     );
 1061:     &js_escape(\%js_lt);
 1062:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1063:     function checkSelect(checkBox) {
 1064: 	var ctr=0;
 1065: 	var sense="";
 1066: 	if (checkBox.length > 1) {
 1067: 	    for (var i=0; i<checkBox.length; i++) {
 1068: 		if (checkBox[i].checked) {
 1069: 		    ctr++;
 1070: 		}
 1071: 	    }
 1072: 	    sense = '$js_lt{'multiple'}';
 1073: 	} else {
 1074: 	    if (checkBox.checked) {
 1075: 		ctr = 1;
 1076: 	    }
 1077: 	    sense = '$js_lt{'single'}';
 1078: 	}
 1079: 	if (ctr == 0) {
 1080: 	    alert(sense);
 1081: 	    return false;
 1082: 	}
 1083: 	document.gradesub.submit();
 1084:     }
 1085: 
 1086:     function reLoadList(formname) {
 1087: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1088: 	formname.command.value = 'submission';
 1089: 	formname.submit();
 1090:     }
 1091: LISTJAVASCRIPT
 1092: 
 1093:     &commonJSfunctions($request);
 1094:     $request->print($result);
 1095: 
 1096:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1097: 	"\n".$table;
 1098: 
 1099:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1100:     unless ($is_tool) {
 1101:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1102:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1103:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1104:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1105:                       .&Apache::lonhtmlcommon::row_closure();
 1106:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1107:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1108:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1109:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1110:                       .&Apache::lonhtmlcommon::row_closure();
 1111:     }
 1112: 
 1113:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1114:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1115:     $env{'form.Status'} = $saveStatus;
 1116:     my %optiontext;
 1117:     if ($is_tool) {
 1118:         %optiontext = &Apache::lonlocal::texthash (
 1119:                           lastonly => 'last transaction',
 1120:                           last     => 'last transaction with details',
 1121:                           datesub  => 'all transactions',
 1122:                           all      => 'all transactions with details',
 1123:                       );
 1124:     } else {
 1125:         %optiontext = &Apache::lonlocal::texthash (
 1126:                           lastonly => 'last submission',
 1127:                           last     => 'last submission with details',
 1128:                           datesub  => 'all submissions',
 1129:                           all      => 'all submissions with details',
 1130:                       );
 1131:     }
 1132:     my $submission_options =
 1133:         '<span class="LC_nobreak">'.
 1134:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1135:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1136:         '<span class="LC_nobreak">'.
 1137:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1138:         $optiontext{'last'}.' </label></span>'."\n".
 1139:         '<span class="LC_nobreak">'.
 1140:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1141:         $optiontext{'datesub'}.'</label></span>'."\n".
 1142:         '<span class="LC_nobreak">'.
 1143:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1144:         $optiontext{'all'}.'</label></span>';
 1145:     my $viewtitle;
 1146:     if ($is_tool) {
 1147:         $viewtitle = &mt('View Transactions');
 1148:     } else {
 1149:         $viewtitle = &mt('View Submissions');
 1150:     }
 1151:     my ($compmsg,$nocompmsg);
 1152:     $nocompmsg = ' checked="checked"';
 1153:     if ($numessay) {
 1154:         $compmsg = $nocompmsg;
 1155:         $nocompmsg = '';
 1156:     }
 1157:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1158:                   .$submission_options
 1159:                   .&Apache::lonhtmlcommon::row_closure()
 1160:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1161:                   .'<span class="LC_nobreak">'
 1162:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1163:                   .&mt('No').('&nbsp;'x2).'</label>'
 1164:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1165:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1166:                   .&Apache::lonhtmlcommon::row_closure();
 1167: 
 1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1169:                   .'<select name="increment">'
 1170:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1171:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1172:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1173:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1174:                   .'</select>';
 1175:     $gradeTable .= 
 1176:         &build_section_inputs().
 1177: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1178: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1179: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1180:     if (exists($env{'form.Status'})) {
 1181: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1182:     } else {
 1183:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1184:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1185:                       .&Apache::lonhtmlcommon::StatusOptions(
 1186:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1187:     }
 1188:     if ($numessay) {
 1189:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1190:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1191:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1192:     }
 1193:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1194:                   .&Apache::lonhtmlcommon::end_pick_box();
 1195:     my $regrademsg;
 1196:     if ($is_tool) {
 1197:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1198:     } else {
 1199:         $regrademsg = &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.");
 1200:     }
 1201:     $gradeTable .= '<p>'
 1202:                   .$regrademsg."\n"
 1203:                   .'<input type="hidden" name="command" value="processGroup" />'
 1204:                   .'</p>';
 1205: 
 1206: # checkall buttons
 1207:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1208:     $gradeTable.='<input type="button" '."\n".
 1209:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1210:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1211:     $gradeTable.=&check_buttons();
 1212:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1213:     $gradeTable.= &Apache::loncommon::start_data_table().
 1214: 	&Apache::loncommon::start_data_table_header_row();
 1215:     my $loop = 0;
 1216:     while ($loop < 2) {
 1217: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1218: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1219: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1220: 	    foreach my $part (sort(@$partlist)) {
 1221: 		my $display_part=
 1222: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1223: 		$gradeTable.=
 1224: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1225: 	    }
 1226: 	} elsif ($submitonly eq 'queued') {
 1227: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1228: 	}
 1229: 	$loop++;
 1230: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1231:     }
 1232:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1233: 
 1234:     my $ctr = 0;
 1235:     foreach my $student (sort 
 1236: 			 {
 1237: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1238: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1239: 			     }
 1240: 			     return $a cmp $b;
 1241: 			 }
 1242: 			 (keys(%$fullname))) {
 1243: 	my ($uname,$udom) = split(/:/,$student);
 1244: 
 1245: 	my %status = ();
 1246: 
 1247: 	if ($submitonly eq 'queued') {
 1248: 	    my %queue_status = 
 1249: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1250: 							$udom,$uname);
 1251: 	    next if (!defined($queue_status{'gradingqueue'}));
 1252: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1253: 	}
 1254: 
 1255: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1256: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1257: 	    my $submitted = 0;
 1258: 	    my $graded = 0;
 1259: 	    my $incorrect = 0;
 1260: 	    foreach (keys(%status)) {
 1261: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1262: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1263: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1264: 		
 1265: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1266: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1267: 		    $submitted = 0;
 1268: 		    my ($part)=split(/\./,$partid);
 1269: 		    $gradeTable.='<input type="hidden" name="'.
 1270: 			$student.':'.$part.':submitted_by" value="'.
 1271: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1272: 		}
 1273: 	    }
 1274: 	    
 1275: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1276: 				     $submitonly eq 'incorrect' ||
 1277: 				     $submitonly eq 'graded'));
 1278: 	    next if (!$graded && ($submitonly eq 'graded'));
 1279: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1280: 	}
 1281: 
 1282: 	$ctr++;
 1283: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1284:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1285: 	if ( $perm{'vgr'} eq 'F' ) {
 1286: 	    if ($ctr%2 ==1) {
 1287: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1288: 	    }
 1289: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1290:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1291:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1292: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1293: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1294: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1295: 
 1296: 	    if ($submitonly ne 'all') {
 1297: 		foreach (sort(keys(%status))) {
 1298: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1299: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1300: 		}
 1301: 	    }
 1302: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1303: 	    if ($ctr%2 ==0) {
 1304: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1305: 	    }
 1306: 	}
 1307:     }
 1308:     if ($ctr%2 ==1) {
 1309: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1310: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1311: 		foreach (@$partlist) {
 1312: 		    $gradeTable.='<td>&nbsp;</td>';
 1313: 		}
 1314: 	    } elsif ($submitonly eq 'queued') {
 1315: 		$gradeTable.='<td>&nbsp;</td>';
 1316: 	    }
 1317: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1318:     }
 1319: 
 1320:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1321:         '<input type="button" '.
 1322:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1323:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1324:     if ($ctr == 0) {
 1325: 	my $num_students=(scalar(keys(%$fullname)));
 1326: 	if ($num_students eq 0) {
 1327: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1328: 	} else {
 1329: 	    my $submissions='submissions';
 1330: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1331: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1332: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1333: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1334: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1335: 		    $num_students).
 1336: 		'</span><br />';
 1337: 	}
 1338:     } elsif ($ctr == 1) {
 1339: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1340:     }
 1341:     $request->print($gradeTable);
 1342:     return '';
 1343: }
 1344: 
 1345: #---- Called from the listStudents routine
 1346: 
 1347: sub check_script {
 1348:     my ($form,$type) = @_;
 1349:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1350:     function checkall() {
 1351:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1352:             ele = document.forms.'.$form.'.elements[i];
 1353:             if (ele.name == "'.$type.'") {
 1354:             document.forms.'.$form.'.elements[i].checked=true;
 1355:                                        }
 1356:         }
 1357:     }
 1358: 
 1359:     function checksec() {
 1360:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1361:             ele = document.forms.'.$form.'.elements[i];
 1362:            string = document.forms.'.$form.'.chksec.value;
 1363:            if
 1364:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1365:               document.forms.'.$form.'.elements[i].checked=true;
 1366:             }
 1367:         }
 1368:     }
 1369: 
 1370: 
 1371:     function uncheckall() {
 1372:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1373:             ele = document.forms.'.$form.'.elements[i];
 1374:             if (ele.name == "'.$type.'") {
 1375:             document.forms.'.$form.'.elements[i].checked=false;
 1376:                                        }
 1377:         }
 1378:     }
 1379: 
 1380: '."\n");
 1381:     return $chkallscript;
 1382: }
 1383: 
 1384: sub check_buttons {
 1385:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1386:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1387:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1388:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1389:     return $buttons;
 1390: }
 1391: 
 1392: #     Displays the submissions for one student or a group of students
 1393: sub processGroup {
 1394:     my ($request,$symb) = @_;
 1395:     my $ctr        = 0;
 1396:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1397:     my $total      = scalar(@stuchecked)-1;
 1398: 
 1399:     foreach my $student (@stuchecked) {
 1400: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1401: 	$env{'form.student'}        = $uname;
 1402: 	$env{'form.userdom'}        = $udom;
 1403: 	$env{'form.fullname'}       = $fullname;
 1404: 	&submission($request,$ctr,$total,$symb);
 1405: 	$ctr++;
 1406:     }
 1407:     return '';
 1408: }
 1409: 
 1410: #------------------------------------------------------------------------------------
 1411: #
 1412: #-------------------------- Next few routines handles grading by student, essentially
 1413: #                           handles essay response type problem/part
 1414: #
 1415: #--- Javascript to handle the submission page functionality ---
 1416: sub sub_page_js {
 1417:     my $request = shift;
 1418:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1419:     &js_escape(\$alertmsg);
 1420:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1421:     function updateRadio(formname,id,weight) {
 1422: 	var gradeBox = formname["GD_BOX"+id];
 1423: 	var radioButton = formname["RADVAL"+id];
 1424: 	var oldpts = formname["oldpts"+id].value;
 1425: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1426: 	gradeBox.value = pts;
 1427: 	var resetbox = false;
 1428: 	if (isNaN(pts) || pts < 0) {
 1429: 	    alert("$alertmsg"+pts);
 1430: 	    for (var i=0; i<radioButton.length; i++) {
 1431: 		if (radioButton[i].checked) {
 1432: 		    gradeBox.value = i;
 1433: 		    resetbox = true;
 1434: 		}
 1435: 	    }
 1436: 	    if (!resetbox) {
 1437: 		formtextbox.value = "";
 1438: 	    }
 1439: 	    return;
 1440: 	}
 1441: 
 1442: 	if (pts > weight) {
 1443: 	    var resp = confirm("You entered a value ("+pts+
 1444: 			       ") greater than the weight for the part. Accept?");
 1445: 	    if (resp == false) {
 1446: 		gradeBox.value = oldpts;
 1447: 		return;
 1448: 	    }
 1449: 	}
 1450: 
 1451: 	for (var i=0; i<radioButton.length; i++) {
 1452: 	    radioButton[i].checked=false;
 1453: 	    if (pts == i && pts != "") {
 1454: 		radioButton[i].checked=true;
 1455: 	    }
 1456: 	}
 1457: 	updateSelect(formname,id);
 1458: 	formname["stores"+id].value = "0";
 1459:     }
 1460: 
 1461:     function writeBox(formname,id,pts) {
 1462: 	var gradeBox = formname["GD_BOX"+id];
 1463: 	if (checkSolved(formname,id) == 'update') {
 1464: 	    gradeBox.value = pts;
 1465: 	} else {
 1466: 	    var oldpts = formname["oldpts"+id].value;
 1467: 	    gradeBox.value = oldpts;
 1468: 	    var radioButton = formname["RADVAL"+id];
 1469: 	    for (var i=0; i<radioButton.length; i++) {
 1470: 		radioButton[i].checked=false;
 1471: 		if (i == oldpts) {
 1472: 		    radioButton[i].checked=true;
 1473: 		}
 1474: 	    }
 1475: 	}
 1476: 	formname["stores"+id].value = "0";
 1477: 	updateSelect(formname,id);
 1478: 	return;
 1479:     }
 1480: 
 1481:     function clearRadBox(formname,id) {
 1482: 	if (checkSolved(formname,id) == 'noupdate') {
 1483: 	    updateSelect(formname,id);
 1484: 	    return;
 1485: 	}
 1486: 	gradeSelect = formname["GD_SEL"+id];
 1487: 	for (var i=0; i<gradeSelect.length; i++) {
 1488: 	    if (gradeSelect[i].selected) {
 1489: 		var selectx=i;
 1490: 	    }
 1491: 	}
 1492: 	var stores = formname["stores"+id];
 1493: 	if (selectx == stores.value) { return };
 1494: 	var gradeBox = formname["GD_BOX"+id];
 1495: 	gradeBox.value = "";
 1496: 	var radioButton = formname["RADVAL"+id];
 1497: 	for (var i=0; i<radioButton.length; i++) {
 1498: 	    radioButton[i].checked=false;
 1499: 	}
 1500: 	stores.value = selectx;
 1501:     }
 1502: 
 1503:     function checkSolved(formname,id) {
 1504: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1505: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1506: 	    if (!reply) {return "noupdate";}
 1507: 	    formname.overRideScore.value = 'yes';
 1508: 	}
 1509: 	return "update";
 1510:     }
 1511: 
 1512:     function updateSelect(formname,id) {
 1513: 	formname["GD_SEL"+id][0].selected = true;
 1514: 	return;
 1515:     }
 1516: 
 1517: //=========== Check that a point is assigned for all the parts  ============
 1518:     function checksubmit(formname,val,total,parttot) {
 1519: 	formname.gradeOpt.value = val;
 1520: 	if (val == "Save & Next") {
 1521: 	    for (i=0;i<=total;i++) {
 1522: 		for (j=0;j<parttot;j++) {
 1523: 		    var partid = formname["partid"+i+"_"+j].value;
 1524: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1525: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1526: 			if (points == "") {
 1527: 			    var name = formname["name"+i].value;
 1528: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1529: 			    var resp = confirm("You did not assign a score for "+studentID+
 1530: 					       ", part "+partid+". Continue?");
 1531: 			    if (resp == false) {
 1532: 				formname["GD_BOX"+i+"_"+partid].focus();
 1533: 				return false;
 1534: 			    }
 1535: 			}
 1536: 		    }
 1537: 		}
 1538: 	    }
 1539: 	}
 1540: 	formname.submit();
 1541:     }
 1542: 
 1543: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1544:     function checkSubmitPage(formname,total) {
 1545: 	noscore = new Array(100);
 1546: 	var ptr = 0;
 1547: 	for (i=1;i<total;i++) {
 1548: 	    var partid = formname["q_"+i].value;
 1549: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1550: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1551: 		var status = formname["solved"+i+"_"+partid].value;
 1552: 		if (points == "" && status != "correct_by_student") {
 1553: 		    noscore[ptr] = i;
 1554: 		    ptr++;
 1555: 		}
 1556: 	    }
 1557: 	}
 1558: 	if (ptr != 0) {
 1559: 	    var sense = ptr == 1 ? ": " : "s: ";
 1560: 	    var prolist = "";
 1561: 	    if (ptr == 1) {
 1562: 		prolist = noscore[0];
 1563: 	    } else {
 1564: 		var i = 0;
 1565: 		while (i < ptr-1) {
 1566: 		    prolist += noscore[i]+", ";
 1567: 		    i++;
 1568: 		}
 1569: 		prolist += "and "+noscore[i];
 1570: 	    }
 1571: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1572: 	    if (resp == false) {
 1573: 		return false;
 1574: 	    }
 1575: 	}
 1576: 
 1577: 	formname.submit();
 1578:     }
 1579: SUBJAVASCRIPT
 1580: }
 1581: 
 1582: #--- javascript for grading message center
 1583: sub sub_grademessage_js {
 1584:     my $request = shift;
 1585:     my $iconpath = $request->dir_config('lonIconsURL');
 1586:     &commonJSfunctions($request);
 1587: 
 1588:     my $inner_js_msg_central= (<<INNERJS);
 1589: <script type="text/javascript">
 1590:     function checkInput() {
 1591:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1592:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1593:       var usrctr = document.msgcenter.usrctr.value;
 1594:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1595:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1596: 
 1597:       var msgchk = "";
 1598:       if (document.msgcenter.subchk.checked) {
 1599:          msgchk = "msgsub,";
 1600:       }
 1601:       var includemsg = 0;
 1602:       for (var i=1; i<=nmsg; i++) {
 1603:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1604:           var frmmsg = document.msgcenter["msg"+i];
 1605:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1606:           var showflg = opener.document.SCORE["shownOnce"+i];
 1607:           showflg.value = "1";
 1608:           var chkbox = document.msgcenter["msgn"+i];
 1609:           if (chkbox.checked) {
 1610:              msgchk += "savemsg"+i+",";
 1611:              includemsg = 1;
 1612:           }
 1613:       }
 1614:       if (document.msgcenter.newmsgchk.checked) {
 1615:          msgchk += "newmsg"+usrctr;
 1616:          includemsg = 1;
 1617:       }
 1618:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1619:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1620:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1621:       includemsg.value = msgchk;
 1622: 
 1623:       self.close()
 1624: 
 1625:     }
 1626: </script>
 1627: INNERJS
 1628: 
 1629:     my $start_page_msg_central =
 1630:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1631: 				       {'js_ready'  => 1,
 1632: 					'only_body' => 1,
 1633: 					'bgcolor'   =>'#FFFFFF',});
 1634:     my $end_page_msg_central =
 1635: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1636: 
 1637:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1638:     $docopen=~s/^document\.//;
 1639: 
 1640:     my %html_js_lt = &Apache::lonlocal::texthash(
 1641:                 comp => 'Compose Message for: ',
 1642:                 incl => 'Include',
 1643:                 type => 'Type',
 1644:                 subj => 'Subject',
 1645:                 mesa => 'Message',
 1646:                 new  => 'New',
 1647:                 save => 'Save',
 1648:                 canc => 'Cancel',
 1649:              );
 1650:     &html_escape(\%html_js_lt);
 1651:     &js_escape(\%html_js_lt);
 1652:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1653: 
 1654: //===================== Script to view submitted by ==================
 1655:   function viewSubmitter(submitter) {
 1656:     document.SCORE.refresh.value = "on";
 1657:     document.SCORE.NCT.value = "1";
 1658:     document.SCORE.unamedom0.value = submitter;
 1659:     document.SCORE.submit();
 1660:     return;
 1661:   }
 1662: 
 1663: //====================== Script for composing message ==============
 1664:    // preload images
 1665:    img1 = new Image();
 1666:    img1.src = "$iconpath/mailbkgrd.gif";
 1667:    img2 = new Image();
 1668:    img2.src = "$iconpath/mailto.gif";
 1669: 
 1670:   function msgCenter(msgform,usrctr,fullname) {
 1671:     var Nmsg  = msgform.savemsgN.value;
 1672:     savedMsgHeader(Nmsg,usrctr,fullname);
 1673:     var subject = msgform.msgsub.value;
 1674:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1675:     re = /msgsub/;
 1676:     var shwsel = "";
 1677:     if (re.test(msgchk)) { shwsel = "checked" }
 1678:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1679:     displaySubject(checkEntities(subject),shwsel);
 1680:     for (var i=1; i<=Nmsg; i++) {
 1681: 	var testmsg = "savemsg"+i+",";
 1682: 	re = new RegExp(testmsg,"g");
 1683: 	shwsel = "";
 1684: 	if (re.test(msgchk)) { shwsel = "checked" }
 1685: 	var message = document.SCORE["savemsg"+i].value;
 1686: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1687: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1688: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1689:     }
 1690:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1691:     shwsel = "";
 1692:     re = /newmsg/;
 1693:     if (re.test(msgchk)) { shwsel = "checked" }
 1694:     newMsg(newmsg,shwsel);
 1695:     msgTail(); 
 1696:     return;
 1697:   }
 1698: 
 1699:   function checkEntities(strx) {
 1700:     if (strx.length == 0) return strx;
 1701:     var orgStr = ["&", "<", ">", '"']; 
 1702:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1703:     var counter = 0;
 1704:     while (counter < 4) {
 1705: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1706: 	counter++;
 1707:     }
 1708:     return strx;
 1709:   }
 1710: 
 1711:   function strReplace(strx, orgStr, newStr) {
 1712:     return strx.split(orgStr).join(newStr);
 1713:   }
 1714: 
 1715:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1716:     var height = 70*Nmsg+250;
 1717:     if (height > 600) {
 1718: 	height = 600;
 1719:     }
 1720:     var xpos = (screen.width-600)/2;
 1721:     xpos = (xpos < 0) ? '0' : xpos;
 1722:     var ypos = (screen.height-height)/2-30;
 1723:     ypos = (ypos < 0) ? '0' : ypos;
 1724: 
 1725:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1726:     pWin.focus();
 1727:     pDoc = pWin.document;
 1728:     pDoc.$docopen;
 1729:     pDoc.write('$start_page_msg_central');
 1730: 
 1731:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1732:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1733:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1734: 
 1735:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1736:     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>");
 1737: }
 1738:     function displaySubject(msg,shwsel) {
 1739:     pDoc = pWin.document;
 1740:     pDoc.write("<tr>");
 1741:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1742:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1743:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1744: }
 1745: 
 1746:   function displaySavedMsg(ctr,msg,shwsel) {
 1747:     pDoc = pWin.document;
 1748:     pDoc.write("<tr>");
 1749:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1750:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1751:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1752: }
 1753: 
 1754:   function newMsg(newmsg,shwsel) {
 1755:     pDoc = pWin.document;
 1756:     pDoc.write("<tr>");
 1757:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1758:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1759:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1760: }
 1761: 
 1762:   function msgTail() {
 1763:     pDoc = pWin.document;
 1764:     //pDoc.write("<\\/table>");
 1765:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1766:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1767:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1768:     pDoc.write("<\\/form>");
 1769:     pDoc.write('$end_page_msg_central');
 1770:     pDoc.close();
 1771: }
 1772: 
 1773: SUBJAVASCRIPT
 1774: }
 1775: 
 1776: #--- javascript for essay type problem --
 1777: sub sub_page_kw_js {
 1778:     my $request = shift;
 1779: 
 1780:     unless ($env{'form.compmsg'}) {
 1781:         &commonJSfunctions($request);
 1782:     }
 1783: 
 1784:     my $inner_js_highlight_central= (<<INNERJS);
 1785: <script type="text/javascript">
 1786:     function updateChoice(flag) {
 1787:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1788:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1789:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1790:       opener.document.SCORE.refresh.value = "on";
 1791:       if (opener.document.SCORE.keywords.value!=""){
 1792:          opener.document.SCORE.submit();
 1793:       }
 1794:       self.close()
 1795:     }
 1796: </script>
 1797: INNERJS
 1798: 
 1799:     my $start_page_highlight_central =
 1800:         &Apache::loncommon::start_page('Highlight Central',
 1801:                                        $inner_js_highlight_central,
 1802:                                        {'js_ready'  => 1,
 1803:                                         'only_body' => 1,
 1804:                                         'bgcolor'   =>'#FFFFFF',});
 1805:     my $end_page_highlight_central =
 1806:         &Apache::loncommon::end_page({'js_ready' => 1});
 1807: 
 1808:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1809:     $docopen=~s/^document\.//;
 1810: 
 1811:     my %js_lt = &Apache::lonlocal::texthash(
 1812:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1813:                 plse => 'Please select a word or group of words from document and then click this link.',
 1814:                 adds => 'Add selection to keyword list? Edit if desired.',
 1815:                 col1 => 'red',
 1816:                 col2 => 'green',
 1817:                 col3 => 'blue',
 1818:                 siz1 => 'normal',
 1819:                 siz2 => '+1',
 1820:                 siz3 => '+2',
 1821:                 sty1 => 'normal',
 1822:                 sty2 => 'italic',
 1823:                 sty3 => 'bold',
 1824:              );
 1825:     my %html_js_lt = &Apache::lonlocal::texthash(
 1826:                 save => 'Save',
 1827:                 canc => 'Cancel',
 1828:                 kehi => 'Keyword Highlight Options',
 1829:                 txtc => 'Text Color',
 1830:                 font => 'Font Size',
 1831:                 fnst => 'Font Style',
 1832:              );
 1833:     &js_escape(\%js_lt);
 1834:     &html_escape(\%html_js_lt);
 1835:     &js_escape(\%html_js_lt);
 1836:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1837: 
 1838: //===================== Show list of keywords ====================
 1839:   function keywords(formname) {
 1840:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1841:     if (nret==null) return;
 1842:     formname.keywords.value = nret;
 1843: 
 1844:     if (formname.keywords.value != "") {
 1845:         formname.refresh.value = "on";
 1846:         formname.submit();
 1847:     }
 1848:     return;
 1849:   }
 1850: 
 1851: //===================== Script to add keyword(s) ==================
 1852:   function getSel() {
 1853:     if (document.getSelection) txt = document.getSelection();
 1854:     else if (document.selection) txt = document.selection.createRange().text;
 1855:     else return;
 1856:     if (typeof(txt) != 'string') {
 1857:         txt = String(txt);
 1858:     }
 1859:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1860:     if (cleantxt=="") {
 1861:         alert("$js_lt{'plse'}");
 1862:         return;
 1863:     }
 1864:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1865:     if (nret==null) return;
 1866:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1867:     if (document.SCORE.keywords.value != "") {
 1868:         document.SCORE.refresh.value = "on";
 1869:         document.SCORE.submit();
 1870:     }
 1871:     return;
 1872:   }
 1873: 
 1874: //====================== Script for keyword highlight options ==============
 1875:   function kwhighlight() {
 1876:     var kwclr    = document.SCORE.kwclr.value;
 1877:     var kwsize   = document.SCORE.kwsize.value;
 1878:     var kwstyle  = document.SCORE.kwstyle.value;
 1879:     var redsel = "";
 1880:     var grnsel = "";
 1881:     var blusel = "";
 1882:     var txtcol1 = "$js_lt{'col1'}";
 1883:     var txtcol2 = "$js_lt{'col2'}";
 1884:     var txtcol3 = "$js_lt{'col3'}";
 1885:     var txtsiz1 = "$js_lt{'siz1'}";
 1886:     var txtsiz2 = "$js_lt{'siz2'}";
 1887:     var txtsiz3 = "$js_lt{'siz3'}";
 1888:     var txtsty1 = "$js_lt{'sty1'}";
 1889:     var txtsty2 = "$js_lt{'sty2'}";
 1890:     var txtsty3 = "$js_lt{'sty3'}";
 1891:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1892:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1893:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1894:     var sznsel = "";
 1895:     var sz1sel = "";
 1896:     var sz2sel = "";
 1897:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1898:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1899:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1900:     var synsel = "";
 1901:     var syisel = "";
 1902:     var sybsel = "";
 1903:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1904:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1905:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1906:     highlightCentral();
 1907:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1908:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1909:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1910:     highlightend();
 1911:     return;
 1912:   }
 1913: 
 1914:   function highlightCentral() {
 1915: //    if (window.hwdWin) window.hwdWin.close();
 1916:     var xpos = (screen.width-400)/2;
 1917:     xpos = (xpos < 0) ? '0' : xpos;
 1918:     var ypos = (screen.height-330)/2-30;
 1919:     ypos = (ypos < 0) ? '0' : ypos;
 1920: 
 1921:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1922:     hwdWin.focus();
 1923:     var hDoc = hwdWin.document;
 1924:     hDoc.$docopen;
 1925:     hDoc.write('$start_page_highlight_central');
 1926:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1927:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1928: 
 1929:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1930:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1931:   }
 1932: 
 1933:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1934:     var hDoc = hwdWin.document;
 1935:     hDoc.write("<tr>");
 1936:     hDoc.write("<td align=\\"left\\">");
 1937:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1938:     hDoc.write("<td align=\\"left\\">");
 1939:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1940:     hDoc.write("<td align=\\"left\\">");
 1941:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1942:     hDoc.write("<\\/tr>");
 1943:   }
 1944: 
 1945:   function highlightend() { 
 1946:     var hDoc = hwdWin.document;
 1947:     hDoc.write("<\\/table><br \\/>");
 1948:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1949:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1950:     hDoc.write("<\\/form>");
 1951:     hDoc.write('$end_page_highlight_central');
 1952:     hDoc.close();
 1953:   }
 1954: 
 1955: SUBJAVASCRIPT
 1956: }
 1957: 
 1958: sub get_increment {
 1959:     my $increment = $env{'form.increment'};
 1960:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1961:         $increment != .1) {
 1962:         $increment = 1;
 1963:     }
 1964:     return $increment;
 1965: }
 1966: 
 1967: sub gradeBox_start {
 1968:     return (
 1969:         &Apache::loncommon::start_data_table()
 1970:        .&Apache::loncommon::start_data_table_header_row()
 1971:        .'<th>'.&mt('Part').'</th>'
 1972:        .'<th>'.&mt('Points').'</th>'
 1973:        .'<th>&nbsp;</th>'
 1974:        .'<th>'.&mt('Assign Grade').'</th>'
 1975:        .'<th>'.&mt('Weight').'</th>'
 1976:        .'<th>'.&mt('Grade Status').'</th>'
 1977:        .&Apache::loncommon::end_data_table_header_row()
 1978:     );
 1979: }
 1980: 
 1981: sub gradeBox_end {
 1982:     return (
 1983:         &Apache::loncommon::end_data_table()
 1984:     );
 1985: }
 1986: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1987: sub gradeBox {
 1988:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1989:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1990: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1991:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1992:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1993:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1994:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1995:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1996: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1997:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1998:     my $display_part= &get_display_part($partid,$symb);
 1999:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2000: 				       [$partid]);
 2001:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2002:     if ($last_resets{$partid}) {
 2003:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2004:     }
 2005:     my $result=&Apache::loncommon::start_data_table_row();
 2006:     my $ctr = 0;
 2007:     my $thisweight = 0;
 2008:     my $increment = &get_increment();
 2009: 
 2010:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2011:     while ($thisweight<=$wgt) {
 2012: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2013:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2014: 	    $thisweight.')" value="'.$thisweight.'" '.
 2015: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2016: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2017:         $thisweight += $increment;
 2018: 	$ctr++;
 2019:     }
 2020:     $radio.='</tr></table>';
 2021: 
 2022:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2023: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2024: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2025: 	$wgt.')" /></td>'."\n";
 2026:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2027: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2028: 	' </td>'."\n";
 2029:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2030: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2031:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2032: 	$line.='<option></option>'.
 2033: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2034:     } else {
 2035: 	$line.='<option selected="selected"></option>'.
 2036: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2037:     }
 2038:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2039: 
 2040: 
 2041:     $result .= 
 2042: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2043:     $result.=&Apache::loncommon::end_data_table_row();
 2044:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2045:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2046: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2047: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2048: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2049:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2050:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2051:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2052:         $aggtries.'" />'."\n";
 2053:     my $res_error;
 2054:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2055:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2056:     if ($res_error) {
 2057:         return &navmap_errormsg();
 2058:     }
 2059:     return $result;
 2060: }
 2061: 
 2062: sub handback_box {
 2063:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2064:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2065:     return unless ($numessay);
 2066:     my (@respids);
 2067:     my @part_response_id = &flatten_responseType($responseType);
 2068:     foreach my $part_response_id (@part_response_id) {
 2069:     	my ($part,$resp) = @{ $part_response_id };
 2070:         if ($part eq $partid) {
 2071:             push(@respids,$resp);
 2072:         }
 2073:     }
 2074:     my $result;
 2075:     foreach my $respid (@respids) {
 2076: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2077: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2078: 	next if (!@$files);
 2079: 	my $file_counter = 0;
 2080: 	foreach my $file (@$files) {
 2081: 	    if ($file =~ /\/portfolio\//) {
 2082:                 $file_counter++;
 2083:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2084:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2085:     	        $file_disp = "$name.$ext";
 2086:     	        $file = $file_path.$file_disp;
 2087:     	        $result.=&mt('Return commented version of [_1] to student.',
 2088:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2089:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2090:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2091: 	    }
 2092: 	}
 2093:         if ($file_counter) {
 2094:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2095:                        '<span class="LC_info">'.
 2096:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2097:         }
 2098:     }
 2099:     return $result;    
 2100: }
 2101: 
 2102: sub show_problem {
 2103:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2104:     my $rendered;
 2105:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2106:     &Apache::lonxml::remember_problem_counter();
 2107:     if ($mode eq 'both' or $mode eq 'text') {
 2108: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2109: 						       $env{'request.course.id'},
 2110: 						       undef,\%form);
 2111:     }
 2112:     if ($removeform) {
 2113: 	$rendered=~s|<form(.*?)>||g;
 2114: 	$rendered=~s|</form>||g;
 2115: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2116:     }
 2117:     my $companswer;
 2118:     if ($mode eq 'both' or $mode eq 'answer') {
 2119: 	&Apache::lonxml::restore_problem_counter();
 2120: 	$companswer=
 2121: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2122: 						    $env{'request.course.id'},
 2123: 						    %form);
 2124:     }
 2125:     if ($removeform) {
 2126: 	$companswer=~s|<form(.*?)>||g;
 2127: 	$companswer=~s|</form>||g;
 2128: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2129:     }
 2130:     my $renderheading = &mt('View of the problem');
 2131:     my $answerheading = &mt('Correct answer');
 2132:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2133:         my $stu_fullname = $env{'form.fullname'};
 2134:         if ($stu_fullname eq '') {
 2135:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2136:         }
 2137:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2138:         if ($forwhom ne '') {
 2139:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2140:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2141:         }
 2142:     }
 2143:     $rendered=
 2144:         '<div class="LC_Box">'
 2145:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2146:        .$rendered
 2147:        .'</div>';
 2148:     $companswer=
 2149:         '<div class="LC_Box">'
 2150:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2151:        .$companswer
 2152:        .'</div>';
 2153:     my $result;
 2154:     if ($mode eq 'both') {
 2155:         $result=$rendered.$companswer;
 2156:     } elsif ($mode eq 'text') {
 2157:         $result=$rendered;
 2158:     } elsif ($mode eq 'answer') {
 2159:         $result=$companswer;
 2160:     }
 2161:     return $result;
 2162: }
 2163: 
 2164: sub files_exist {
 2165:     my ($r, $symb) = @_;
 2166:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2167:     foreach my $student (@students) {
 2168:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2169:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2170: 					      $udom,$uname);
 2171:         my ($string,$timestamp)= &get_last_submission(\%record);
 2172:         foreach my $submission (@$string) {
 2173:             my ($partid,$respid) =
 2174: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2175:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2176: 					   \%record);
 2177:             return 1 if (@$files);
 2178:         }
 2179:     }
 2180:     return 0;
 2181: }
 2182: 
 2183: sub download_all_link {
 2184:     my ($r,$symb) = @_;
 2185:     unless (&files_exist($r, $symb)) {
 2186:         $r->print(&mt('There are currently no submitted documents.'));
 2187:         return;
 2188:     }
 2189:     my $all_students = 
 2190: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2191: 
 2192:     my $parts =
 2193: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2194: 
 2195:     my $identifier = &Apache::loncommon::get_cgi_id();
 2196:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2197:                              'cgi.'.$identifier.'.symb' => $symb,
 2198:                              'cgi.'.$identifier.'.parts' => $parts,});
 2199:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2200: 	      &mt('Download All Submitted Documents').'</a>');
 2201:     return;
 2202: }
 2203: 
 2204: sub submit_download_link {
 2205:     my ($request,$symb) = @_;
 2206:     if (!$symb) { return ''; }
 2207:     my $res_error;
 2208:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2209:         &response_type($symb,\$res_error);
 2210:     if ($res_error) {
 2211:         $request->print(&mt('An error occurred retrieving response types'));
 2212:         return;
 2213:     }
 2214:     unless ($numessay) {
 2215:         $request->print(&mt('No essayresponse items found'));
 2216:         return;
 2217:     }
 2218:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2219:     if (@chosenparts) {
 2220:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2221:                                           undef,undef,1));
 2222:     }
 2223:     if ($numessay) {
 2224:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2225:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2226:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2227:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2228:         if (ref($fullname) eq 'HASH') {
 2229:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2230:             if (@students) {
 2231:                 @{$env{'form.stuinfo'}} = @students;
 2232:                 if ($numdropbox) {
 2233:                     &download_all_link($request,$symb);
 2234:                 } else {
 2235:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2236:                 }
 2237: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2238: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2239:             } else {
 2240:                 $request->print(&mt('No students match the criteria you selected'));
 2241:             }
 2242:         } else {
 2243:             $request->print(&mt('Could not retrieve student information'));
 2244:         }
 2245:     } else {
 2246:         $request->print(&mt('No essayresponse items found'));
 2247:     }
 2248:     return;
 2249: }
 2250: 
 2251: sub build_section_inputs {
 2252:     my $section_inputs;
 2253:     if ($env{'form.section'} eq '') {
 2254:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2255:     } else {
 2256:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2257:         foreach my $section (@sections) {
 2258:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2259:         }
 2260:     }
 2261:     return $section_inputs;
 2262: }
 2263: 
 2264: # --------------------------- show submissions of a student, option to grade 
 2265: sub submission {
 2266:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2267:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2268:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2269:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2270:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2271: 
 2272:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2273:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2274:     my $is_tool = ($symb =~ /ext\.tool$/);
 2275:     my ($essayurl,%coursedesc_by_cid);
 2276: 
 2277:     if (!&canview($usec)) {
 2278:         $request->print(
 2279:             '<span class="LC_warning">'.
 2280:             &mt('Unable to view requested student.').
 2281:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2282:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2283:             '</span>');
 2284: 	return;
 2285:     }
 2286: 
 2287:     my $res_error;
 2288:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2289:         &response_type($symb,\$res_error);
 2290:     if ($res_error) {
 2291:         $request->print(&navmap_errormsg());
 2292:         return;
 2293:     }
 2294: 
 2295:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2296:     unless ($is_tool) { 
 2297:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2298:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2299:     }
 2300:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2301:         $env{'form.compmsg'} = 1;
 2302:     }
 2303:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2304:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2305: 	'" src="'.$request->dir_config('lonIconsURL').
 2306: 	'/check.gif" height="16" border="0" />';
 2307: 
 2308:     # header info
 2309:     if ($counter == 0) {
 2310:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2311:         if (@chosenparts) {
 2312:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2313:         } elsif ($divforres) {
 2314:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2315:         } else {
 2316:             $request->print('<br clear="all" />');
 2317:         }
 2318: 	&sub_page_js($request);
 2319:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2320: 	&sub_page_kw_js($request) if ($numessay);
 2321: 
 2322: 	# option to display problem, only once else it cause problems 
 2323:         # with the form later since the problem has a form.
 2324: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2325: 	    my $mode;
 2326: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2327: 		$mode='both';
 2328: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2329: 		$mode='text';
 2330: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2331: 		$mode='answer';
 2332: 	    }
 2333: 	    &Apache::lonxml::clear_problem_counter();
 2334: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2335: 	}
 2336: 
 2337: 	my %keyhash = ();
 2338: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2339: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2340: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2341: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2342: 	}
 2343: 	# kwclr is the only variable that is guaranteed not to be blank
 2344: 	# if this subroutine has been called once.
 2345: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2346: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2347: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2348: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2349: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2350: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2351: 	}
 2352: 	if ($env{'form.compmsg'}) {
 2353: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2354: 		$keyhash{$symb.'_subject'} : $probtitle;
 2355: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2356: 	}
 2357: 
 2358: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2359: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2360: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2361: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2362: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2363: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2364: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2365: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2366: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2367: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2368: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2369: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2370: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2371: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2372: 			&build_section_inputs().
 2373: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2374: 			'<input type="hidden" name="NCT"'.
 2375: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2376: 	if ($env{'form.compmsg'}) {
 2377: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2378: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2379: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2380: 	}
 2381: 	if ($numessay) {
 2382: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2383: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2384: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2385: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2386: 	}
 2387: 
 2388: 	my ($cts,$prnmsg) = (1,'');
 2389: 	while ($cts <= $env{'form.savemsgN'}) {
 2390: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2391: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2392: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2393: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2394: 		'" />'."\n".
 2395: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2396: 	    $cts++;
 2397: 	}
 2398: 	$request->print($prnmsg);
 2399: 
 2400: 	if ($numessay) {
 2401: 
 2402:             my %lt = &Apache::lonlocal::texthash(
 2403:                           keyh => 'Keyword Highlighting for Essays',
 2404:                           keyw => 'Keyword Options',
 2405:                           list => 'List',
 2406:                           past => 'Paste Selection to List',
 2407:                           high => 'Highlight Attribute',
 2408:                      );
 2409: #
 2410: # Print out the keyword options line
 2411: #
 2412: 	    $request->print(
 2413:                 '<div class="LC_columnSection">'
 2414:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2415:                .&Apache::lonhtmlcommon::funclist_from_array(
 2416:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2417:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2418:  class="page">'.$lt{'past'}.'</a>',
 2419:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2420:                     {legend => $lt{'keyw'}})
 2421:                .'</fieldset></div>'
 2422:             );
 2423: 
 2424: #
 2425: # Load the other essays for similarity check
 2426: #
 2427:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2428:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2429:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2430:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2431:                 if ($cdom ne '' && $cnum ne '') {
 2432:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2433:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2434:                         my $apath = $1.'_'.$id;
 2435:                         $apath=~s/\W/\_/gs;
 2436:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2437:                     }
 2438:                 }
 2439:             } else {
 2440: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2441: 	        $apath=&escape($apath);
 2442: 	        $apath=~s/\W/\_/gs;
 2443:                 &init_old_essays($symb,$apath,$adom,$aname);
 2444:             }
 2445:         }
 2446:     }
 2447: 
 2448: # This is where output for one specific student would start
 2449:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2450:     $request->print(
 2451:         "\n\n"
 2452:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2453:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2454:        ."\n"
 2455:     );
 2456: 
 2457:     # Show additional functions if allowed
 2458:     if ($perm{'vgr'}) {
 2459:         $request->print(
 2460:             &Apache::loncommon::track_student_link(
 2461:                 'View recent activity',
 2462:                 $uname,$udom,'check')
 2463:            .' '
 2464:         );
 2465:     }
 2466:     if ($perm{'opa'}) {
 2467:         $request->print(
 2468:             &Apache::loncommon::pprmlink(
 2469:                 &mt('Set/Change parameters'),
 2470:                 $uname,$udom,$symb,'check'));
 2471:     }
 2472: 
 2473:     # Show Problem
 2474:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2475: 	my $mode;
 2476: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2477: 	    $mode='both';
 2478: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2479: 	    $mode='text';
 2480: 	} elsif ($env{'form.vAns'} eq 'all') {
 2481: 	    $mode='answer';
 2482: 	}
 2483: 	&Apache::lonxml::clear_problem_counter();
 2484: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2485:     }
 2486: 
 2487:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2488: 
 2489:     # Display student info
 2490:     $request->print(($counter == 0 ? '' : '<br />'));
 2491: 
 2492:     my $boxtitle = &mt('Submissions');
 2493:     if ($is_tool) {
 2494:         $boxtitle = &mt('Transactions')
 2495:     }
 2496:     my $result='<div class="LC_Box">'
 2497:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2498:     $result.='<input type="hidden" name="name'.$counter.
 2499:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2500:     if (($numresp > $numessay) && !$is_tool) {
 2501:         $result.='<p class="LC_info">'
 2502:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2503:                 ."</p>\n";
 2504:     }
 2505: 
 2506:     # If any part of the problem is an essayresponse, then check for collaborators
 2507:     my $fullname;
 2508:     my $col_fullnames = [];
 2509:     if ($numessay) {
 2510: 	(my $sub_result,$fullname,$col_fullnames)=
 2511: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2512: 				 $counter);
 2513: 	$result.=$sub_result;
 2514:     }
 2515:     $request->print($result."\n");
 2516: 
 2517:     # print student answer/submission
 2518:     # Options are (1) Last submission only
 2519:     #             (2) Last submission (with detailed information for that submission)
 2520:     #             (3) All transactions (by date)
 2521:     #             (4) The whole record (with detailed information for all transactions)
 2522: 
 2523:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2524: 
 2525:     my $lastsubonly;
 2526: 
 2527:     if ($$timestamp eq '') {
 2528:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2529:     } elsif ($is_tool) {
 2530:         $lastsubonly =
 2531:             '<div class="LC_grade_submissions_body">'
 2532:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2533:     } else {
 2534:         $lastsubonly =
 2535:             '<div class="LC_grade_submissions_body">'
 2536:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2537: 
 2538: 	my %seenparts;
 2539: 	my @part_response_id = &flatten_responseType($responseType);
 2540: 	foreach my $part (@part_response_id) {
 2541: 	    my ($partid,$respid) = @{ $part };
 2542: 	    my $display_part=&get_display_part($partid,$symb);
 2543: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2544: 		if (exists($seenparts{$partid})) { next; }
 2545: 		$seenparts{$partid}=1;
 2546:                 $request->print(
 2547:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2548:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2549:                                '<a href="javascript:viewSubmitter(\''.
 2550:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2551:                                '\');" target="_self">'.
 2552:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2553:                     '<br />');
 2554: 		next;
 2555: 	    }
 2556: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2557: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2558:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2559:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2560:                     ' <span class="LC_internal_info">'.
 2561:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2562:                     '</span>&nbsp; &nbsp;'.
 2563: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2564: 		next;
 2565: 	    }
 2566: 	    foreach my $submission (@$string) {
 2567: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2568: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2569: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2570: 		# Similarity check
 2571:                 my $similar='';
 2572:                 my ($type,$trial,$rndseed);
 2573:                 if ($hide eq 'rand') {
 2574:                     $type = 'randomizetry';
 2575:                     $trial = $record{"resource.$partid.tries"};
 2576:                     $rndseed = $record{"resource.$partid.rndseed"};
 2577:                 }
 2578: 	        if ($env{'form.checkPlag'}) {
 2579: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2580: 		    &most_similar($uname,$udom,$symb,$subval);
 2581: 		    if ($osim) {
 2582: 			$osim=int($osim*100.0);
 2583:                         if ($hide eq 'anon') {
 2584:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2585:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2586:                         } else {
 2587: 			    $similar='<hr />';
 2588:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2589:                                 $similar .= '<h3><span class="LC_warning">'.
 2590:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2591:                                                 $osim,
 2592:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2593:                                             '</span></h3>';
 2594:                             } else {
 2595:                                 my %old_course_desc;
 2596:                                 if ($ocrsid ne '') {
 2597:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2598:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2599:                                     } else {
 2600:                                         my $args;
 2601:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2602:                                             $args = {'one_time' => 1};
 2603:                                         }
 2604:                                         %old_course_desc =
 2605:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2606:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2607:                                     }
 2608:                                     $similar .=
 2609:                                         '<h3><span class="LC_warning">'.
 2610:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2611:                                             $osim,
 2612:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2613:                                             $old_course_desc{'description'},
 2614:                                             $old_course_desc{'num'},
 2615:                                             $old_course_desc{'domain'}).
 2616:                                         '</span></h3>';
 2617:                                 } else {
 2618:                                     $similar .=
 2619:                                         '<h3><span class="LC_warning">'.
 2620:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2621:                                             $osim,
 2622:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2623:                                         '</span></h3>';
 2624:                                 }
 2625:                             }
 2626:                             $similar .= '<blockquote><i>'.
 2627:                                         &keywords_highlight($oessay).
 2628:                                         '</i></blockquote><hr />';
 2629:                         }
 2630: 	            }
 2631: 		}
 2632: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2633:                                      undef,$type,$trial,$rndseed);
 2634:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2635:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2636:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2637: 		    my $display_part=&get_display_part($partid,$symb);
 2638:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2639:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2640:                         ' <span class="LC_internal_info">'.
 2641:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2642:                         '</span>&nbsp; &nbsp;';
 2643: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2644: 		    if (@$files) {
 2645:                         if ($hide eq 'anon') {
 2646:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2647:                         } else {
 2648:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2649:                                         .'<br /><span class="LC_warning">';
 2650:                             if(@$files == 1) {
 2651:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2652:                             } else {
 2653:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2654:                             }
 2655:                             $lastsubonly .= '</span>';
 2656:                             foreach my $file (@$files) {
 2657:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2658:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2659:                             }
 2660:                         }
 2661: 			$lastsubonly.='<br />';
 2662:                     }
 2663:                     if ($hide eq 'anon') {
 2664:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2665:                     } else {
 2666:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2667:                         if ($draft) {
 2668:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2669:                         }
 2670:                         $subval =
 2671: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2672: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2673:                         if ($responsetype eq 'essay') {
 2674:                             $subval =~ s{\n}{<br />}g;
 2675:                         }
 2676:                         $lastsubonly.=$subval."\n";
 2677:                     }
 2678:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2679: 		    $lastsubonly.='</div>';
 2680: 		}
 2681:             }
 2682: 	}
 2683: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2684:     }
 2685:     $request->print($lastsubonly);
 2686:     if ($env{'form.lastSub'} eq 'datesub') {
 2687:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2688: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2689:     }
 2690:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2691:         my $identifier = (&canmodify($usec)? $counter : '');
 2692:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2693: 								 $env{'request.course.id'},
 2694: 								 $last,'.submission',
 2695: 								 'Apache::grades::keywords_highlight',
 2696:                                                                  $usec,$identifier));
 2697:     }
 2698:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2699: 	.$udom.'" />'."\n");
 2700:     # return if view submission with no grading option
 2701:     if (!&canmodify($usec)) {
 2702: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2703: 	return;
 2704:     } else {
 2705: 	$request->print('</div>'."\n");
 2706:     }
 2707: 
 2708:     # grading message center
 2709: 
 2710:     if ($env{'form.compmsg'}) {
 2711:         my $result='<div class="LC_Box">'.
 2712:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2713:                    '<div class="LC_grade_message_center_body">';
 2714:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2715:         my $msgfor = $givenn.' '.$lastname;
 2716:         if (scalar(@$col_fullnames) > 0) {
 2717:             my $lastone = pop(@$col_fullnames);
 2718:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2719:         }
 2720:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2721:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2722:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2723:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2724:                  ',\''.$msgfor.'\');" target="_self">'.
 2725:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2726:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2727:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2728:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2729:                  '<br />&nbsp;('.
 2730:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2731:                  '</div></div>';
 2732:         $request->print($result);
 2733:     }
 2734: 
 2735:     my %seen = ();
 2736:     my @partlist;
 2737:     my @gradePartRespid;
 2738:     my @part_response_id;
 2739:     if ($is_tool) {
 2740:         @part_response_id = ([0,'']);
 2741:     } else {
 2742:         @part_response_id = &flatten_responseType($responseType);
 2743:     }
 2744:     $request->print(
 2745:         '<div class="LC_Box">'
 2746:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2747:     );
 2748:     $request->print(&gradeBox_start());
 2749:     foreach my $part_response_id (@part_response_id) {
 2750:     	my ($partid,$respid) = @{ $part_response_id };
 2751: 	my $part_resp = join('_',@{ $part_response_id });
 2752: 	next if ($seen{$partid} > 0);
 2753: 	$seen{$partid}++;
 2754: 	push(@partlist,$partid);
 2755: 	push(@gradePartRespid,$partid.'.'.$respid);
 2756: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2757:     }
 2758:     $request->print(&gradeBox_end()); # </div>
 2759:     $request->print('</div>');
 2760: 
 2761:     $request->print('<div class="LC_grade_info_links">');
 2762:     $request->print('</div>');
 2763: 
 2764:     $result='<input type="hidden" name="partlist'.$counter.
 2765: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2766:     $result.='<input type="hidden" name="gradePartRespid'.
 2767: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2768:     my $ctr = 0;
 2769:     while ($ctr < scalar(@partlist)) {
 2770: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2771: 	    $partlist[$ctr].'" />'."\n";
 2772: 	$ctr++;
 2773:     }
 2774:     $request->print($result.''."\n");
 2775: 
 2776: # Done with printing info for one student
 2777: 
 2778:     $request->print('</div>');#LC_grade_show_user
 2779: 
 2780: 
 2781:     # print end of form
 2782:     if ($counter == $total) {
 2783:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2784: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2785: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2786: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2787: 	my $ntstu ='<select name="NTSTU">'.
 2788: 	    '<option>1</option><option>2</option>'.
 2789: 	    '<option>3</option><option>5</option>'.
 2790: 	    '<option>7</option><option>10</option></select>'."\n";
 2791: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2792: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2793:         $endform.=&mt('[_1]student(s)',$ntstu);
 2794: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2795: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2796: 	    '<input type="button" value="'.&mt('Next').'" '.
 2797: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2798:         $endform.='<span class="LC_warning">'.
 2799:                   &mt('(Next and Previous (student) do not save the scores.)').
 2800:                   '</span>'."\n" ;
 2801:         $endform.="<input type='hidden' value='".&get_increment().
 2802:             "' name='increment' />";
 2803: 	$endform.='</td></tr></table></form>';
 2804: 	$request->print($endform);
 2805:     }
 2806:     return '';
 2807: }
 2808: 
 2809: sub check_collaborators {
 2810:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2811:     my ($result,@col_fullnames);
 2812:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2813:     foreach my $part (keys(%$handgrade)) {
 2814: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2815: 					'.maxcollaborators',
 2816: 					$symb,$udom,$uname);
 2817: 	next if ($ncol <= 0);
 2818: 	$part =~ s/\_/\./g;
 2819: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2820: 	my (@good_collaborators, @bad_collaborators);
 2821: 	foreach my $possible_collaborator
 2822: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2823: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2824: 	    next if ($possible_collaborator eq '');
 2825: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2826: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2827: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2828: 	    # Doing this grep allows 'fuzzy' specification
 2829: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2830: 			       keys(%$classlist));
 2831: 	    if (! scalar(@matches)) {
 2832: 		push(@bad_collaborators, $possible_collaborator);
 2833: 	    } else {
 2834: 		push(@good_collaborators, @matches);
 2835: 	    }
 2836: 	}
 2837: 	if (scalar(@good_collaborators) != 0) {
 2838: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2839: 	    foreach my $name (@good_collaborators) {
 2840: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2841: 		push(@col_fullnames, $givenn.' '.$lastname);
 2842: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2843: 	    }
 2844: 	    $result.='</ol><br />'."\n";
 2845: 	    my ($part)=split(/\./,$part);
 2846: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2847: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2848: 		"\n";
 2849: 	}
 2850: 	if (scalar(@bad_collaborators) > 0) {
 2851: 	    $result.='<div class="LC_warning">';
 2852: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2853: 	    $result .= '</div>';
 2854: 	}         
 2855: 	if (scalar(@bad_collaborators > $ncol)) {
 2856: 	    $result .= '<div class="LC_warning">';
 2857: 	    $result .= &mt('This student has submitted too many '.
 2858: 		'collaborators.  Maximum is [_1].',$ncol);
 2859: 	    $result .= '</div>';
 2860: 	}
 2861:     }
 2862:     return ($result,$fullname,\@col_fullnames);
 2863: }
 2864: 
 2865: #--- Retrieve the last submission for all the parts
 2866: sub get_last_submission {
 2867:     my ($returnhash,$is_tool)=@_;
 2868:     my (@string,$timestamp,%lasthidden);
 2869:     if ($$returnhash{'version'}) {
 2870: 	my %lasthash=();
 2871: 	my ($version);
 2872: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2873: 	    foreach my $key (sort(split(/\:/,
 2874: 					$$returnhash{$version.':keys'}))) {
 2875: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2876: 		$timestamp = 
 2877: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2878: 	    }
 2879: 	}
 2880:         my (%typeparts,%randombytry);
 2881:         my $showsurv = 
 2882:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2883:         foreach my $key (sort(keys(%lasthash))) {
 2884:             if ($key =~ /\.type$/) {
 2885:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2886:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2887:                     ($lasthash{$key} eq 'randomizetry')) {
 2888:                     my ($ign,@parts) = split(/\./,$key);
 2889:                     pop(@parts);
 2890:                     my $id = join('.',@parts);
 2891:                     if ($lasthash{$key} eq 'randomizetry') {
 2892:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2893:                     } else {
 2894:                         unless ($showsurv) {
 2895:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2896:                         }
 2897:                     }
 2898:                     delete($lasthash{$key});
 2899:                 }
 2900:             }
 2901:         }
 2902:         my @hidden = keys(%typeparts);
 2903:         my @randomize = keys(%randombytry);
 2904: 	foreach my $key (keys(%lasthash)) {
 2905: 	    next if ($key !~ /\.submission$/);
 2906:             my $hide;
 2907:             if (@hidden) {
 2908:                 foreach my $id (@hidden) {
 2909:                     if ($key =~ /^\Q$id\E/) {
 2910:                         $hide = 'anon';
 2911:                         last;
 2912:                     }
 2913:                 }
 2914:             }
 2915:             unless ($hide) {
 2916:                 if (@randomize) {
 2917:                     foreach my $id (@randomize) {
 2918:                         if ($key =~ /^\Q$id\E/) {
 2919:                             $hide = 'rand';
 2920:                             last;
 2921:                         }
 2922:                     }
 2923:                 }
 2924:             }
 2925: 	    my ($partid,$foo) = split(/submission$/,$key);
 2926: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2927:             push(@string, join(':', $key, $hide, $draft, (
 2928:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2929:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2930: 	}
 2931:     }
 2932:     if (!@string) {
 2933:         my $msg;
 2934:         if ($is_tool) {
 2935:             $msg = &mt('No grade passed back.');
 2936:         } else {
 2937:             $msg = &mt('Nothing submitted - no attempts.');
 2938:         }
 2939: 	$string[0] =
 2940: 	    '<span class="LC_warning">'.$msg.'</span>';
 2941:     }
 2942:     return (\@string,\$timestamp);
 2943: }
 2944: 
 2945: #--- High light keywords, with style choosen by user.
 2946: sub keywords_highlight {
 2947:     my $string    = shift;
 2948:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2949:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2950:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2951:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2952:     foreach my $keyword (@keylist) {
 2953: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2954:     }
 2955:     return $string;
 2956: }
 2957: 
 2958: # For Tasks provide a mechanism to display previous version for one specific student
 2959: 
 2960: sub show_previous_task_version {
 2961:     my ($request,$symb) = @_;
 2962:     if ($symb eq '') {
 2963:         $request->print(
 2964:             '<span class="LC_error">'.
 2965:             &mt('Unable to handle ambiguous references.').
 2966:             '</span>');
 2967:         return '';
 2968:     }
 2969:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2970:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2971:     if (!&canview($usec)) {
 2972:         $request->print(
 2973:             '<span class="LC_warning">'.
 2974:             &mt('Unable to view previous version for requested student.').
 2975:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2976:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2977:             '</span>');
 2978:         return;
 2979:     }
 2980:     my $mode = 'both';
 2981:     my $isTask = ($symb =~/\.task$/);
 2982:     if ($isTask) {
 2983:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2984:             if ($env{'form.fullname'} eq '') {
 2985:                 $env{'form.fullname'} =
 2986:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2987:             }
 2988:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2989:             $request->print("\n\n".
 2990:                             '<div class="LC_grade_show_user">'.
 2991:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2992:                             '</h2>'."\n");
 2993:             &Apache::lonxml::clear_problem_counter();
 2994:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2995:                             {'previousversion' => $env{'form.previousversion'} }));
 2996:             $request->print("\n</div>");
 2997:         }
 2998:     }
 2999:     return;
 3000: }
 3001: 
 3002: sub choose_task_version_form {
 3003:     my ($symb,$uname,$udom,$nomenu) = @_;
 3004:     my $isTask = ($symb =~/\.task$/);
 3005:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3006:     if ($isTask) {
 3007:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3008:                                               $udom,$uname);
 3009:         if (($record{'resource.0.version'} eq '') ||
 3010:             ($record{'resource.0.version'} < 2)) {
 3011:             return ($record{'resource.0.version'},
 3012:                     $record{'resource.0.version'},$result,$js);
 3013:         } else {
 3014:             $current = $record{'resource.0.version'};
 3015:         }
 3016:         if ($env{'form.previousversion'}) {
 3017:             $displayed = $env{'form.previousversion'};
 3018:             $rowtitle = &mt('Choose another version:')
 3019:         } else {
 3020:             $displayed = $current;
 3021:             $rowtitle = &mt('Show earlier version:');
 3022:         }
 3023:         $result = '<div class="LC_left_float">';
 3024:         my $list;
 3025:         my $numversions = 0;
 3026:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3027:             if ($i == $current) {
 3028:                 if (!$env{'form.previousversion'} || $nomenu) {
 3029:                     next;
 3030:                 } else {
 3031:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3032:                     $numversions ++;
 3033:                 }
 3034:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3035:                 unless ($i == $env{'form.previousversion'}) {
 3036:                     $numversions ++;
 3037:                 }
 3038:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3039:             }
 3040:         }
 3041:         if ($numversions) {
 3042:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3043:             $result .=
 3044:                 '<form name="getprev" method="post" action=""'.
 3045:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3046:                 &Apache::loncommon::start_data_table().
 3047:                 &Apache::loncommon::start_data_table_row().
 3048:                 '<th align="left">'.$rowtitle.'</th>'.
 3049:                 '<td><select name="version">'.
 3050:                 '<option>'.&mt('Select').'</option>'.
 3051:                 $list.
 3052:                 '</select></td>'.
 3053:                 &Apache::loncommon::end_data_table_row();
 3054:             unless ($nomenu) {
 3055:                 $result .= &Apache::loncommon::start_data_table_row().
 3056:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3057:                 '<td><span class="LC_nobreak">'.
 3058:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3059:                 &mt('Yes').'</label>'.
 3060:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3061:                 '</span></td>'.
 3062:                 &Apache::loncommon::end_data_table_row();
 3063:             }
 3064:             $result .=
 3065:                 &Apache::loncommon::start_data_table_row().
 3066:                 '<th align="left">&nbsp;</th>'.
 3067:                 '<td>'.
 3068:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3069:                 '</td>'.
 3070:                 &Apache::loncommon::end_data_table_row().
 3071:                 &Apache::loncommon::end_data_table().
 3072:                 '</form>';
 3073:             $js = &previous_display_javascript($nomenu,$current);
 3074:         } elsif ($displayed && $nomenu) {
 3075:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3076:         } else {
 3077:             $result .= &mt('No previous versions to show for this student');
 3078:         }
 3079:         $result .= '</div>';
 3080:     }
 3081:     return ($current,$displayed,$result,$js);
 3082: }
 3083: 
 3084: sub previous_display_javascript {
 3085:     my ($nomenu,$current) = @_;
 3086:     my $js = <<"JSONE";
 3087: <script type="text/javascript">
 3088: // <![CDATA[
 3089: function previousVersion(uname,udom,symb) {
 3090:     var current = '$current';
 3091:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3092:     var prevstr = new RegExp("^\\\\d+\$");
 3093:     if (!prevstr.test(version)) {
 3094:         return false;
 3095:     }
 3096:     var url = '';
 3097:     if (version == current) {
 3098:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3099:     } else {
 3100:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3101:     }
 3102: JSONE
 3103:     if ($nomenu) {
 3104:         $js .= <<"JSTWO";
 3105:     document.location.href = url;
 3106: JSTWO
 3107:     } else {
 3108:         $js .= <<"JSTHREE";
 3109:     var newwin = 0;
 3110:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3111:         if (document.getprev.prevwin[i].checked == true) {
 3112:             newwin = document.getprev.prevwin[i].value;
 3113:         }
 3114:     }
 3115:     if (newwin == 1) {
 3116:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3117:         url = url+'&inhibitmenu=yes';
 3118:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3119:             previousWin = window.open(url,'',options,1);
 3120:         } else {
 3121:             previousWin.location.href = url;
 3122:         }
 3123:         previousWin.focus();
 3124:         return false;
 3125:     } else {
 3126:         document.location.href = url;
 3127:         return false;
 3128:     }
 3129: JSTHREE
 3130:     }
 3131:     $js .= <<"ENDJS";
 3132:     return false;
 3133: }
 3134: // ]]>
 3135: </script>
 3136: ENDJS
 3137: 
 3138: }
 3139: 
 3140: #--- Called from submission routine
 3141: sub processHandGrade {
 3142:     my ($request,$symb) = @_;
 3143:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3144:     my $button = $env{'form.gradeOpt'};
 3145:     my $ngrade = $env{'form.NCT'};
 3146:     my $ntstu  = $env{'form.NTSTU'};
 3147:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3148:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3149: 
 3150:     if ($button eq 'Save & Next') {
 3151: 	my $ctr = 0;
 3152: 	while ($ctr < $ngrade) {
 3153: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3154: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3155:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3156: 	    if ($errorflag eq 'no_score') {
 3157: 		$ctr++;
 3158: 		next;
 3159: 	    }
 3160: 	    if ($errorflag eq 'not_allowed') {
 3161: 		$request->print(
 3162:                     '<span class="LC_error">'
 3163:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3164:                    .'</span>');
 3165: 		$ctr++;
 3166: 		next;
 3167: 	    }
 3168:             if ($numhidden) {
 3169:                 $request->print(
 3170:                     '<span class="LC_info">'
 3171:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3172:                    .'</span><br />');
 3173:             }
 3174: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3175: 	    my ($subject,$message,$msgstatus) = ('','','');
 3176: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3177:             my ($feedurl,$showsymb) =
 3178: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3179: 	    my $messagetail;
 3180: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3181: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3182: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3183: 		$subject.=' ['.$restitle.']';
 3184: 		my (@msgnum) = split(/,/,$includemsg);
 3185: 		foreach (@msgnum) {
 3186: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3187: 		}
 3188: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3189: 		if ($env{'form.withgrades'.$ctr}) {
 3190: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3191: 		    $messagetail = " for <a href=\"".
 3192: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3193: 		}
 3194: 		$msgstatus = 
 3195:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3196: 						     $message.$messagetail,
 3197:                                                      undef,$feedurl,undef,
 3198:                                                      undef,undef,$showsymb,
 3199:                                                      $restitle);
 3200: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3201: 				$msgstatus.'<br />');
 3202: 	    }
 3203: 	    if ($env{'form.collaborator'.$ctr}) {
 3204: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3205: 		foreach my $collabstr (@collabstrs) {
 3206: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3207: 		    foreach my $collaborator (@collaborators) {
 3208: 			my ($errorflag,$pts,$wgt) = 
 3209: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3210: 					   $env{'form.unamedom'.$ctr},$part);
 3211: 			if ($errorflag eq 'not_allowed') {
 3212: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3213: 			    next;
 3214: 			} elsif ($message ne '') {
 3215: 			    my ($baseurl,$showsymb) = 
 3216: 				&get_feedurl_and_symb($symb,$collaborator,
 3217: 						      $udom);
 3218: 			    if ($env{'form.withgrades'.$ctr}) {
 3219: 				$messagetail = " for <a href=\"".
 3220:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3221: 			    }
 3222: 			    $msgstatus = 
 3223: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3224: 			}
 3225: 		    }
 3226: 		}
 3227: 	    }
 3228: 	    $ctr++;
 3229: 	}
 3230:     }
 3231: 
 3232:     my $res_error;
 3233:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3234:     if ($res_error) {
 3235:         $request->print(&navmap_errormsg());
 3236:         return;
 3237:     }
 3238: 
 3239:     my %keyhash = ();
 3240:     if ($numessay) {
 3241: 	# Keywords sorted in alphabatical order
 3242: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3243: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3244: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3245: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3246: 	$env{'form.keywords'} = join(' ',@keywords);
 3247: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3248: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3249: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3250: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3251: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3252:     }
 3253: 
 3254:     if ($env{'form.compmsg'}) {
 3255: 	# message center - Order of message gets changed. Blank line is eliminated.
 3256: 	# New messages are saved in env for the next student.
 3257: 	# All messages are saved in nohist_handgrade.db
 3258: 	my ($ctr,$idx) = (1,1);
 3259: 	while ($ctr <= $env{'form.savemsgN'}) {
 3260: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3261: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3262: 		$idx++;
 3263: 	    }
 3264: 	    $ctr++;
 3265: 	}
 3266: 	$ctr = 0;
 3267: 	while ($ctr < $ngrade) {
 3268: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3269: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3270: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3271: 	        $idx++;
 3272: 	    }
 3273: 	    $ctr++;
 3274: 	}
 3275: 	$env{'form.savemsgN'} = --$idx;
 3276: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3277:     }
 3278:     if (($numessay) || ($env{'form.compmsg'})) {
 3279:         my $putresult = &Apache::lonnet::put
 3280:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3281:     }
 3282: 
 3283:     # Called by Save & Refresh from Highlight Attribute Window
 3284:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3285:     if ($env{'form.refresh'} eq 'on') {
 3286: 	my ($ctr,$total) = (0,0);
 3287: 	while ($ctr < $ngrade) {
 3288: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3289: 	    $ctr++;
 3290: 	}
 3291: 	$env{'form.NTSTU'}=$ngrade;
 3292: 	$ctr = 0;
 3293: 	while ($ctr < $total) {
 3294: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3295: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3296: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3297: 	    &submission($request,$ctr,$total-1,$symb);
 3298: 	    $ctr++;
 3299: 	}
 3300: 	return '';
 3301:     }
 3302: 
 3303:     # Get the next/previous one or group of students
 3304:     my $firststu = $env{'form.unamedom0'};
 3305:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3306:     my $ctr = 2;
 3307:     while ($laststu eq '') {
 3308: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3309: 	$ctr++;
 3310: 	$laststu = $firststu if ($ctr > $ngrade);
 3311:     }
 3312: 
 3313:     my (@parsedlist,@nextlist);
 3314:     my ($nextflg) = 0;
 3315:     foreach my $item (sort 
 3316: 	     {
 3317: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3318: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3319: 		 }
 3320: 		 return $a cmp $b;
 3321: 	     } (keys(%$fullname))) {
 3322: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3323: 	    push(@parsedlist,$item);
 3324: 	}
 3325: 	$nextflg = 1 if ($item eq $laststu);
 3326: 	if ($button eq 'Previous') {
 3327: 	    last if ($item eq $firststu);
 3328: 	    push(@parsedlist,$item);
 3329: 	}
 3330:     }
 3331:     $ctr = 0;
 3332:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3333:     foreach my $student (@parsedlist) {
 3334: 	my $submitonly=$env{'form.submitonly'};
 3335: 	my ($uname,$udom) = split(/:/,$student);
 3336: 	
 3337: 	if ($submitonly eq 'queued') {
 3338: 	    my %queue_status = 
 3339: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3340: 							$udom,$uname);
 3341: 	    next if (!defined($queue_status{'gradingqueue'}));
 3342: 	}
 3343: 
 3344: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3345: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3346: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3347: 	    my $submitted = 0;
 3348: 	    my $ungraded = 0;
 3349: 	    my $incorrect = 0;
 3350: 	    foreach my $item (keys(%status)) {
 3351: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3352: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3353: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3354: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3355: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3356: 		    $submitted = 0;
 3357: 		}
 3358: 	    }
 3359: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3360: 				     $submitonly eq 'incorrect' ||
 3361: 				     $submitonly eq 'graded'));
 3362: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3363: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3364: 	}
 3365: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3366: 	last if ($ctr == $ntstu);
 3367: 	$ctr++;
 3368:     }
 3369: 
 3370:     $ctr = 0;
 3371:     my $total = scalar(@nextlist)-1;
 3372: 
 3373:     foreach (sort(@nextlist)) {
 3374: 	my ($uname,$udom,$submitter) = split(/:/);
 3375: 	$env{'form.student'}  = $uname;
 3376: 	$env{'form.userdom'}  = $udom;
 3377: 	$env{'form.fullname'} = $$fullname{$_};
 3378: 	&submission($request,$ctr,$total,$symb);
 3379: 	$ctr++;
 3380:     }
 3381:     if ($total < 0) {
 3382: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3383: 	$request->print($the_end);
 3384:     }
 3385:     return '';
 3386: }
 3387: 
 3388: #---- Save the score and award for each student, if changed
 3389: sub saveHandGrade {
 3390:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3391:     my @version_parts;
 3392:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3393: 					   $env{'request.course.id'});
 3394:     if (!&canmodify($usec)) { return('not_allowed'); }
 3395:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3396:     my @parts_graded;
 3397:     my %newrecord  = ();
 3398:     my ($pts,$wgt,$totchg) = ('','',0);
 3399:     my %aggregate = ();
 3400:     my $aggregateflag = 0;
 3401:     if ($env{'form.HIDE'.$newflg}) {
 3402:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3403:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3404:         $totchg += $numchgs;
 3405:     }
 3406:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3407:     foreach my $new_part (@parts) {
 3408: 	#collaborator ($submi may vary for different parts
 3409: 	if ($submitter && $new_part ne $part) { next; }
 3410: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3411: 	if ($dropMenu eq 'excused') {
 3412: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3413: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3414: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3415: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3416: 		}
 3417: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3418: 	    }
 3419: 	} elsif ($dropMenu eq 'reset status'
 3420: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3421: 	    foreach my $key (keys(%record)) {
 3422: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3423: 	    }
 3424: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3425: 		"$env{'user.name'}:$env{'user.domain'}";
 3426:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3427: 
 3428:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3429: 					       [$new_part]);
 3430:             my $aggtries =$totaltries;
 3431:             if ($last_resets{$new_part}) {
 3432:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3433: 					   $new_part);
 3434:             }
 3435: 
 3436:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3437:             if ($aggtries > 0) {
 3438:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3439:                 $aggregateflag = 1;
 3440:             }
 3441: 	} elsif ($dropMenu eq '') {
 3442: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3443: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3444: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3445: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3446: 		next;
 3447: 	    }
 3448: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3449: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3450: 	    my $partial= $pts/$wgt;
 3451: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3452: 		#do not update score for part if not changed.
 3453:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3454: 		next;
 3455: 	    } else {
 3456: 	        push(@parts_graded,$new_part);
 3457: 	    }
 3458: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3459: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3460: 	    }
 3461: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3462: 	    if ($partial == 0) {
 3463: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3464: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3465: 		}
 3466: 	    } else {
 3467: 		if ($record{$reckey} ne 'correct_by_override') {
 3468: 		    $newrecord{$reckey} = 'correct_by_override';
 3469: 		}
 3470: 	    }	    
 3471: 	    if ($submitter && 
 3472: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3473: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3474: 	    }
 3475: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3476: 		"$env{'user.name'}:$env{'user.domain'}";
 3477: 	}
 3478: 	# unless problem has been graded, set flag to version the submitted files
 3479: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3480: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3481: 	        $dropMenu eq 'reset status')
 3482: 	   {
 3483: 	    push(@version_parts,$new_part);
 3484: 	}
 3485:     }
 3486:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3487:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3488: 
 3489:     if (%newrecord) {
 3490:         if (@version_parts) {
 3491:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3492:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3493: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3494: 	    foreach my $new_part (@version_parts) {
 3495: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3496: 				$new_part,\%newrecord);
 3497: 	    }
 3498:         }
 3499: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3500: 				$env{'request.course.id'},$domain,$stuname);
 3501: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3502: 				     $cdom,$cnum,$domain,$stuname);
 3503:     }
 3504:     if ($aggregateflag) {
 3505:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3506: 			      $cdom,$cnum);
 3507:     }
 3508:     return ('',$pts,$wgt,$totchg);
 3509: }
 3510: 
 3511: sub makehidden {
 3512:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3513:     return unless (ref($record) eq 'HASH');
 3514:     my %modified;
 3515:     my $numchanged = 0;
 3516:     if (exists($record->{$version.':keys'})) {
 3517:         my $partsregexp = $parts;
 3518:         $partsregexp =~ s/,/|/g;
 3519:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3520:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3521:                  my $item = $1;
 3522:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3523:                      $modified{$key} = $record->{$version.':'.$key};
 3524:                  }
 3525:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3526:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3527:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3528:                 $modified{$key} = $record->{$version.':'.$key};
 3529:             }
 3530:         }
 3531:         if (keys(%modified)) {
 3532:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3533:                                           $domain,$stuname,$tolog) eq 'ok') {
 3534:                 $numchanged ++;
 3535:             }
 3536:         }
 3537:     }
 3538:     return $numchanged;
 3539: }
 3540: 
 3541: sub check_and_remove_from_queue {
 3542:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3543:     my @ungraded_parts;
 3544:     foreach my $part (@{$parts}) {
 3545: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3546: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3547: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3548: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3549: 		) {
 3550: 	    push(@ungraded_parts, $part);
 3551: 	}
 3552:     }
 3553:     if ( !@ungraded_parts ) {
 3554: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3555: 					       $cnum,$domain,$stuname);
 3556:     }
 3557: }
 3558: 
 3559: sub handback_files {
 3560:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3561:     my $portfolio_root = '/userfiles/portfolio';
 3562:     my $res_error;
 3563:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3564:     if ($res_error) {
 3565:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3566:         return;
 3567:     }
 3568:     my @handedback;
 3569:     my $file_msg;
 3570:     my @part_response_id = &flatten_responseType($responseType);
 3571:     foreach my $part_response_id (@part_response_id) {
 3572:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3573: 	my $part_resp = join('_',@{ $part_response_id });
 3574:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3575:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3576:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3577:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3578:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3579:                     my ($directory,$answer_file) = 
 3580:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3581:                     my ($answer_name,$answer_ver,$answer_ext) =
 3582: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3583: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3584:                     my $getpropath = 1;
 3585:                     my ($dir_list,$listerror) =
 3586:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3587:                                                  $domain,$stuname,$getpropath);
 3588: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3589:                     # fix filename
 3590:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3591:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3592:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3593:             	                                $save_file_name);
 3594:                     if ($result !~ m|^/uploaded/|) {
 3595:                         $request->print('<br /><span class="LC_error">'.
 3596:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3597:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3598:                                         '</span>');
 3599:                     } else {
 3600:                         # mark the file as read only
 3601:                         push(@handedback,$save_file_name);
 3602: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3603: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3604: 			}
 3605:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3606: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3607:                     }
 3608:                     $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>'));
 3609:                 }
 3610:             }
 3611:         }
 3612:     }
 3613:     if (@handedback > 0) {
 3614:         $request->print('<br />');
 3615:         my @what = ($symb,$env{'request.course.id'},'handback');
 3616:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3617:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3618:         my ($subject,$message);
 3619:         if (scalar(@handedback) == 1) {
 3620:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3621:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3622:         } else {
 3623:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3624:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3625:         }
 3626:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3627:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3628:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3629:         my ($feedurl,$showsymb) =
 3630:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3631:         my $restitle = &Apache::lonnet::gettitle($symb);
 3632:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3633:         my $msgstatus =
 3634:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3635:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3636:                  $restitle);
 3637:         if ($msgstatus) {
 3638:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3639:         }
 3640:     }
 3641:     return;
 3642: }
 3643: 
 3644: sub get_feedurl_and_symb {
 3645:     my ($symb,$uname,$udom) = @_;
 3646:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3647:     $url = &Apache::lonnet::clutter($url);
 3648:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3649: 					$symb,$udom,$uname);
 3650:     if ($encrypturl =~ /^yes$/i) {
 3651: 	&Apache::lonenc::encrypted(\$url,1);
 3652: 	&Apache::lonenc::encrypted(\$symb,1);
 3653:     }
 3654:     return ($url,$symb);
 3655: }
 3656: 
 3657: sub get_submitted_files {
 3658:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3659:     my @files;
 3660:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3661:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3662:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3663:     	    push(@files,$file_url.$file);
 3664:         }
 3665:     }
 3666:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3667:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3668:     }
 3669:     return (\@files);
 3670: }
 3671: 
 3672: # ----------- Provides number of tries since last reset.
 3673: sub get_num_tries {
 3674:     my ($record,$last_reset,$part) = @_;
 3675:     my $timestamp = '';
 3676:     my $num_tries = 0;
 3677:     if ($$record{'version'}) {
 3678:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3679:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3680:                 $timestamp = $$record{$version.':timestamp'};
 3681:                 if ($timestamp > $last_reset) {
 3682:                     $num_tries ++;
 3683:                 } else {
 3684:                     last;
 3685:                 }
 3686:             }
 3687:         }
 3688:     }
 3689:     return $num_tries;
 3690: }
 3691: 
 3692: # ----------- Determine decrements required in aggregate totals 
 3693: sub decrement_aggs {
 3694:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3695:     my %decrement = (
 3696:                         attempts => 0,
 3697:                         users => 0,
 3698:                         correct => 0
 3699:                     );
 3700:     $decrement{'attempts'} = $aggtries;
 3701:     if ($solvedstatus =~ /^correct/) {
 3702:         $decrement{'correct'} = 1;
 3703:     }
 3704:     if ($aggtries == $totaltries) {
 3705:         $decrement{'users'} = 1;
 3706:     }
 3707:     foreach my $type (keys(%decrement)) {
 3708:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3709:     }
 3710:     return;
 3711: }
 3712: 
 3713: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3714: sub get_last_resets {
 3715:     my ($symb,$courseid,$partids) =@_;
 3716:     my %last_resets;
 3717:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3718:     my $cname = $env{'course.'.$courseid.'.num'};
 3719:     my @keys;
 3720:     foreach my $part (@{$partids}) {
 3721: 	push(@keys,"$symb\0$part\0resettime");
 3722:     }
 3723:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3724: 				     $cdom,$cname);
 3725:     foreach my $part (@{$partids}) {
 3726: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3727:     }
 3728:     return %last_resets;
 3729: }
 3730: 
 3731: # ----------- Handles creating versions for portfolio files as answers
 3732: sub version_portfiles {
 3733:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3734:     my $version_parts = join('|',@$v_flag);
 3735:     my @returned_keys;
 3736:     my $parts = join('|', @$parts_graded);
 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:             if (@portfiles) {
 3743:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3744:                                                       \@versioned_portfiles);
 3745:             }
 3746:             $$record{$key} = join(',',@versioned_portfiles);
 3747:             push(@returned_keys,$key);
 3748:         }
 3749:     } 
 3750:     return (@returned_keys);   
 3751: }
 3752: 
 3753: #--------------------------------------------------------------------------------------
 3754: #
 3755: #-------------------------- Next few routines handles grading by section or whole class
 3756: #
 3757: #--- Javascript to handle grading by section or whole class
 3758: sub viewgrades_js {
 3759:     my ($request) = shift;
 3760: 
 3761:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3762:     &js_escape(\$alertmsg);
 3763:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3764:    function writePoint(partid,weight,point) {
 3765: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3766: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3767: 	if (point == "textval") {
 3768: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3769: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3770: 		alert("$alertmsg"+parseFloat(point));
 3771: 		var resetbox = false;
 3772: 		for (var i=0; i<radioButton.length; i++) {
 3773: 		    if (radioButton[i].checked) {
 3774: 			textbox.value = i;
 3775: 			resetbox = true;
 3776: 		    }
 3777: 		}
 3778: 		if (!resetbox) {
 3779: 		    textbox.value = "";
 3780: 		}
 3781: 		return;
 3782: 	    }
 3783: 	    if (parseFloat(point) > parseFloat(weight)) {
 3784: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3785: 				   ") greater than the weight for the part. Accept?");
 3786: 		if (resp == false) {
 3787: 		    textbox.value = "";
 3788: 		    return;
 3789: 		}
 3790: 	    }
 3791: 	    for (var i=0; i<radioButton.length; i++) {
 3792: 		radioButton[i].checked=false;
 3793: 		if (parseFloat(point) == i) {
 3794: 		    radioButton[i].checked=true;
 3795: 		}
 3796: 	    }
 3797: 
 3798: 	} else {
 3799: 	    textbox.value = parseFloat(point);
 3800: 	}
 3801: 	for (i=0;i<document.classgrade.total.value;i++) {
 3802: 	    var user = document.classgrade["ctr"+i].value;
 3803: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3804: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3805: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3806: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3807: 	    if (saveval != "correct") {
 3808: 		scorename.value = point;
 3809: 		if (selname[0].selected != true) {
 3810: 		    selname[0].selected = true;
 3811: 		}
 3812: 	    }
 3813: 	}
 3814: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3815:     }
 3816: 
 3817:     function writeRadText(partid,weight) {
 3818: 	var selval   = document.classgrade["SELVAL_"+partid];
 3819: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3820:         var override = document.classgrade["FORCE_"+partid].checked;
 3821: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3822: 	if (selval[1].selected || selval[2].selected) {
 3823: 	    for (var i=0; i<radioButton.length; i++) {
 3824: 		radioButton[i].checked=false;
 3825: 
 3826: 	    }
 3827: 	    textbox.value = "";
 3828: 
 3829: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3830: 		var user = document.classgrade["ctr"+i].value;
 3831: 		user = user.replace(new RegExp(':', 'g'),"_");
 3832: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3833: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3834: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3835: 		if ((saveval != "correct") || override) {
 3836: 		    scorename.value = "";
 3837: 		    if (selval[1].selected) {
 3838: 			selname[1].selected = true;
 3839: 		    } else {
 3840: 			selname[2].selected = true;
 3841: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3842: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3843: 		    }
 3844: 		}
 3845: 	    }
 3846: 	} else {
 3847: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3848: 		var user = document.classgrade["ctr"+i].value;
 3849: 		user = user.replace(new RegExp(':', 'g'),"_");
 3850: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3851: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3852: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3853: 		if ((saveval != "correct") || override) {
 3854: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3855: 		    selname[0].selected = true;
 3856: 		}
 3857: 	    }
 3858: 	}	    
 3859:     }
 3860: 
 3861:     function changeSelect(partid,user) {
 3862: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3863: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3864: 	var point  = textbox.value;
 3865: 	var weight = document.classgrade["weight_"+partid].value;
 3866: 
 3867: 	if (isNaN(point) || parseFloat(point) < 0) {
 3868: 	    alert("$alertmsg"+parseFloat(point));
 3869: 	    textbox.value = "";
 3870: 	    return;
 3871: 	}
 3872: 	if (parseFloat(point) > parseFloat(weight)) {
 3873: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3874: 			       ") greater than the weight of the part. Accept?");
 3875: 	    if (resp == false) {
 3876: 		textbox.value = "";
 3877: 		return;
 3878: 	    }
 3879: 	}
 3880: 	selval[0].selected = true;
 3881:     }
 3882: 
 3883:     function changeOneScore(partid,user) {
 3884: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3885: 	if (selval[1].selected || selval[2].selected) {
 3886: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3887: 	    if (selval[2].selected) {
 3888: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3889: 	    }
 3890:         }
 3891:     }
 3892: 
 3893:     function resetEntry(numpart) {
 3894: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3895: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3896: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3897: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3898: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3899: 	    for (var i=0; i<radioButton.length; i++) {
 3900: 		radioButton[i].checked=false;
 3901: 
 3902: 	    }
 3903: 	    textbox.value = "";
 3904: 	    selval[0].selected = true;
 3905: 
 3906: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3907: 		var user = document.classgrade["ctr"+i].value;
 3908: 		user = user.replace(new RegExp(':', 'g'),"_");
 3909: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3910: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3911: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3912: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3913: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3914: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3915: 		if (saveselval == "excused") {
 3916: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3917: 		} else {
 3918: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3919: 		}
 3920: 	    }
 3921: 	}
 3922:     }
 3923: 
 3924: VIEWJAVASCRIPT
 3925: }
 3926: 
 3927: #--- show scores for a section or whole class w/ option to change/update a score
 3928: sub viewgrades {
 3929:     my ($request,$symb) = @_;
 3930:     my ($is_tool,$toolsymb);
 3931:     if ($symb =~ /ext\.tool$/) {
 3932:         $is_tool = 1;
 3933:         $toolsymb = $symb;
 3934:     }
 3935:     &viewgrades_js($request);
 3936: 
 3937:     #need to make sure we have the correct data for later EXT calls, 
 3938:     #thus invalidate the cache
 3939:     &Apache::lonnet::devalidatecourseresdata(
 3940:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3941:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3942:     &Apache::lonnet::clear_EXT_cache_status();
 3943: 
 3944:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3945: 
 3946:     #view individual student submission form - called using Javascript viewOneStudent
 3947:     $result.=&jscriptNform($symb);
 3948: 
 3949:     #beginning of class grading form
 3950:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3951:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3952: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3953: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3954: 	&build_section_inputs().
 3955: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3956: 
 3957:     #retrieve selected groups
 3958:     my (@groups,$group_display);
 3959:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3960:     if (grep(/^all$/,@groups)) {
 3961:         @groups = ('all');
 3962:     } elsif (grep(/^none$/,@groups)) {
 3963:         @groups = ('none');
 3964:     } elsif (@groups > 0) {
 3965:         $group_display = join(', ',@groups);
 3966:     }
 3967: 
 3968:     my ($common_header,$specific_header,@sections,$section_display);
 3969:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3970:     if (grep(/^all$/,@sections)) {
 3971:         @sections = ('all');
 3972:         if ($group_display) {
 3973:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3974:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3975:         } elsif (grep(/^none$/,@groups)) {
 3976:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3977:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3978:         } else {
 3979: 	    $common_header = &mt('Assign Common Grade to Class');
 3980:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3981:         }
 3982:     } elsif (grep(/^none$/,@sections)) {
 3983:         @sections = ('none');
 3984:         if ($group_display) {
 3985:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3986:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3987:         } elsif (grep(/^none$/,@groups)) {
 3988:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3989:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3990:         } else {
 3991:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3992: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3993:         }
 3994:     } else {
 3995:         $section_display = join (", ",@sections);
 3996:         if ($group_display) {
 3997:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3998:                                  $section_display,$group_display);
 3999:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4000:                                    $section_display,$group_display);
 4001:         } elsif (grep(/^none$/,@groups)) {
 4002:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4003:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4004:         } else {
 4005:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4006: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4007:         }
 4008:     }
 4009:     my %submit_types = &substatus_options();
 4010:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4011: 
 4012:     if ($env{'form.submitonly'} eq 'all') {
 4013:         $result.= '<h3>'.$common_header.'</h3>';
 4014:     } else {
 4015:         my $text;
 4016:         if ($is_tool) {
 4017:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4018:         } else {
 4019:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4020:         }
 4021:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4022:     }
 4023:     $result .= &Apache::loncommon::start_data_table();
 4024:     #radio buttons/text box for assigning points for a section or class.
 4025:     #handles different parts of a problem
 4026:     my $res_error;
 4027:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4028:     if ($res_error) {
 4029:         return &navmap_errormsg();
 4030:     }
 4031:     my %weight = ();
 4032:     my $ctsparts = 0;
 4033:     my %seen = ();
 4034:     my @part_response_id;
 4035:     if ($is_tool) {
 4036:         @part_response_id = ([0,'']);
 4037:     } else {
 4038:         @part_response_id = &flatten_responseType($responseType);
 4039:     }
 4040:     foreach my $part_response_id (@part_response_id) {
 4041:     	my ($partid,$respid) = @{ $part_response_id };
 4042: 	my $part_resp = join('_',@{ $part_response_id });
 4043: 	next if $seen{$partid};
 4044: 	$seen{$partid}++;
 4045: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4046: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4047: 
 4048: 	my $display_part=&get_display_part($partid,$symb);
 4049: 	my $radio.='<table border="0"><tr>';  
 4050: 	my $ctr = 0;
 4051: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4052: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4053: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4054: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4055: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4056: 	    $ctr++;
 4057: 	}
 4058: 	$radio.='</tr></table>';
 4059: 	my $line = '<input type="text" name="TEXTVAL_'.
 4060: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4061: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4062: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4063:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4064:             '<select name="SELVAL_'.$partid.'" '.
 4065:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4066:                 $weight{$partid}.')"> '.
 4067: 	    '<option selected="selected"> </option>'.
 4068: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4069: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4070: 	    '</select></td>'.
 4071:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4072: 	$line.='<input type="hidden" name="partid_'.
 4073: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4074: 	$line.='<input type="hidden" name="weight_'.
 4075: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4076: 
 4077: 	$result.=
 4078: 	    &Apache::loncommon::start_data_table_row()."\n".
 4079: 	    '<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>'.
 4080: 	    &Apache::loncommon::end_data_table_row()."\n";
 4081: 	$ctsparts++;
 4082:     }
 4083:     $result.=&Apache::loncommon::end_data_table()."\n".
 4084: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4085:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4086: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4087: 
 4088:     #table listing all the students in a section/class
 4089:     #header of table
 4090:     if ($env{'form.submitonly'} eq 'all') {
 4091:         $result.= '<h3>'.$specific_header.'</h3>';
 4092:     } else {
 4093:         my $text;
 4094:         if ($is_tool) {
 4095:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4096:         } else {
 4097:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4098:         }
 4099:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4100:     }
 4101:     $result.= &Apache::loncommon::start_data_table().
 4102: 	      &Apache::loncommon::start_data_table_header_row().
 4103: 	      '<th>'.&mt('No.').'</th>'.
 4104: 	      '<th>'.&nameUserString('header')."</th>\n";
 4105:     my $partserror;
 4106:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4107:     if ($partserror) {
 4108:         return &navmap_errormsg();
 4109:     }
 4110:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4111:     my @partids = ();
 4112:     foreach my $part (@parts) {
 4113: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4114:         my $narrowtext = &mt('Tries');
 4115: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4116: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4117: 	my ($partid) = &split_part_type($part);
 4118:         push(@partids,$partid);
 4119: #
 4120: # FIXME: Looks like $display looks at English text
 4121: #
 4122: 	my $display_part=&get_display_part($partid,$symb);
 4123: 	if ($display =~ /^Partial Credit Factor/) {
 4124: 	    $result.='<th>'.
 4125: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4126: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4127: 	    next;
 4128: 	    
 4129: 	} else {
 4130: 	    if ($display =~ /Problem Status/) {
 4131: 		my $grade_status_mt = &mt('Grade Status');
 4132: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4133: 	    }
 4134: 	    my $part_mt = &mt('Part:');
 4135: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4136: 	}
 4137: 
 4138: 	$result.='<th>'.$display.'</th>'."\n";
 4139:     }
 4140:     $result.=&Apache::loncommon::end_data_table_header_row();
 4141: 
 4142:     my %last_resets = 
 4143: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4144: 
 4145:     #get info for each student
 4146:     #list all the students - with points and grade status
 4147:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4148:     my $ctr = 0;
 4149:     foreach (sort 
 4150: 	     {
 4151: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4152: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4153: 		 }
 4154: 		 return $a cmp $b;
 4155: 	     } (keys(%$fullname))) {
 4156: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4157: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4158:     }
 4159:     $result.=&Apache::loncommon::end_data_table();
 4160:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4161:     $result.='<input type="button" value="'.&mt('Save').'" '.
 4162: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4163:     if ($ctr == 0) {
 4164:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4165:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4166:                 '<span class="LC_warning">';
 4167:         if ($env{'form.submitonly'} eq 'all') {
 4168:             if (grep(/^all$/,@sections)) {
 4169:                 if (grep(/^all$/,@groups)) {
 4170:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4171:                                    $stu_status);
 4172:                 } elsif (grep(/^none$/,@groups)) {
 4173:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4174:                                    $stu_status); 
 4175:                 } else {
 4176:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4177:                                    $group_display,$stu_status);
 4178:                 }
 4179:             } elsif (grep(/^none$/,@sections)) {
 4180:                 if (grep(/^all$/,@groups)) {
 4181:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4182:                                    $stu_status);
 4183:                 } elsif (grep(/^none$/,@groups)) {
 4184:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4185:                                    $stu_status);
 4186:                 } else {
 4187:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4188:                                    $group_display,$stu_status);
 4189:                 }
 4190:             } else {
 4191:                 if (grep(/^all$/,@groups)) {
 4192:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4193:                                    $section_display,$stu_status);
 4194:                 } elsif (grep(/^none$/,@groups)) {
 4195:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4196:                                    $section_display,$stu_status);
 4197:                 } else {
 4198:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4199:                                    $section_display,$group_display,$stu_status);
 4200:                 }
 4201:             }
 4202:         } else {
 4203:             if (grep(/^all$/,@sections)) {
 4204:                 if (grep(/^all$/,@groups)) {
 4205:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4206:                                    $stu_status,$submission_status);
 4207:                 } elsif (grep(/^none$/,@groups)) {
 4208:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4209:                                    $stu_status,$submission_status);
 4210:                 } else {
 4211:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4212:                                    $group_display,$stu_status,$submission_status);
 4213:                 }
 4214:             } elsif (grep(/^none$/,@sections)) {
 4215:                 if (grep(/^all$/,@groups)) {
 4216:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4217:                                    $stu_status,$submission_status);
 4218:                 } elsif (grep(/^none$/,@groups)) {
 4219:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4220:                                    $stu_status,$submission_status);
 4221:                 } else {
 4222:                     $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.',
 4223:                                    $group_display,$stu_status,$submission_status);
 4224:                 }
 4225:             } else {
 4226:                 if (grep(/^all$/,@groups)) {
 4227: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4228: 	                           $section_display,$stu_status,$submission_status);
 4229:                 } elsif (grep(/^none$/,@groups)) {
 4230:                     $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.',
 4231:                                    $section_display,$stu_status,$submission_status);
 4232:                 } else {
 4233:                     $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.',
 4234:                                    $section_display,$group_display,$stu_status,$submission_status);
 4235:                 }
 4236:             }
 4237:         }
 4238: 	$result .= '</span><br />';
 4239:     }
 4240:     return $result;
 4241: }
 4242: 
 4243: #--- call by previous routine to display each student who satisfies submission filter. 
 4244: sub viewstudentgrade {
 4245:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4246:     my ($uname,$udom) = split(/:/,$student);
 4247:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4248:     my $submitonly = $env{'form.submitonly'};
 4249:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4250:         my %partstatus = ();
 4251:         if (ref($parts) eq 'ARRAY') {
 4252:             foreach my $apart (@{$parts}) {
 4253:                 my ($part,$type) = &split_part_type($apart);
 4254:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4255:                 $status = 'nothing' if ($status eq '');
 4256:                 $partstatus{$part}      = $status;
 4257:                 my $subkey = "resource.$part.submitted_by";
 4258:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4259:             }
 4260:             my $submitted = 0;
 4261:             my $graded = 0;
 4262:             my $incorrect = 0;
 4263:             foreach my $key (keys(%partstatus)) {
 4264:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4265:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4266:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4267: 
 4268:                 my $partid = (split(/\./,$key))[1];
 4269:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4270:                     $submitted = 0;
 4271:                 }
 4272:             }
 4273:             return if (!$submitted && ($submitonly eq 'yes' ||
 4274:                                        $submitonly eq 'incorrect' ||
 4275:                                        $submitonly eq 'graded'));
 4276:             return if (!$graded && ($submitonly eq 'graded'));
 4277:             return if (!$incorrect && $submitonly eq 'incorrect');
 4278:         }
 4279:     }
 4280:     if ($submitonly eq 'queued') {
 4281:         my ($cdom,$cnum) = split(/_/,$courseid);
 4282:         my %queue_status =
 4283:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4284:                                                     $udom,$uname);
 4285:         return if (!defined($queue_status{'gradingqueue'}));
 4286:     }
 4287:     $$ctr++;
 4288:     my %aggregates = ();
 4289:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4290: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4291: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4292: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4293: 	'\');" target="_self">'.$fullname.'</a> '.
 4294: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4295:     $student=~s/:/_/; # colon doen't work in javascript for names
 4296:     foreach my $apart (@$parts) {
 4297: 	my ($part,$type) = &split_part_type($apart);
 4298: 	my $score=$record{"resource.$part.$type"};
 4299:         $result.='<td align="center">';
 4300:         my ($aggtries,$totaltries);
 4301:         unless (exists($aggregates{$part})) {
 4302: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4303: 	    $aggtries = $totaltries;
 4304:             if ($$last_resets{$part}) {  
 4305:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4306: 					   $part);
 4307:             }
 4308:             $result.='<input type="hidden" name="'.
 4309:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4310:             $result.='<input type="hidden" name="'.
 4311:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4312:             $aggregates{$part} = 1;
 4313:         }
 4314: 	if ($type eq 'awarded') {
 4315: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4316: 	    $result.='<input type="hidden" name="'.
 4317: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4318: 	    $result.='<input type="text" name="'.
 4319: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4320:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4321: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4322: 	} elsif ($type eq 'solved') {
 4323: 	    my ($status,$foo)=split(/_/,$score,2);
 4324: 	    $status = 'nothing' if ($status eq '');
 4325: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4326: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4327: 	    $result.='&nbsp;<select name="'.
 4328: 		'GD_'.$student.'_'.$part.'_solved" '.
 4329:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4330: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4331: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4332: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4333: 	    $result.="</select>&nbsp;</td>\n";
 4334: 	} else {
 4335: 	    $result.='<input type="hidden" name="'.
 4336: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4337: 		    "\n";
 4338: 	    $result.='<input type="text" name="'.
 4339: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4340: 		'value="'.$score.'" size="4" /></td>'."\n";
 4341: 	}
 4342:     }
 4343:     $result.=&Apache::loncommon::end_data_table_row();
 4344:     return $result;
 4345: }
 4346: 
 4347: #--- change scores for all the students in a section/class
 4348: #    record does not get update if unchanged
 4349: sub editgrades {
 4350:     my ($request,$symb) = @_;
 4351:     my $toolsymb;
 4352:     if ($symb =~ /ext\.tool$/) {
 4353:         $toolsymb = $symb;
 4354:     }
 4355: 
 4356:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4357:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4358:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4359: 
 4360:     my $result= &Apache::loncommon::start_data_table().
 4361: 	&Apache::loncommon::start_data_table_header_row().
 4362: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4363: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4364:     my %scoreptr = (
 4365: 		    'correct'  =>'correct_by_override',
 4366: 		    'incorrect'=>'incorrect_by_override',
 4367: 		    'excused'  =>'excused',
 4368: 		    'ungraded' =>'ungraded_attempted',
 4369:                     'credited' =>'credit_attempted',
 4370: 		    'nothing'  => '',
 4371: 		    );
 4372:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4373: 
 4374:     my (@partid);
 4375:     my %weight = ();
 4376:     my %columns = ();
 4377:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4378: 
 4379:     my $partserror;
 4380:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4381:     if ($partserror) {
 4382:         return &navmap_errormsg();
 4383:     }
 4384:     my $header;
 4385:     while ($ctr < $env{'form.totalparts'}) {
 4386: 	my $partid = $env{'form.partid_'.$ctr};
 4387: 	push(@partid,$partid);
 4388: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4389: 	$ctr++;
 4390:     }
 4391:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4392:     my $totcolspan = 0;
 4393:     foreach my $partid (@partid) {
 4394: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4395: 	    '<th align="center">'.&mt('New Score').'</th>';
 4396: 	$columns{$partid}=2;
 4397: 	foreach my $stores (@parts) {
 4398: 	    my ($part,$type) = &split_part_type($stores);
 4399: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4400: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4401: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4402: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4403:             my $narrowtext = &mt('Tries');
 4404: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4405: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4406: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4407: 	    $columns{$partid}+=2;
 4408: 	}
 4409:         $totcolspan += $columns{$partid};
 4410:     }
 4411:     foreach my $partid (@partid) {
 4412: 	my $display_part=&get_display_part($partid,$symb);
 4413: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4414: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4415: 	    '</th>';
 4416: 
 4417:     }
 4418:     $result .= &Apache::loncommon::end_data_table_header_row().
 4419: 	&Apache::loncommon::start_data_table_header_row().
 4420: 	$header.
 4421: 	&Apache::loncommon::end_data_table_header_row();
 4422:     my @noupdate;
 4423:     my ($updateCtr,$noupdateCtr) = (1,1);
 4424:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4425: 	my $user = $env{'form.ctr'.$i};
 4426: 	my ($uname,$udom)=split(/:/,$user);
 4427: 	my %newrecord;
 4428: 	my $updateflag = 0;
 4429: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4430: 	my $canmodify = &canmodify($usec);
 4431: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4432: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4433: 	if (!$canmodify) {
 4434: 	    push(@noupdate,
 4435: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4436: 		 &mt('Not allowed to modify student')."</span></td>");
 4437: 	    next;
 4438: 	}
 4439:         my %aggregate = ();
 4440:         my $aggregateflag = 0;
 4441: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4442: 	foreach (@partid) {
 4443: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4444: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4445: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4446: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4447: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4448: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4449: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4450: 	    my $score;
 4451: 	    if ($partial eq '') {
 4452: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4453: 	    } elsif ($partial > 0) {
 4454: 		$score = 'correct_by_override';
 4455: 	    } elsif ($partial == 0) {
 4456: 		$score = 'incorrect_by_override';
 4457: 	    }
 4458: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4459: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4460: 
 4461: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4462: 		"$env{'user.name'}:$env{'user.domain'}";
 4463: 	    if ($dropMenu eq 'reset status' &&
 4464: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4465: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4466: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4467: 		$newrecord{'resource.'.$_.'.award'} = '';
 4468: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4469: 		$updateflag = 1;
 4470:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4471:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4472:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4473:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4474:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4475:                     $aggregateflag = 1;
 4476:                 }
 4477: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4478: 		$updateflag = 1;
 4479: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4480: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4481: 		$rec_update++;
 4482: 	    }
 4483: 
 4484: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4485: 		'<td align="center">'.$awarded.
 4486: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4487: 
 4488: 
 4489: 	    my $partid=$_;
 4490: 	    foreach my $stores (@parts) {
 4491: 		my ($part,$type) = &split_part_type($stores);
 4492: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4493: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4494: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4495: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4496: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4497: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4498: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4499: 		    $updateflag=1;
 4500: 		}
 4501: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4502: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4503: 	    }
 4504: 	}
 4505: 	$line.="\n";
 4506: 
 4507: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4508: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4509: 
 4510: 	if ($updateflag) {
 4511: 	    $count++;
 4512: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4513: 				    $udom,$uname);
 4514: 
 4515: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4516: 					      $cnum,$udom,$uname)) {
 4517: 		# need to figure out if should be in queue.
 4518: 		my %record =  
 4519: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4520: 					     $udom,$uname);
 4521: 		my $all_graded = 1;
 4522: 		my $none_graded = 1;
 4523: 		foreach my $part (@parts) {
 4524: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4525: 			$all_graded = 0;
 4526: 		    } else {
 4527: 			$none_graded = 0;
 4528: 		    }
 4529: 		}
 4530: 
 4531: 		if ($all_graded || $none_graded) {
 4532: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4533: 							   $symb,$cdom,$cnum,
 4534: 							   $udom,$uname);
 4535: 		}
 4536: 	    }
 4537: 
 4538: 	    $result.=&Apache::loncommon::start_data_table_row().
 4539: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4540: 		&Apache::loncommon::end_data_table_row();
 4541: 	    $updateCtr++;
 4542: 	} else {
 4543: 	    push(@noupdate,
 4544: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4545: 	    $noupdateCtr++;
 4546: 	}
 4547:         if ($aggregateflag) {
 4548:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4549: 				  $cdom,$cnum);
 4550:         }
 4551:     }
 4552:     if (@noupdate) {
 4553:         my $numcols=$totcolspan+2;
 4554: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4555: 	    '<td align="center" colspan="'.$numcols.'">'.
 4556: 	    &mt('No Changes Occurred For the Students Below').
 4557: 	    '</td>'.
 4558: 	    &Apache::loncommon::end_data_table_row();
 4559: 	foreach my $line (@noupdate) {
 4560: 	    $result.=
 4561: 		&Apache::loncommon::start_data_table_row().
 4562: 		$line.
 4563: 		&Apache::loncommon::end_data_table_row();
 4564: 	}
 4565:     }
 4566:     $result .= &Apache::loncommon::end_data_table();
 4567:     my $msg = '<p><b>'.
 4568: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4569: 	    $rec_update,$count).'</b><br />'.
 4570: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4571: 	'</b></p>';
 4572:     return $title.$msg.$result;
 4573: }
 4574: 
 4575: sub split_part_type {
 4576:     my ($partstr) = @_;
 4577:     my ($temp,@allparts)=split(/_/,$partstr);
 4578:     my $type=pop(@allparts);
 4579:     my $part=join('_',@allparts);
 4580:     return ($part,$type);
 4581: }
 4582: 
 4583: #------------- end of section for handling grading by section/class ---------
 4584: #
 4585: #----------------------------------------------------------------------------
 4586: 
 4587: 
 4588: #----------------------------------------------------------------------------
 4589: #
 4590: #-------------------------- Next few routines handles grading by csv upload
 4591: #
 4592: #--- Javascript to handle csv upload
 4593: sub csvupload_javascript_reverse_associate {
 4594:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4595:     my $error2=&mt('You need to specify at least one grading field');
 4596:   &js_escape(\$error1);
 4597:   &js_escape(\$error2);
 4598:   return(<<ENDPICK);
 4599:   function verify(vf) {
 4600:     var foundsomething=0;
 4601:     var founduname=0;
 4602:     var foundID=0;
 4603:     var foundclicker=0;
 4604:     for (i=0;i<=vf.nfields.value;i++) {
 4605:       tw=eval('vf.f'+i+'.selectedIndex');
 4606:       if (i==0 && tw!=0) { foundID=1; }
 4607:       if (i==1 && tw!=0) { founduname=1; }
 4608:       if (i==2 && tw!=0) { foundclicker=1; }
 4609:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4610:     }
 4611:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4612: 	alert('$error1');
 4613: 	return;
 4614:     }
 4615:     if (foundsomething==0) {
 4616: 	alert('$error2');
 4617: 	return;
 4618:     }
 4619:     vf.submit();
 4620:   }
 4621:   function flip(vf,tf) {
 4622:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4623:     var i;
 4624:     for (i=0;i<=vf.nfields.value;i++) {
 4625:       //can not pick the same destination field for both name and domain
 4626:       if (((i ==0)||(i ==1)) && 
 4627:           ((tf==0)||(tf==1)) && 
 4628:           (i!=tf) &&
 4629:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4630:         eval('vf.f'+i+'.selectedIndex=0;')
 4631:       }
 4632:     }
 4633:   }
 4634: ENDPICK
 4635: }
 4636: 
 4637: sub csvupload_javascript_forward_associate {
 4638:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4639:     my $error2=&mt('You need to specify at least one grading field');
 4640:   &js_escape(\$error1);
 4641:   &js_escape(\$error2);
 4642:   return(<<ENDPICK);
 4643:   function verify(vf) {
 4644:     var foundsomething=0;
 4645:     var founduname=0;
 4646:     var foundID=0;
 4647:     var foundclicker=0;
 4648:     for (i=0;i<=vf.nfields.value;i++) {
 4649:       tw=eval('vf.f'+i+'.selectedIndex');
 4650:       if (tw==1) { foundID=1; }
 4651:       if (tw==2) { founduname=1; }
 4652:       if (tw==3) { foundclicker=1; }
 4653:       if (tw>4) { foundsomething=1; }
 4654:     }
 4655:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4656: 	alert('$error1');
 4657: 	return;
 4658:     }
 4659:     if (foundsomething==0) {
 4660: 	alert('$error2');
 4661: 	return;
 4662:     }
 4663:     vf.submit();
 4664:   }
 4665:   function flip(vf,tf) {
 4666:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4667:     var i;
 4668:     //can not pick the same destination field twice
 4669:     for (i=0;i<=vf.nfields.value;i++) {
 4670:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4671:         eval('vf.f'+i+'.selectedIndex=0;')
 4672:       }
 4673:     }
 4674:   }
 4675: ENDPICK
 4676: }
 4677: 
 4678: sub csvuploadmap_header {
 4679:     my ($request,$symb,$datatoken,$distotal)= @_;
 4680:     my $javascript;
 4681:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4682: 	$javascript=&csvupload_javascript_reverse_associate();
 4683:     } else {
 4684: 	$javascript=&csvupload_javascript_forward_associate();
 4685:     }
 4686: 
 4687:     $symb = &Apache::lonenc::check_encrypt($symb);
 4688:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4689:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4690:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4691:     my $reverse=&mt("Reverse Association");
 4692:     $request->print(<<ENDPICK);
 4693: <br />
 4694: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4695: <input type="hidden" name="associate"  value="" />
 4696: <input type="hidden" name="phase"      value="three" />
 4697: <input type="hidden" name="datatoken"  value="$datatoken" />
 4698: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4699: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4700: <input type="hidden" name="upfile_associate" 
 4701:                                        value="$env{'form.upfile_associate'}" />
 4702: <input type="hidden" name="symb"       value="$symb" />
 4703: <input type="hidden" name="command"    value="csvuploadoptions" />
 4704: <hr />
 4705: ENDPICK
 4706:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4707:     return '';
 4708: 
 4709: }
 4710: 
 4711: sub csvupload_fields {
 4712:     my ($symb,$errorref) = @_;
 4713:     my $toolsymb;
 4714:     if ($symb =~ /ext\.tool$/) {
 4715:         $toolsymb = $symb;
 4716:     }
 4717:     my (@parts) = &getpartlist($symb,$errorref);
 4718:     if (ref($errorref)) {
 4719:         if ($$errorref) {
 4720:             return;
 4721:         }
 4722:     }
 4723: 
 4724:     my @fields=(['ID','Student/Employee ID'],
 4725: 		['username','Student Username'],
 4726: 		['clicker','Clicker ID'],
 4727: 		['domain','Student Domain']);
 4728:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4729:     foreach my $part (sort(@parts)) {
 4730: 	my @datum;
 4731: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4732: 	my $name=$part;
 4733: 	if (!$display) { $display = $name; }
 4734: 	@datum=($name,$display);
 4735: 	if ($name=~/^stores_(.*)_awarded/) {
 4736: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4737: 	}
 4738: 	push(@fields,\@datum);
 4739:     }
 4740:     return (@fields);
 4741: }
 4742: 
 4743: sub csvuploadmap_footer {
 4744:     my ($request,$i,$keyfields) =@_;
 4745:     my $buttontext = &mt('Assign Grades');
 4746:     $request->print(<<ENDPICK);
 4747: </table>
 4748: <input type="hidden" name="nfields" value="$i" />
 4749: <input type="hidden" name="keyfields" value="$keyfields" />
 4750: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4751: </form>
 4752: ENDPICK
 4753: }
 4754: 
 4755: sub checkforfile_js {
 4756:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4757:     &js_escape(\$alertmsg);
 4758:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4759:     function checkUpload(formname) {
 4760: 	if (formname.upfile.value == "") {
 4761: 	    alert("$alertmsg");
 4762: 	    return false;
 4763: 	}
 4764: 	formname.submit();
 4765:     }
 4766: CSVFORMJS
 4767:     return $result;
 4768: }
 4769: 
 4770: sub upcsvScores_form {
 4771:     my ($request,$symb) = @_;
 4772:     if (!$symb) {return '';}
 4773:     my $result=&checkforfile_js();
 4774:     $result.=&Apache::loncommon::start_data_table().
 4775:              &Apache::loncommon::start_data_table_header_row().
 4776:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4777:              &Apache::loncommon::end_data_table_header_row().
 4778:              &Apache::loncommon::start_data_table_row().'<td>';
 4779:     my $upload=&mt("Upload Scores");
 4780:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4781:     my $ignore=&mt('Ignore First Line');
 4782:     $symb = &Apache::lonenc::check_encrypt($symb);
 4783:     $result.=<<ENDUPFORM;
 4784: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4785: <input type="hidden" name="symb" value="$symb" />
 4786: <input type="hidden" name="command" value="csvuploadmap" />
 4787: $upfile_select
 4788: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4789: </form>
 4790: ENDUPFORM
 4791:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4792:                            &mt("How do I create a CSV file from a spreadsheet")).
 4793:              '</td>'.
 4794:             &Apache::loncommon::end_data_table_row().
 4795:             &Apache::loncommon::end_data_table();
 4796:     return $result;
 4797: }
 4798: 
 4799: 
 4800: sub csvuploadmap {
 4801:     my ($request,$symb) = @_;
 4802:     if (!$symb) {return '';}
 4803: 
 4804:     my $datatoken;
 4805:     if (!$env{'form.datatoken'}) {
 4806: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4807:     } else {
 4808: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4809:         if ($datatoken ne '') {
 4810: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4811:         }
 4812:     }
 4813:     my @records=&Apache::loncommon::upfile_record_sep();
 4814:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4815:     my ($i,$keyfields);
 4816:     if (@records) {
 4817:         my $fieldserror;
 4818: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4819:         if ($fieldserror) {
 4820:             $request->print(&navmap_errormsg());
 4821:             return;
 4822:         }
 4823: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4824: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4825: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4826: 							  \@fields);
 4827: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4828: 	    chop($keyfields);
 4829: 	} else {
 4830: 	    unshift(@fields,['none','']);
 4831: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4832: 							    \@fields);
 4833:             foreach my $rec (@records) {
 4834:                 my %temp = &Apache::loncommon::record_sep($rec);
 4835:                 if (%temp) {
 4836:                     $keyfields=join(',',sort(keys(%temp)));
 4837:                     last;
 4838:                 }
 4839:             }
 4840: 	}
 4841:     }
 4842:     &csvuploadmap_footer($request,$i,$keyfields);
 4843: 
 4844:     return '';
 4845: }
 4846: 
 4847: sub csvuploadoptions {
 4848:     my ($request,$symb)= @_;
 4849:     my $overwrite=&mt('Overwrite any existing score');
 4850:     $request->print(<<ENDPICK);
 4851: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4852: <input type="hidden" name="command"    value="csvuploadassign" />
 4853: <p>
 4854: <label>
 4855:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4856:    $overwrite
 4857: </label>
 4858: </p>
 4859: ENDPICK
 4860:     my %fields=&get_fields();
 4861:     if (!defined($fields{'domain'})) {
 4862: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4863: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4864:     }
 4865:     foreach my $key (sort(keys(%env))) {
 4866: 	if ($key !~ /^form\.(.*)$/) { next; }
 4867: 	my $cleankey=$1;
 4868: 	if ($cleankey eq 'command') { next; }
 4869: 	$request->print('<input type="hidden" name="'.$cleankey.
 4870: 			'"  value="'.$env{$key}.'" />'."\n");
 4871:     }
 4872:     # FIXME do a check for any duplicated user ids...
 4873:     # FIXME do a check for any invalid user ids?...
 4874:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4875: <hr /></form>'."\n");
 4876:     return '';
 4877: }
 4878: 
 4879: sub get_fields {
 4880:     my %fields;
 4881:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4882:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4883: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4884: 	    if ($env{'form.f'.$i} ne 'none') {
 4885: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4886: 	    }
 4887: 	} else {
 4888: 	    if ($env{'form.f'.$i} ne 'none') {
 4889: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4890: 	    }
 4891: 	}
 4892:     }
 4893:     return %fields;
 4894: }
 4895: 
 4896: sub csvuploadassign {
 4897:     my ($request,$symb) = @_;
 4898:     if (!$symb) {return '';}
 4899:     my $error_msg = '';
 4900:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4901:     if ($datatoken ne '') { 
 4902:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4903:     }
 4904:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4905:     my %fields=&get_fields();
 4906:     my $courseid=$env{'request.course.id'};
 4907:     my ($classlist) = &getclasslist('all',0);
 4908:     my @notallowed;
 4909:     my @skipped;
 4910:     my @warnings;
 4911:     my $countdone=0;
 4912:     foreach my $grade (@gradedata) {
 4913: 	my %entries=&Apache::loncommon::record_sep($grade);
 4914: 	my $domain;
 4915: 	if ($entries{$fields{'domain'}}) {
 4916: 	    $domain=$entries{$fields{'domain'}};
 4917: 	} else {
 4918: 	    $domain=$env{'form.default_domain'};
 4919: 	}
 4920: 	$domain=~s/\s//g;
 4921: 	my $username=$entries{$fields{'username'}};
 4922: 	$username=~s/\s//g;
 4923: 	if (!$username) {
 4924: 	    my $id=$entries{$fields{'ID'}};
 4925: 	    $id=~s/\s//g;
 4926:             if ($id ne '') {
 4927: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4928: 	        $username=$ids{$id};
 4929:             } else {
 4930:                 if ($entries{$fields{'clicker'}}) {
 4931:                     my $clicker = $entries{$fields{'clicker'}};
 4932:                     $clicker=~s/\s//g;
 4933:                     if ($clicker ne '') {
 4934:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4935:                         if ($clickers{$clicker} ne '') {  
 4936:                             my $match = 0;
 4937:                             my @inclass;
 4938:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4939:                                 if (exists($$classlist{"$poss:$domain"})) {
 4940:                                     $username = $poss;
 4941:                                     push(@inclass,$poss);
 4942:                                     $match ++;
 4943:                                     
 4944:                                 }
 4945:                             }
 4946:                             if ($match > 1) {
 4947:                                 undef($username); 
 4948:                                 $request->print('<p class="LC_warning">'.
 4949:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4950:                                                 $clicker,join(', ',@inclass)).'</p>');
 4951:                             }
 4952:                         }
 4953:                     }
 4954:                 }
 4955:             }
 4956: 	}
 4957: 	if (!exists($$classlist{"$username:$domain"})) {
 4958: 	    my $id=$entries{$fields{'ID'}};
 4959: 	    $id=~s/\s//g;
 4960:             my $clicker = $entries{$fields{'clicker'}};
 4961:             $clicker=~s/\s//g;
 4962:             if ($clicker) {
 4963:                 push(@skipped,"$clicker:$domain");
 4964: 	    } elsif ($id) {
 4965: 		push(@skipped,"$id:$domain");
 4966: 	    } else {
 4967: 		push(@skipped,"$username:$domain");
 4968: 	    }
 4969: 	    next;
 4970: 	}
 4971: 	my $usec=$classlist->{"$username:$domain"}[5];
 4972: 	if (!&canmodify($usec)) {
 4973: 	    push(@notallowed,"$username:$domain");
 4974: 	    next;
 4975: 	}
 4976: 	my %points;
 4977: 	my %grades;
 4978: 	foreach my $dest (keys(%fields)) {
 4979: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4980: 		$dest eq 'domain') { next; }
 4981: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4982: 	    if ($dest=~/stores_(.*)_points/) {
 4983: 		my $part=$1;
 4984: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4985: 					      $symb,$domain,$username);
 4986:                 if ($wgt) {
 4987:                     $entries{$fields{$dest}}=~s/\s//g;
 4988:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4989:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4990:                                           : 'correct_by_override';
 4991:                     if ($pcr>1) {
 4992:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4993:                     }
 4994:                     $grades{"resource.$part.awarded"}=$pcr;
 4995:                     $grades{"resource.$part.solved"}=$award;
 4996:                     $points{$part}=1;
 4997:                 } else {
 4998:                     $error_msg = "<br />" .
 4999:                         &mt("Some point values were assigned"
 5000:                             ." for problems with a weight "
 5001:                             ."of zero. These values were "
 5002:                             ."ignored.");
 5003:                 }
 5004: 	    } else {
 5005: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5006: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5007: 		my $store_key=$dest;
 5008: 		$store_key=~s/^stores/resource/;
 5009: 		$store_key=~s/_/\./g;
 5010: 		$grades{$store_key}=$entries{$fields{$dest}};
 5011: 	    }
 5012: 	}
 5013: 	if (! %grades) {
 5014:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5015:         } else {
 5016: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5017: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5018: 					   $env{'request.course.id'},
 5019: 					   $domain,$username);
 5020: 	   if ($result eq 'ok') {
 5021: # Successfully stored
 5022: 	      $request->print('.');
 5023: # Remove from grading queue
 5024:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5025:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5026:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5027:                                              $domain,$username);
 5028:               $countdone++;
 5029:            } else {
 5030: 	      $request->print("<p><span class=\"LC_error\">".
 5031:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5032:                                   "$username:$domain",$result)."</span></p>");
 5033: 	   }
 5034: 	   $request->rflush();
 5035:         }
 5036:     }
 5037:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5038:     if (@warnings) {
 5039:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5040:         $request->print(join(', ',@warnings));
 5041:     }
 5042:     if (@skipped) {
 5043: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5044:         $request->print(join(', ',@skipped));
 5045:     }
 5046:     if (@notallowed) {
 5047: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5048: 	$request->print(join(', ',@notallowed));
 5049:     }
 5050:     $request->print("<br />\n");
 5051:     return $error_msg;
 5052: }
 5053: #------------- end of section for handling csv file upload ---------
 5054: #
 5055: #-------------------------------------------------------------------
 5056: #
 5057: #-------------- Next few routines handle grading by page/sequence
 5058: #
 5059: #--- Select a page/sequence and a student to grade
 5060: sub pickStudentPage {
 5061:     my ($request,$symb) = @_;
 5062: 
 5063:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5064:     &js_escape(\$alertmsg);
 5065:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5066: 
 5067: function checkPickOne(formname) {
 5068:     if (radioSelection(formname.student) == null) {
 5069: 	alert("$alertmsg");
 5070: 	return;
 5071:     }
 5072:     ptr = pullDownSelection(formname.selectpage);
 5073:     formname.page.value = formname["page"+ptr].value;
 5074:     formname.title.value = formname["title"+ptr].value;
 5075:     formname.submit();
 5076: }
 5077: 
 5078: LISTJAVASCRIPT
 5079:     &commonJSfunctions($request);
 5080: 
 5081:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5082:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5083:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5084:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5085: 
 5086:     my $result='<h3><span class="LC_info">&nbsp;'.
 5087: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5088: 
 5089:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5090:     my $map_error;
 5091:     my ($titles,$symbx) = &getSymbMap($map_error);
 5092:     if ($map_error) {
 5093:         $request->print(&navmap_errormsg());
 5094:         return; 
 5095:     }
 5096:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5097: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5098: #    my $type=($curpage =~ /\.(page|sequence)/);
 5099: 
 5100:     # Collection of hidden fields
 5101:     my $ctr=0;
 5102:     foreach (@$titles) {
 5103:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5104:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5105:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5106:         $ctr++;
 5107:     }
 5108:     $result.='<input type="hidden" name="page" />'."\n".
 5109:         '<input type="hidden" name="title" />'."\n";
 5110: 
 5111:     $result.=&build_section_inputs();
 5112:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5113:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5114: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5115: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5116: 
 5117:     # Show grading options
 5118:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5119:     my $select = '<select name="selectpage">'."\n";
 5120:     $ctr=0;
 5121:     foreach (@$titles) {
 5122: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5123: 	$select.='<option value="'.$ctr.'"'.
 5124: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5125: 	    '>'.$showtitle.'</option>'."\n";
 5126: 	$ctr++;
 5127:     }
 5128:     $select.= '</select>';
 5129: 
 5130:     $result.=
 5131:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5132:        .$select
 5133:        .&Apache::lonhtmlcommon::row_closure();
 5134: 
 5135:     $result.=
 5136:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5137:        .'<label><input type="radio" name="vProb" value="no"'
 5138:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5139:        .'<label><input type="radio" name="vProb" value="yes" />'
 5140:            .&mt('yes').'</label>'."\n"
 5141:        .&Apache::lonhtmlcommon::row_closure();
 5142: 
 5143:     $result.=
 5144:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5145:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5146:            .&mt('none').' </label>'."\n"
 5147:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5148:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5149:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5150:            .&mt('all submissions with details').' </label>'
 5151:        .&Apache::lonhtmlcommon::row_closure();
 5152:     
 5153:     $result.=
 5154:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5155:        .'<input type="text" name="CODE" value="" />'
 5156:        .&Apache::lonhtmlcommon::row_closure(1)
 5157:        .&Apache::lonhtmlcommon::end_pick_box();
 5158: 
 5159:     # Show list of students to select for grading
 5160:     $result.='<br /><input type="button" '.
 5161:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5162: 
 5163:     $request->print($result);
 5164: 
 5165:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5166: 	&Apache::loncommon::start_data_table().
 5167: 	&Apache::loncommon::start_data_table_header_row().
 5168: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5169: 	'<th>'.&nameUserString('header').'</th>'.
 5170: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5171: 	'<th>'.&nameUserString('header').'</th>'.
 5172: 	&Apache::loncommon::end_data_table_header_row();
 5173:  
 5174:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5175:     my $ptr = 1;
 5176:     foreach my $student (sort 
 5177: 			 {
 5178: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5179: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5180: 			     }
 5181: 			     return $a cmp $b;
 5182: 			 } (keys(%$fullname))) {
 5183: 	my ($uname,$udom) = split(/:/,$student);
 5184: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5185:                                   : '</td>');
 5186: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5187: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5188: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5189: 	$studentTable.=
 5190: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5191:                          : '');
 5192: 	$ptr++;
 5193:     }
 5194:     if ($ptr%2 == 0) {
 5195: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5196: 	    &Apache::loncommon::end_data_table_row();
 5197:     }
 5198:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5199:     $studentTable.='<input type="button" '.
 5200:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5201: 
 5202:     $request->print($studentTable);
 5203: 
 5204:     return '';
 5205: }
 5206: 
 5207: sub getSymbMap {
 5208:     my ($map_error) = @_;
 5209:     my $navmap = Apache::lonnavmaps::navmap->new();
 5210:     unless (ref($navmap)) {
 5211:         if (ref($map_error)) {
 5212:             $$map_error = 'navmap';
 5213:         }
 5214:         return;
 5215:     }
 5216:     my %symbx = ();
 5217:     my @titles = ();
 5218:     my $minder = 0;
 5219: 
 5220:     # Gather every sequence that has problems.
 5221:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5222: 					       1,0,1);
 5223:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5224: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5225: 	    my $title = $minder.'.'.
 5226: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5227: 	    push(@titles, $title); # minder in case two titles are identical
 5228: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5229: 	    $minder++;
 5230: 	}
 5231:     }
 5232:     return \@titles,\%symbx;
 5233: }
 5234: 
 5235: #
 5236: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5237: sub displayPage {
 5238:     my ($request,$symb) = @_;
 5239:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5240:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5241:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5242:     my $pageTitle = $env{'form.page'};
 5243:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5244:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5245:     my $usec=$classlist->{$env{'form.student'}}[5];
 5246: 
 5247:     #need to make sure we have the correct data for later EXT calls, 
 5248:     #thus invalidate the cache
 5249:     &Apache::lonnet::devalidatecourseresdata(
 5250:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5251:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5252:     &Apache::lonnet::clear_EXT_cache_status();
 5253: 
 5254:     if (!&canview($usec)) {
 5255:         $request->print(
 5256:             '<span class="LC_warning">'.
 5257:             &mt('Unable to view requested student. ([_1])',
 5258:                     $env{'form.student'}).
 5259:             '</span>');
 5260:         return;
 5261:     }
 5262:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5263:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5264: 	'</h3>'."\n";
 5265:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5266:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5267: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5268:     } else {
 5269: 	delete($env{'form.CODE'});
 5270:     }
 5271:     &sub_page_js($request);
 5272:     $request->print($result);
 5273: 
 5274:     my $navmap = Apache::lonnavmaps::navmap->new();
 5275:     unless (ref($navmap)) {
 5276:         $request->print(&navmap_errormsg());
 5277:         return;
 5278:     }
 5279:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5280:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5281:     if (!$map) {
 5282: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5283: 	return; 
 5284:     }
 5285:     my $iterator = $navmap->getIterator($map->map_start(),
 5286: 					$map->map_finish());
 5287: 
 5288:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5289: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5290: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5291: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5292: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5293: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5294: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5295: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5296: 
 5297:     if (defined($env{'form.CODE'})) {
 5298: 	$studentTable.=
 5299: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5300:     }
 5301:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5302: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5303: 
 5304:     $studentTable.='&nbsp;<span class="LC_info">'.
 5305:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5306:         '</span>'."\n".
 5307: 	&Apache::loncommon::start_data_table().
 5308: 	&Apache::loncommon::start_data_table_header_row().
 5309: 	'<th>'.&mt('Prob.').'</th>'.
 5310: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5311: 	&Apache::loncommon::end_data_table_header_row();
 5312: 
 5313:     &Apache::lonxml::clear_problem_counter();
 5314:     my ($depth,$question,$prob) = (1,1,1);
 5315:     $iterator->next(); # skip the first BEGIN_MAP
 5316:     my $curRes = $iterator->next(); # for "current resource"
 5317:     while ($depth > 0) {
 5318:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5319:         if($curRes == $iterator->END_MAP) { $depth--; }
 5320: 
 5321:         if (ref($curRes) && $curRes->is_gradable()) {
 5322: 	    my $parts = $curRes->parts();
 5323:             my $title = $curRes->compTitle();
 5324: 	    my $symbx = $curRes->symb();
 5325:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5326: 	    $studentTable.=
 5327: 		&Apache::loncommon::start_data_table_row().
 5328: 		'<td align="center" valign="top" >'.$prob.
 5329: 		(scalar(@{$parts}) == 1 ? '' 
 5330: 		                        : '<br />('.&mt('[_1]parts',
 5331: 							scalar(@{$parts}).'&nbsp;').')'
 5332: 		 ).
 5333: 		 '</td>';
 5334: 	    $studentTable.='<td valign="top">';
 5335: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5336:             if ($is_tool) {
 5337:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5338:             } else {
 5339: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5340: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5341: 					         undef,'both',\%form);
 5342: 	        } else {
 5343: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5344: 		    $companswer =~ s|<form(.*?)>||g;
 5345: 		    $companswer =~ s|</form>||g;
 5346: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5347: #		        $companswer =~ s/$1/ /ms;
 5348: #		        $request->print('match='.$1."<br />\n");
 5349: #		    }
 5350: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5351: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5352: 		}
 5353: 	    }
 5354: 
 5355: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5356: 
 5357: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5358: 		if ($record{'version'} eq '') {
 5359:                     my $msg = &mt('No recorded submission for this problem.');
 5360:                     if ($is_tool) {
 5361:                         $msg = &mt('No recorded transactions for this external tool');
 5362:                     }
 5363: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5364: 		} else {
 5365: 		    my %responseType = ();
 5366: 		    foreach my $partid (@{$parts}) {
 5367: 			my @responseIds =$curRes->responseIds($partid);
 5368: 			my @responseType =$curRes->responseType($partid);
 5369: 			my %responseIds;
 5370: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5371: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5372: 			}
 5373: 			$responseType{$partid} = \%responseIds;
 5374: 		    }
 5375: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5376: 		}
 5377: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5378: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5379:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5380: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5381: 									$env{'request.course.id'},
 5382: 									'','.submission',undef,
 5383:                                                                         $usec,$identifier);
 5384:  
 5385: 	    }
 5386: 	    if (&canmodify($usec)) {
 5387:             $studentTable.=&gradeBox_start();
 5388: 		foreach my $partid (@{$parts}) {
 5389: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5390: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5391: 		    $question++;
 5392: 		}
 5393:             $studentTable.=&gradeBox_end();
 5394: 		$prob++;
 5395: 	    }
 5396: 	    $studentTable.='</td></tr>';
 5397: 
 5398: 	}
 5399:         $curRes = $iterator->next();
 5400:     }
 5401: 
 5402:     $studentTable.=
 5403:         '</table>'."\n".
 5404:         '<input type="button" value="'.&mt('Save').'" '.
 5405:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5406:         '</form>'."\n";
 5407:     $request->print($studentTable);
 5408: 
 5409:     return '';
 5410: }
 5411: 
 5412: sub displaySubByDates {
 5413:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5414:     my $isCODE=0;
 5415:     my $isTask = ($symb =~/\.task$/);
 5416:     my $is_tool = ($symb =~/\.tool$/);
 5417:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5418:     my $studentTable=&Apache::loncommon::start_data_table().
 5419: 	&Apache::loncommon::start_data_table_header_row().
 5420: 	'<th>'.&mt('Date/Time').'</th>'.
 5421: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5422:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5423: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5424: 	'<th>'.&mt('Status').'</th>'.
 5425: 	&Apache::loncommon::end_data_table_header_row();
 5426:     my ($version);
 5427:     my %mark;
 5428:     my %orders;
 5429:     $mark{'correct_by_student'} = $checkIcon;
 5430:     if (!exists($$record{'1:timestamp'})) {
 5431:         if ($is_tool) {
 5432:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5433:         } else {
 5434:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5435:         }
 5436:     }
 5437: 
 5438:     my $interaction;
 5439:     my $no_increment = 1;
 5440:     my (%lastrndseed,%lasttype);
 5441:     for ($version=1;$version<=$$record{'version'};$version++) {
 5442: 	my $timestamp = 
 5443: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5444: 	if (exists($$record{$version.':resource.0.version'})) {
 5445: 	    $interaction = $$record{$version.':resource.0.version'};
 5446: 	}
 5447:         if ($isTask && $env{'form.previousversion'}) {
 5448:             next unless ($interaction == $env{'form.previousversion'});
 5449:         }
 5450: 	my $where = ($isTask ? "$version:resource.$interaction"
 5451: 		             : "$version:resource");
 5452: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5453: 	    '<td>'.$timestamp.'</td>';
 5454: 	if ($isCODE) {
 5455: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5456: 	}
 5457:         if ($isTask) {
 5458:             $studentTable.='<td>'.$interaction.'</td>';
 5459:         }
 5460: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5461: 	my @displaySub = ();
 5462: 	foreach my $partid (@{$parts}) {
 5463:             my ($hidden,$type);
 5464:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5465:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5466:                 $hidden = 1;
 5467:             }
 5468:             my @matchKey;
 5469:             if ($isTask) {
 5470:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5471:             } elsif ($is_tool) {
 5472:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5473:             } else {
 5474:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5475:             }
 5476: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5477: 	    my $display_part=&get_display_part($partid,$symb);
 5478: 	    foreach my $matchKey (@matchKey) {
 5479: 		if (exists($$record{$version.':'.$matchKey}) &&
 5480: 		    $$record{$version.':'.$matchKey} ne '') {
 5481:                     if ($is_tool) {
 5482:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5483:                     } else {
 5484: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5485: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5486:                         $displaySub[0].='<span class="LC_nobreak">';
 5487:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5488:                                        .' <span class="LC_internal_info">'
 5489:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5490:                                        .'</span>'
 5491:                                        .' <b>';
 5492:                         if ($hidden) {
 5493:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5494:                         } else {
 5495:                             my ($trial,$rndseed,$newvariation);
 5496:                             if ($type eq 'randomizetry') {
 5497:                                 $trial = $$record{"$where.$partid.tries"};
 5498:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5499:                             }
 5500: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5501: 			        $displaySub[0].=&mt('Trial not counted');
 5502: 		            } else {
 5503: 			        $displaySub[0].=&mt('Trial: [_1]',
 5504: 					        $$record{"$where.$partid.tries"});
 5505:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5506:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5507:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5508:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5509:                                     }
 5510:                                 }
 5511:                                 $lastrndseed{$partid} = $rndseed;
 5512:                                 $lasttype{$partid} = $type;
 5513: 		            }
 5514: 		            my $responseType=($isTask ? 'Task'
 5515:                                               : $responseType->{$partid}->{$responseId});
 5516: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5517: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5518: 			        $orders{$partid}->{$responseId}=
 5519: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5520:                                                $no_increment,$type,$trial,$rndseed);
 5521: 		            }
 5522: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5523: 		            $displaySub[0].='&nbsp; '.
 5524: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5525:                         }
 5526:                     }
 5527: 		}
 5528: 	    }
 5529: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5530: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5531: 				    $$record{"$where.$partid.checkedin"},
 5532: 				    $$record{"$where.$partid.checkedin.slot"}).
 5533: 					'<br />';
 5534: 	    }
 5535: 	    if (exists $$record{"$where.$partid.award"}) {
 5536: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5537: 		    lc($$record{"$where.$partid.award"}).' '.
 5538: 		    $mark{$$record{"$where.$partid.solved"}}.
 5539: 		    '<br />';
 5540: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5541: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5542: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5543: 		}
 5544: 	    }
 5545: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5546: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5547: 		unless ($is_tool) {
 5548: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5549: 		}
 5550: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5551: 		$displaySub[2].=
 5552: 		    $$record{"$version:resource.$partid.regrader"};
 5553:                 unless ($is_tool) {
 5554: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5555:                 }
 5556: 	    }
 5557: 	}
 5558: 	# needed because old essay regrader has not parts info
 5559: 	if (exists $$record{"$version:resource.regrader"}) {
 5560: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5561: 	}
 5562: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5563: 	if ($displaySub[2]) {
 5564: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5565: 	}
 5566: 	$studentTable.='&nbsp;</td>'.
 5567: 	    &Apache::loncommon::end_data_table_row();
 5568:     }
 5569:     $studentTable.=&Apache::loncommon::end_data_table();
 5570:     return $studentTable;
 5571: }
 5572: 
 5573: sub updateGradeByPage {
 5574:     my ($request,$symb) = @_;
 5575: 
 5576:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5577:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5578:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5579:     my $pageTitle = $env{'form.page'};
 5580:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5581:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5582:     my $usec=$classlist->{$env{'form.student'}}[5];
 5583:     if (!&canmodify($usec)) {
 5584: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5585: 	return;
 5586:     }
 5587:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5588:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5589: 	'</h3>'."\n";
 5590: 
 5591:     $request->print($result);
 5592: 
 5593: 
 5594:     my $navmap = Apache::lonnavmaps::navmap->new();
 5595:     unless (ref($navmap)) {
 5596:         $request->print(&navmap_errormsg());
 5597:         return;
 5598:     }
 5599:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5600:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5601:     if (!$map) {
 5602: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5603: 	return; 
 5604:     }
 5605:     my $iterator = $navmap->getIterator($map->map_start(),
 5606: 					$map->map_finish());
 5607: 
 5608:     my $studentTable=
 5609: 	&Apache::loncommon::start_data_table().
 5610: 	&Apache::loncommon::start_data_table_header_row().
 5611: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5612: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5613: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5614: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5615: 	&Apache::loncommon::end_data_table_header_row();
 5616: 
 5617:     $iterator->next(); # skip the first BEGIN_MAP
 5618:     my $curRes = $iterator->next(); # for "current resource"
 5619:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5620:     while ($depth > 0) {
 5621:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5622:         if($curRes == $iterator->END_MAP) { $depth--; }
 5623: 
 5624:         if (ref($curRes) && $curRes->is_problem()) {
 5625: 	    my $parts = $curRes->parts();
 5626:             my $title = $curRes->compTitle();
 5627: 	    my $symbx = $curRes->symb();
 5628: 	    $studentTable.=
 5629: 		&Apache::loncommon::start_data_table_row().
 5630: 		'<td align="center" valign="top" >'.$prob.
 5631: 		(scalar(@{$parts}) == 1 ? '' 
 5632:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5633: 		.')').'</td>';
 5634: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5635: 
 5636: 	    my %newrecord=();
 5637: 	    my @displayPts=();
 5638:             my %aggregate = ();
 5639:             my $aggregateflag = 0;
 5640:             if ($env{'form.HIDE'.$prob}) {
 5641:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5642:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5643:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5644:                 $hideflag += $numchgs;
 5645:             }
 5646: 	    foreach my $partid (@{$parts}) {
 5647: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5648: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5649: 
 5650: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5651: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5652: 		my $partial = $newpts/$wgt;
 5653: 		my $score;
 5654: 		if ($partial > 0) {
 5655: 		    $score = 'correct_by_override';
 5656: 		} elsif ($newpts ne '') { #empty is taken as 0
 5657: 		    $score = 'incorrect_by_override';
 5658: 		}
 5659: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5660: 		if ($dropMenu eq 'excused') {
 5661: 		    $partial = '';
 5662: 		    $score = 'excused';
 5663: 		} elsif ($dropMenu eq 'reset status'
 5664: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5665: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5666: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5667: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5668: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5669: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5670: 		    $changeflag++;
 5671: 		    $newpts = '';
 5672:                     
 5673:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5674:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5675:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5676:                     if ($aggtries > 0) {
 5677:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5678:                         $aggregateflag = 1;
 5679:                     }
 5680: 		}
 5681: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5682: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5683: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5684: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5685: 		    '&nbsp;<br />';
 5686: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5687: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5688: 		    '&nbsp;<br />';
 5689: 		$question++;
 5690: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5691: 
 5692: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5693: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5694: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5695: 		    if (scalar(keys(%newrecord)) > 0);
 5696: 
 5697: 		$changeflag++;
 5698: 	    }
 5699: 	    if (scalar(keys(%newrecord)) > 0) {
 5700: 		my %record = 
 5701: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5702: 					     $udom,$uname);
 5703: 
 5704: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5705: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5706: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5707: 		    $newrecord{'resource.CODE'} = '';
 5708: 		}
 5709: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5710: 					$udom,$uname);
 5711: 		%record = &Apache::lonnet::restore($symbx,
 5712: 						   $env{'request.course.id'},
 5713: 						   $udom,$uname);
 5714: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5715: 					     $cdom,$cnum,$udom,$uname);
 5716: 	    }
 5717: 	    
 5718:             if ($aggregateflag) {
 5719:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5720:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5721:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5722:             }
 5723: 
 5724: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5725: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5726: 		&Apache::loncommon::end_data_table_row();
 5727: 
 5728: 	    $prob++;
 5729: 	}
 5730:         $curRes = $iterator->next();
 5731:     }
 5732: 
 5733:     $studentTable.=&Apache::loncommon::end_data_table();
 5734:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5735: 		  &mt('The scores were changed for [quant,_1,problem].',
 5736: 		  $changeflag).'<br />');
 5737:     my $hidemsg=($hideflag == 0 ? '' :
 5738:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5739:                      $hideflag).'<br />');
 5740:     $request->print($hidemsg.$grademsg.$studentTable);
 5741: 
 5742:     return '';
 5743: }
 5744: 
 5745: #-------- end of section for handling grading by page/sequence ---------
 5746: #
 5747: #-------------------------------------------------------------------
 5748: 
 5749: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5750: #
 5751: #------ start of section for handling grading by page/sequence ---------
 5752: 
 5753: =pod
 5754: 
 5755: =head1 Bubble sheet grading routines
 5756: 
 5757:   For this documentation:
 5758: 
 5759:    'scanline' refers to the full line of characters
 5760:    from the file that we are parsing that represents one entire sheet
 5761: 
 5762:    'bubble line' refers to the data
 5763:    representing the line of bubbles that are on the physical bubblesheet
 5764: 
 5765: 
 5766: The overall process is that a scanned in bubblesheet data is uploaded
 5767: into a course. When a user wants to grade, they select a
 5768: sequence/folder of resources, a file of bubblesheet info, and pick
 5769: one of the predefined configurations for what each scanline looks
 5770: like.
 5771: 
 5772: Next each scanline is checked for any errors of either 'missing
 5773: bubbles' (it's an error because it may have been mis-scanned
 5774: because too light bubbling), 'double bubble' (each bubble line should
 5775: have no more than one letter picked), invalid or duplicated CODE,
 5776: invalid student/employee ID
 5777: 
 5778: If the CODE option is used that determines the randomization of the
 5779: homework problems, either way the student/employee ID is looked up into a
 5780: username:domain.
 5781: 
 5782: During the validation phase the instructor can choose to skip scanlines. 
 5783: 
 5784: After the validation phase, there are now 3 bubblesheet files
 5785: 
 5786:   scantron_original_filename (unmodified original file)
 5787:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5788:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5789: 
 5790: Also there is a separate hash nohist_scantrondata that contains extra
 5791: correction information that isn't representable in the bubblesheet
 5792: file (see &scantron_getfile() for more information)
 5793: 
 5794: After all scanlines are either valid, marked as valid or skipped, then
 5795: foreach line foreach problem in the picked sequence, an ssi request is
 5796: made that simulates a user submitting their selected letter(s) against
 5797: the homework problem.
 5798: 
 5799: =over 4
 5800: 
 5801: 
 5802: 
 5803: =item defaultFormData
 5804: 
 5805:   Returns html hidden inputs used to hold context/default values.
 5806: 
 5807:  Arguments:
 5808:   $symb - $symb of the current resource 
 5809: 
 5810: =cut
 5811: 
 5812: sub defaultFormData {
 5813:     my ($symb)=@_;
 5814:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5815: }
 5816: 
 5817: 
 5818: =pod 
 5819: 
 5820: =item getSequenceDropDown
 5821: 
 5822:    Return html dropdown of possible sequences to grade
 5823:  
 5824:  Arguments:
 5825:    $symb - $symb of the current resource
 5826:    $map_error - ref to scalar which will container error if
 5827:                 $navmap object is unavailable in &getSymbMap().
 5828: 
 5829: =cut
 5830: 
 5831: sub getSequenceDropDown {
 5832:     my ($symb,$map_error)=@_;
 5833:     my $result='<select name="selectpage">'."\n";
 5834:     my ($titles,$symbx) = &getSymbMap($map_error);
 5835:     if (ref($map_error)) {
 5836:         return if ($$map_error);
 5837:     }
 5838:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5839:     my $ctr=0;
 5840:     foreach (@$titles) {
 5841: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5842: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5843: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5844: 	    '>'.$showtitle.'</option>'."\n";
 5845: 	$ctr++;
 5846:     }
 5847:     $result.= '</select>';
 5848:     return $result;
 5849: }
 5850: 
 5851: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5852:                                    # key is zero-based index - 0, 1, 2 ...
 5853: 
 5854: my %first_bubble_line;             # First bubble line no. for each bubble.
 5855: 
 5856: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5857:                                    # matchresponse or rankresponse, where 
 5858:                                    # an individual response can have multiple 
 5859:                                    # lines
 5860: 
 5861: my %responsetype_per_response;     # responsetype for each response
 5862: 
 5863: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5864:                                    # numbered response. Needed when randomorder
 5865:                                    # or randompick are in use. Key is ID, value 
 5866:                                    # is response number.
 5867: 
 5868: # Save and restore the bubble lines array to the form env.
 5869: 
 5870: 
 5871: sub save_bubble_lines {
 5872:     foreach my $line (keys(%bubble_lines_per_response)) {
 5873: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5874: 	$env{"form.scantron.first_bubble_line.$line"} =
 5875: 	    $first_bubble_line{$line};
 5876:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5877:             $subdivided_bubble_lines{$line};
 5878:         $env{"form.scantron.responsetype.$line"} =
 5879:             $responsetype_per_response{$line};
 5880:     }
 5881:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5882:         my $line = $masterseq_id_responsenum{$resid};
 5883:         $env{"form.scantron.residpart.$line"} = $resid;
 5884:     }
 5885: }
 5886: 
 5887: 
 5888: sub restore_bubble_lines {
 5889:     my $line = 0;
 5890:     %bubble_lines_per_response = ();
 5891:     %masterseq_id_responsenum = ();
 5892:     while ($env{"form.scantron.bubblelines.$line"}) {
 5893: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5894: 	$bubble_lines_per_response{$line} = $value;
 5895: 	$first_bubble_line{$line}  =
 5896: 	    $env{"form.scantron.first_bubble_line.$line"};
 5897:         $subdivided_bubble_lines{$line} =
 5898:             $env{"form.scantron.sub_bubblelines.$line"};
 5899:         $responsetype_per_response{$line} =
 5900:             $env{"form.scantron.responsetype.$line"};
 5901:         my $id = $env{"form.scantron.residpart.$line"};
 5902:         $masterseq_id_responsenum{$id} = $line;
 5903: 	$line++;
 5904:     }
 5905: }
 5906: 
 5907: =pod 
 5908: 
 5909: =item scantron_filenames
 5910: 
 5911:    Returns a list of the scantron files in the current course 
 5912: 
 5913: =cut
 5914: 
 5915: sub scantron_filenames {
 5916:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5917:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5918:     my $getpropath = 1;
 5919:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5920:                                                         $cname,$getpropath);
 5921:     my @possiblenames;
 5922:     if (ref($dirlist) eq 'ARRAY') {
 5923:         foreach my $filename (sort(@{$dirlist})) {
 5924: 	    ($filename)=split(/&/,$filename);
 5925: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5926: 	    $filename=~s/^scantron_orig_//;
 5927: 	    push(@possiblenames,$filename);
 5928:         }
 5929:     }
 5930:     return @possiblenames;
 5931: }
 5932: 
 5933: =pod 
 5934: 
 5935: =item scantron_uploads
 5936: 
 5937:    Returns  html drop-down list of scantron files in current course.
 5938: 
 5939:  Arguments:
 5940:    $file2grade - filename to set as selected in the dropdown
 5941: 
 5942: =cut
 5943: 
 5944: sub scantron_uploads {
 5945:     my ($file2grade) = @_;
 5946:     my $result=	'<select name="scantron_selectfile">';
 5947:     $result.="<option></option>";
 5948:     foreach my $filename (sort(&scantron_filenames())) {
 5949: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5950:     }
 5951:     $result.="</select>";
 5952:     return $result;
 5953: }
 5954: 
 5955: =pod 
 5956: 
 5957: =item scantron_scantab
 5958: 
 5959:   Returns html drop down of the scantron formats in the scantronformat.tab
 5960:   file.
 5961: 
 5962: =cut
 5963: 
 5964: sub scantron_scantab {
 5965:     my $result='<select name="scantron_format">'."\n";
 5966:     $result.='<option></option>'."\n";
 5967:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5968:     if (@lines > 0) {
 5969:         foreach my $line (@lines) {
 5970:             next if (($line =~ /^\#/) || ($line eq ''));
 5971: 	    my ($name,$descrip)=split(/:/,$line);
 5972: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5973:         }
 5974:     }
 5975:     $result.='</select>'."\n";
 5976:     return $result;
 5977: }
 5978: 
 5979: =pod 
 5980: 
 5981: =item scantron_CODElist
 5982: 
 5983:   Returns html drop down of the saved CODE lists from current course,
 5984:   generated from earlier printings.
 5985: 
 5986: =cut
 5987: 
 5988: sub scantron_CODElist {
 5989:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5990:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5991:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5992:     my $namechoice='<option></option>';
 5993:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5994: 	if ($name =~ /^error: 2 /) { next; }
 5995: 	if ($name =~ /^type\0/) { next; }
 5996: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5997:     }
 5998:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5999:     return $namechoice;
 6000: }
 6001: 
 6002: =pod 
 6003: 
 6004: =item scantron_CODEunique
 6005: 
 6006:   Returns the html for "Each CODE to be used once" radio.
 6007: 
 6008: =cut
 6009: 
 6010: sub scantron_CODEunique {
 6011:     my $result='<span class="LC_nobreak">
 6012:                  <label><input type="radio" name="scantron_CODEunique"
 6013:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6014:                 </span>
 6015:                 <span class="LC_nobreak">
 6016:                  <label><input type="radio" name="scantron_CODEunique"
 6017:                         value="no" />'.&mt('No').' </label>
 6018:                 </span>';
 6019:     return $result;
 6020: }
 6021: 
 6022: =pod 
 6023: 
 6024: =item scantron_selectphase
 6025: 
 6026:   Generates the initial screen to start the bubblesheet process.
 6027:   Allows for - starting a grading run.
 6028:              - downloading existing scan data (original, corrected
 6029:                                                 or skipped info)
 6030: 
 6031:              - uploading new scan data
 6032: 
 6033:  Arguments:
 6034:   $r          - The Apache request object
 6035:   $file2grade - name of the file that contain the scanned data to score
 6036: 
 6037: =cut
 6038: 
 6039: sub scantron_selectphase {
 6040:     my ($r,$file2grade,$symb) = @_;
 6041:     if (!$symb) {return '';}
 6042:     my $map_error;
 6043:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6044:     if ($map_error) {
 6045:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6046:         return;
 6047:     }
 6048:     my $default_form_data=&defaultFormData($symb);
 6049:     my $file_selector=&scantron_uploads($file2grade);
 6050:     my $format_selector=&scantron_scantab();
 6051:     my $CODE_selector=&scantron_CODElist();
 6052:     my $CODE_unique=&scantron_CODEunique();
 6053:     my $result;
 6054: 
 6055:     $ssi_error = 0;
 6056: 
 6057:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6058: 
 6059: 	# Chunk of form to prompt for a scantron file upload.
 6060: 
 6061:         $r->print('
 6062:     <br />');
 6063:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6064:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6065:     my $csec= $env{'request.course.sec'};
 6066:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6067:     &js_escape(\$alertmsg);
 6068:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6069:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6070:     function checkUpload(formname) {
 6071: 	if (formname.upfile.value == "") {
 6072: 	    alert("'.$alertmsg.'");
 6073: 	    return false;
 6074: 	}
 6075: 	formname.submit();
 6076:     }'."\n".$formatjs));
 6077:     $r->print('
 6078:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6079:                 '.$default_form_data.'
 6080:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6081:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6082:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6083:                 <input name="command" value="scantronupload_save" type="hidden" />
 6084:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6085:               '.&Apache::loncommon::start_data_table_header_row().'
 6086:                 <th>
 6087:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6088:                 </th>
 6089:               '.&Apache::loncommon::end_data_table_header_row().'
 6090:               '.&Apache::loncommon::start_data_table_row().'
 6091:             <td>
 6092:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6093:     if ($formatoptions) {
 6094:         $r->print('</td>
 6095:                  '.&Apache::loncommon::end_data_table_row().'
 6096:                  '.&Apache::loncommon::start_data_table_row().'
 6097:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6098:                  </td>
 6099:                  '.&Apache::loncommon::end_data_table_row().'
 6100:                  '.&Apache::loncommon::start_data_table_row().'
 6101:                  <td>'
 6102:         );
 6103:     } else {
 6104:         $r->print(' <br />');
 6105:     }
 6106:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6107:               </td>
 6108:              '.&Apache::loncommon::end_data_table_row().'
 6109:              '.&Apache::loncommon::end_data_table().'
 6110:              </form>'
 6111:     );
 6112: 
 6113:     }
 6114: 
 6115:     # Chunk of form to prompt for a file to grade and how:
 6116: 
 6117:     $result.= '
 6118:     <br />
 6119:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6120:     <input type="hidden" name="command" value="scantron_warning" />
 6121:     '.$default_form_data.'
 6122:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6123:        '.&Apache::loncommon::start_data_table_header_row().'
 6124:             <th colspan="2">
 6125:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6126:             </th>
 6127:        '.&Apache::loncommon::end_data_table_header_row().'
 6128:        '.&Apache::loncommon::start_data_table_row().'
 6129:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6130:        '.&Apache::loncommon::end_data_table_row().'
 6131:        '.&Apache::loncommon::start_data_table_row().'
 6132:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6133:        '.&Apache::loncommon::end_data_table_row().'
 6134:        '.&Apache::loncommon::start_data_table_row().'
 6135:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6136:        '.&Apache::loncommon::end_data_table_row().'
 6137:        '.&Apache::loncommon::start_data_table_row().'
 6138:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6139:        '.&Apache::loncommon::end_data_table_row().'
 6140:        '.&Apache::loncommon::start_data_table_row().'
 6141:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6142:        '.&Apache::loncommon::end_data_table_row().'
 6143:        '.&Apache::loncommon::start_data_table_row().'
 6144: 	    <td> '.&mt('Options:').' </td>
 6145:             <td>
 6146: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6147:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6148:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6149: 	    </td>
 6150:        '.&Apache::loncommon::end_data_table_row().'
 6151:        '.&Apache::loncommon::start_data_table_row().'
 6152:             <td colspan="2">
 6153:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6154:             </td>
 6155:        '.&Apache::loncommon::end_data_table_row().'
 6156:     '.&Apache::loncommon::end_data_table().'
 6157:     </form>
 6158: ';
 6159:    
 6160:     $r->print($result);
 6161: 
 6162:     # Chunk of the form that prompts to view a scoring office file,
 6163:     # corrected file, skipped records in a file.
 6164: 
 6165:     $r->print('
 6166:    <br />
 6167:    <form action="/adm/grades" name="scantron_download">
 6168:      '.$default_form_data.'
 6169:      <input type="hidden" name="command" value="scantron_download" />
 6170:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6171:        '.&Apache::loncommon::start_data_table_header_row().'
 6172:               <th>
 6173:                 &nbsp;'.&mt('Download a scoring office file').'
 6174:               </th>
 6175:        '.&Apache::loncommon::end_data_table_header_row().'
 6176:        '.&Apache::loncommon::start_data_table_row().'
 6177:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6178:                 <br />
 6179:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6180:        '.&Apache::loncommon::end_data_table_row().'
 6181:      '.&Apache::loncommon::end_data_table().'
 6182:    </form>
 6183:    <br />
 6184: ');
 6185: 
 6186:     &Apache::lonpickcode::code_list($r,2);
 6187: 
 6188:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6189:              $default_form_data."\n".
 6190:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6191:              &Apache::loncommon::start_data_table_header_row()."\n".
 6192:              '<th colspan="2">
 6193:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6194:              '</th>'."\n".
 6195:               &Apache::loncommon::end_data_table_header_row()."\n".
 6196:               &Apache::loncommon::start_data_table_row()."\n".
 6197:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6198:               '<td> '.$sequence_selector.' </td>'.
 6199:               &Apache::loncommon::end_data_table_row()."\n".
 6200:               &Apache::loncommon::start_data_table_row()."\n".
 6201:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6202:               '<td> '.$file_selector.' </td>'."\n".
 6203:               &Apache::loncommon::end_data_table_row()."\n".
 6204:               &Apache::loncommon::start_data_table_row()."\n".
 6205:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6206:               '<td> '.$format_selector.' </td>'."\n".
 6207:               &Apache::loncommon::end_data_table_row()."\n".
 6208:               &Apache::loncommon::start_data_table_row()."\n".
 6209:               '<td> '.&mt('Options').' </td>'."\n".
 6210:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6211:               &Apache::loncommon::end_data_table_row()."\n".
 6212:               &Apache::loncommon::start_data_table_row()."\n".
 6213:               '<td colspan="2">'."\n".
 6214:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6215:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6216:               '</td>'."\n".
 6217:               &Apache::loncommon::end_data_table_row()."\n".
 6218:               &Apache::loncommon::end_data_table()."\n".
 6219:               '</form><br />');
 6220:     return;
 6221: }
 6222: 
 6223: =pod 
 6224: 
 6225: =item username_to_idmap
 6226: 
 6227:     creates a hash keyed by student/employee ID with values of the corresponding
 6228:     student username:domain. If a single ID occurs for more than one student,
 6229:     the status of the student is checked, and if Active, the value in the hash
 6230:     will be set to the Active student.
 6231: 
 6232:   Arguments:
 6233: 
 6234:     $classlist - reference to the class list hash. This is a hash
 6235:                  keyed by student name:domain  whose elements are references
 6236:                  to arrays containing various chunks of information
 6237:                  about the student. (See loncoursedata for more info).
 6238: 
 6239:   Returns
 6240:     %idmap - the constructed hash
 6241: 
 6242: =cut
 6243: 
 6244: sub username_to_idmap {
 6245:     my ($classlist)= @_;
 6246:     my %idmap;
 6247:     foreach my $student (keys(%$classlist)) {
 6248:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6249:         unless ($id eq '') {
 6250:             if (!exists($idmap{$id})) {
 6251:                 $idmap{$id} = $student;
 6252:             } else {
 6253:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6254:                 if ($status eq 'Active') {
 6255:                     $idmap{$id} = $student;
 6256:                 }
 6257:             }
 6258:         }
 6259:     }
 6260:     return %idmap;
 6261: }
 6262: 
 6263: =pod
 6264: 
 6265: =item scantron_fixup_scanline
 6266: 
 6267:    Process a requested correction to a scanline.
 6268: 
 6269:   Arguments:
 6270:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6271:     $scan_data         - hash of correction information 
 6272:                           (see &scantron_getfile())
 6273:     $line              - existing scanline
 6274:     $whichline         - line number of the passed in scanline
 6275:     $field             - type of change to process 
 6276:                          (either 
 6277:                           'ID'     -> correct the student/employee ID
 6278:                           'CODE'   -> correct the CODE
 6279:                           'answer' -> fixup the submitted answers)
 6280:     
 6281:    $args               - hash of additional info,
 6282:                           - 'ID' 
 6283:                                'newid' -> studentID to use in replacement
 6284:                                           of existing one
 6285:                           - 'CODE' 
 6286:                                'CODE_ignore_dup' - set to true if duplicates
 6287:                                                    should be ignored.
 6288: 	                       'CODE' - is new code or 'use_unfound'
 6289:                                         if the existing unfound code should
 6290:                                         be used as is
 6291:                           - 'answer'
 6292:                                'response' - new answer or 'none' if blank
 6293:                                'question' - the bubble line to change
 6294:                                'questionnum' - the question identifier,
 6295:                                                may include subquestion. 
 6296: 
 6297:   Returns:
 6298:     $line - the modified scanline
 6299: 
 6300:   Side effects: 
 6301:     $scan_data - may be updated
 6302: 
 6303: =cut
 6304: 
 6305: 
 6306: sub scantron_fixup_scanline {
 6307:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6308:     if ($field eq 'ID') {
 6309: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6310: 	    return ($line,1,'New value too large');
 6311: 	}
 6312: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6313: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6314: 				     $args->{'newid'});
 6315: 	}
 6316: 	substr($line,$$scantron_config{'IDstart'}-1,
 6317: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6318: 	if ($args->{'newid'}=~/^\s*$/) {
 6319: 	    &scan_data($scan_data,"$whichline.user",
 6320: 		       $args->{'username'}.':'.$args->{'domain'});
 6321: 	}
 6322:     } elsif ($field eq 'CODE') {
 6323: 	if ($args->{'CODE_ignore_dup'}) {
 6324: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6325: 	}
 6326: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6327: 	if ($args->{'CODE'} ne 'use_unfound') {
 6328: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6329: 		return ($line,1,'New CODE value too large');
 6330: 	    }
 6331: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6332: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6333: 	    }
 6334: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6335: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6336: 	}
 6337:     } elsif ($field eq 'answer') {
 6338: 	my $length=$scantron_config->{'Qlength'};
 6339: 	my $off=$scantron_config->{'Qoff'};
 6340: 	my $on=$scantron_config->{'Qon'};
 6341: 	my $answer=${off}x$length;
 6342: 	if ($args->{'response'} eq 'none') {
 6343: 	    &scan_data($scan_data,
 6344: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6345: 	} else {
 6346: 	    if ($on eq 'letter') {
 6347: 		my @alphabet=('A'..'Z');
 6348: 		$answer=$alphabet[$args->{'response'}];
 6349: 	    } elsif ($on eq 'number') {
 6350: 		$answer=$args->{'response'}+1;
 6351: 		if ($answer == 10) { $answer = '0'; }
 6352: 	    } else {
 6353: 		substr($answer,$args->{'response'},1)=$on;
 6354: 	    }
 6355: 	    &scan_data($scan_data,
 6356: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6357: 	}
 6358: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6359: 	substr($line,$where-1,$length)=$answer;
 6360:     }
 6361:     return $line;
 6362: }
 6363: 
 6364: =pod
 6365: 
 6366: =item scan_data
 6367: 
 6368:     Edit or look up  an item in the scan_data hash.
 6369: 
 6370:   Arguments:
 6371:     $scan_data  - The hash (see scantron_getfile)
 6372:     $key        - shorthand of the key to edit (actual key is
 6373:                   scantronfilename_key).
 6374:     $data        - New value of the hash entry.
 6375:     $delete      - If true, the entry is removed from the hash.
 6376: 
 6377:   Returns:
 6378:     The new value of the hash table field (undefined if deleted).
 6379: 
 6380: =cut
 6381: 
 6382: 
 6383: sub scan_data {
 6384:     my ($scan_data,$key,$value,$delete)=@_;
 6385:     my $filename=$env{'form.scantron_selectfile'};
 6386:     if (defined($value)) {
 6387: 	$scan_data->{$filename.'_'.$key} = $value;
 6388:     }
 6389:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6390:     return $scan_data->{$filename.'_'.$key};
 6391: }
 6392: 
 6393: # ----- These first few routines are general use routines.----
 6394: 
 6395: # Return the number of occurences of a pattern in a string.
 6396: 
 6397: sub occurence_count {
 6398:     my ($string, $pattern) = @_;
 6399: 
 6400:     my @matches = ($string =~ /$pattern/g);
 6401: 
 6402:     return scalar(@matches);
 6403: }
 6404: 
 6405: 
 6406: # Take a string known to have digits and convert all the
 6407: # digits into letters in the range J,A..I.
 6408: 
 6409: sub digits_to_letters {
 6410:     my ($input) = @_;
 6411: 
 6412:     my @alphabet = ('J', 'A'..'I');
 6413: 
 6414:     my @input    = split(//, $input);
 6415:     my $output ='';
 6416:     for (my $i = 0; $i < scalar(@input); $i++) {
 6417: 	if ($input[$i] =~ /\d/) {
 6418: 	    $output .= $alphabet[$input[$i]];
 6419: 	} else {
 6420: 	    $output .= $input[$i];
 6421: 	}
 6422:     }
 6423:     return $output;
 6424: }
 6425: 
 6426: =pod 
 6427: 
 6428: =item scantron_parse_scanline
 6429: 
 6430:   Decodes a scanline from the selected bubblesheet file
 6431: 
 6432:  Arguments:
 6433:     line             - The text of the bubblesheet file line to process
 6434:     whichline        - Line number
 6435:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6436:     scan_data        - Hash of extra information about the scanline
 6437:                        (see scantron_getfile for more information)
 6438:     just_header      - True if should not process question answers but only
 6439:                        the stuff to the left of the answers.
 6440:     randomorder      - True if randomorder in use
 6441:     randompick       - True if randompick in use
 6442:     sequence         - Exam folder URL
 6443:     master_seq       - Ref to array containing symbs in exam folder
 6444:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6445:                        (corresponding values are resource objects)
 6446:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6447:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6448:                        are refs to an array of resource objects, ordered
 6449:                        according to order used for CODE, when randomorder
 6450:                        and or randompick are in use.
 6451:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6452:                        for current line to question number used for same question
 6453:                         in "Master Sequence" (as seen by Course Coordinator).
 6454:     startline        - Ref to hash where key is question number (0 is first)
 6455:                        and value is number of first bubble line for current 
 6456:                        student or code-based randompick and/or randomorder.
 6457:     totalref         - Ref of scalar used to score total number of bubble
 6458:                        lines needed for responses in a scan line (used when
 6459:                        randompick in use. 
 6460:     
 6461:  Returns:
 6462:    Hash containing the result of parsing the scanline
 6463: 
 6464:    Keys are all proceeded by the string 'scantron.'
 6465: 
 6466:        CODE    - the CODE in use for this scanline
 6467:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6468:                  by the operator
 6469:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6470:                             CODEs were selected, but the usage has been
 6471:                             forced by the operator
 6472:        ID  - student/employee ID
 6473:        PaperID - if used, the ID number printed on the sheet when the 
 6474:                  paper was scanned
 6475:        FirstName - first name from the sheet
 6476:        LastName  - last name from the sheet
 6477: 
 6478:      if just_header was not true these key may also exist
 6479: 
 6480:        missingerror - a list of bubble ranges that are considered to be answers
 6481:                       to a single question that don't have any bubbles filled in.
 6482:                       Of the form questionnumber:firstbubblenumber:count.
 6483:        doubleerror  - a list of bubble ranges that are considered to be answers
 6484:                       to a single question that have more than one bubble filled in.
 6485:                       Of the form questionnumber::firstbubblenumber:count
 6486:    
 6487:                 In the above, count is the number of bubble responses in the
 6488:                 input line needed to represent the possible answers to the question.
 6489:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6490:                 per line would have count = 2.
 6491: 
 6492:        maxquest     - the number of the last bubble line that was parsed
 6493: 
 6494:        (<number> starts at 1)
 6495:        <number>.answer - zero or more letters representing the selected
 6496:                          letters from the scanline for the bubble line 
 6497:                          <number>.
 6498:                          if blank there was either no bubble or there where
 6499:                          multiple bubbles, (consult the keys missingerror and
 6500:                          doubleerror if this is an error condition)
 6501: 
 6502: =cut
 6503: 
 6504: sub scantron_parse_scanline {
 6505:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6506:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6507:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6508: 
 6509:     my %record;
 6510:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6511:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6512: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6513: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6514: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6515: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6516: 	    $record{'scantron.CODE'}=substr($data,
 6517: 					    $$scantron_config{'CODEstart'}-1,
 6518: 					    $$scantron_config{'CODElength'});
 6519: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6520: 		$record{'scantron.useCODE'}=1;
 6521: 	    }
 6522: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6523: 		$record{'scantron.CODE_ignore_dup'}=1;
 6524: 	    }
 6525: 	} else {
 6526: 	    #FIXME interpret first N questions
 6527: 	}
 6528:     }
 6529:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6530: 				  $$scantron_config{'IDlength'});
 6531:     $record{'scantron.PaperID'}=
 6532: 	substr($data,$$scantron_config{'PaperID'}-1,
 6533: 	       $$scantron_config{'PaperIDlength'});
 6534:     $record{'scantron.FirstName'}=
 6535: 	substr($data,$$scantron_config{'FirstName'}-1,
 6536: 	       $$scantron_config{'FirstNamelength'});
 6537:     $record{'scantron.LastName'}=
 6538: 	substr($data,$$scantron_config{'LastName'}-1,
 6539: 	       $$scantron_config{'LastNamelength'});
 6540:     if ($just_header) { return \%record; }
 6541: 
 6542:     my @alphabet=('A'..'Z');
 6543:     my $questnum=0;
 6544:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6545: 
 6546:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6547:     if ($randompick || $randomorder) {
 6548:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6549:                                          $master_seq,$symb_to_resource,
 6550:                                          $partids_by_symb,$orderedforcode,
 6551:                                          $respnumlookup,$startline);
 6552:         if ($total) {
 6553:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6554:         }
 6555:         if (ref($totalref)) {
 6556:             $$totalref = $total;
 6557:         }
 6558:     }
 6559:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6560:     chomp($questions);		# Get rid of any trailing \n.
 6561:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6562:     while (length($questions)) {
 6563:         my $answers_needed;
 6564:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6565:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6566:         } else {
 6567: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6568:         }
 6569:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6570:                              || 1;
 6571:         $questnum++;
 6572:         my $quest_id = $questnum;
 6573:         my $currentquest = substr($questions,0,$answer_length);
 6574:         $questions       = substr($questions,$answer_length);
 6575:         if (length($currentquest) < $answer_length) { next; }
 6576: 
 6577:         my $subdivided;
 6578:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6579:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6580:         } else {
 6581:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6582:         }
 6583:         if ($subdivided =~ /,/) {
 6584:             my $subquestnum = 1;
 6585:             my $subquestions = $currentquest;
 6586:             my @subanswers_needed = split(/,/,$subdivided);
 6587:             foreach my $subans (@subanswers_needed) {
 6588:                 my $subans_length =
 6589:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6590:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6591:                 $subquestions   = substr($subquestions,$subans_length);
 6592:                 $quest_id = "$questnum.$subquestnum";
 6593:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6594:                     ($$scantron_config{'Qon'} eq 'number')) {
 6595:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6596:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6597:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6598:                         $randomorder,$randompick,$respnumlookup);
 6599:                 } else {
 6600:                     $ansnum = &scantron_validator_positional($ansnum,
 6601:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6602:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6603:                         $randomorder,$randompick,$respnumlookup);
 6604:                 }
 6605:                 $subquestnum ++;
 6606:             }
 6607:         } else {
 6608:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6609:                 ($$scantron_config{'Qon'} eq 'number')) {
 6610:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6611:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6612:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6613:                     $randomorder,$randompick,$respnumlookup);
 6614:             } else {
 6615:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6616:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6617:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6618:                     $randomorder,$randompick,$respnumlookup);
 6619:             }
 6620:         }
 6621:     }
 6622:     $record{'scantron.maxquest'}=$questnum;
 6623:     return \%record;
 6624: }
 6625: 
 6626: sub get_master_seq {
 6627:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6628:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6629:                    (ref($symb_to_resource) eq 'HASH'));
 6630:     my $resource_error;
 6631:     foreach my $resource (@{$resources}) {
 6632:         my $ressymb;
 6633:         if (ref($resource)) {
 6634:             $ressymb = $resource->symb();
 6635:             push(@{$master_seq},$ressymb);
 6636:             $symb_to_resource->{$ressymb} = $resource;
 6637:         } else {
 6638:             $resource_error = 1;
 6639:             last;
 6640:         }
 6641:     }
 6642:     return $resource_error;
 6643: }
 6644: 
 6645: sub get_respnum_lookups {
 6646:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6647:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6648:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6649:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6650:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6651:                    (ref($startline) eq 'HASH'));
 6652:     my ($user,$scancode);
 6653:     if ((exists($record->{'scantron.CODE'})) &&
 6654:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6655:         $scancode = $record->{'scantron.CODE'};
 6656:     } else {
 6657:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6658:     }
 6659:     my @mapresources =
 6660:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6661:                      $orderedforcode);
 6662:     my $total = 0;
 6663:     my $count = 0;
 6664:     foreach my $resource (@mapresources) {
 6665:         my $id = $resource->id();
 6666:         my $symb = $resource->symb();
 6667:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6668:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6669:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6670:                 if ($respnum ne '') {
 6671:                     $respnumlookup->{$count} = $respnum;
 6672:                     $startline->{$count} = $total;
 6673:                     $total += $bubble_lines_per_response{$respnum};
 6674:                     $count ++;
 6675:                 }
 6676:             }
 6677:         }
 6678:     }
 6679:     return $total;
 6680: }
 6681: 
 6682: sub scantron_validator_lettnum {
 6683:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6684:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6685:         $randompick,$respnumlookup) = @_;
 6686: 
 6687:     # Qon 'letter' implies for each slot in currquest we have:
 6688:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6689:     #    about anything else (esp. a value of Qoff) for missing
 6690:     #    bubbles.
 6691:     #
 6692:     # Qon 'number' implies each slot gives a digit that indexes the
 6693:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6694:     #    and * or ? for double bubbles on a single line.
 6695:     #
 6696: 
 6697:     my $matchon;
 6698:     if ($$scantron_config{'Qon'} eq 'letter') {
 6699:         $matchon = '[A-Z]';
 6700:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6701:         $matchon = '\d';
 6702:     }
 6703:     my $occurrences = 0;
 6704:     my $responsenum = $questnum-1;
 6705:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6706:        $responsenum = $respnumlookup->{$questnum-1} 
 6707:     }
 6708:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6709:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6710:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6711:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6712:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6713:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6714:         my @singlelines = split('',$currquest);
 6715:         foreach my $entry (@singlelines) {
 6716:             $occurrences = &occurence_count($entry,$matchon);
 6717:             if ($occurrences > 1) {
 6718:                 last;
 6719:             }
 6720:         }
 6721:     } else {
 6722:         $occurrences = &occurence_count($currquest,$matchon); 
 6723:     }
 6724:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6725:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6726:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6727:             my $bubble = substr($currquest,$ans,1);
 6728:             if ($bubble =~ /$matchon/ ) {
 6729:                 if ($$scantron_config{'Qon'} eq 'number') {
 6730:                     if ($bubble == 0) {
 6731:                         $bubble = 10; 
 6732:                     }
 6733:                     $record->{"scantron.$ansnum.answer"} = 
 6734:                         $alphabet->[$bubble-1];
 6735:                 } else {
 6736:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6737:                 }
 6738:             } else {
 6739:                 $record->{"scantron.$ansnum.answer"}='';
 6740:             }
 6741:             $ansnum++;
 6742:         }
 6743:     } elsif (!defined($currquest)
 6744:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6745:             || (&occurence_count($currquest,$matchon) == 0)) {
 6746:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6747:             $record->{"scantron.$ansnum.answer"}='';
 6748:             $ansnum++;
 6749:         }
 6750:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6751:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6752:         }
 6753:     } else {
 6754:         if ($$scantron_config{'Qon'} eq 'number') {
 6755:             $currquest = &digits_to_letters($currquest);            
 6756:         }
 6757:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6758:             my $bubble = substr($currquest,$ans,1);
 6759:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6760:             $ansnum++;
 6761:         }
 6762:     }
 6763:     return $ansnum;
 6764: }
 6765: 
 6766: sub scantron_validator_positional {
 6767:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6768:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6769:         $randomorder,$randompick,$respnumlookup) = @_;
 6770: 
 6771:     # Otherwise there's a positional notation;
 6772:     # each bubble line requires Qlength items, and there are filled in
 6773:     # bubbles for each case where there 'Qon' characters.
 6774:     #
 6775: 
 6776:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6777: 
 6778:     # If the split only gives us one element.. the full length of the
 6779:     # answer string, no bubbles are filled in:
 6780: 
 6781:     if ($answers_needed eq '') {
 6782:         return;
 6783:     }
 6784: 
 6785:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6786:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6787:             $record->{"scantron.$ansnum.answer"}='';
 6788:             $ansnum++;
 6789:         }
 6790:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6791:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6792:         }
 6793:     } elsif (scalar(@array) == 2) {
 6794:         my $location = length($array[0]);
 6795:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6796:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6797:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6798:             if ($ans eq $line_num) {
 6799:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6800:             } else {
 6801:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6802:             }
 6803:             $ansnum++;
 6804:          }
 6805:     } else {
 6806:         #  If there's more than one instance of a bubble character
 6807:         #  That's a double bubble; with positional notation we can
 6808:         #  record all the bubbles filled in as well as the
 6809:         #  fact this response consists of multiple bubbles.
 6810:         #
 6811:         my $responsenum = $questnum-1;
 6812:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6813:             $responsenum = $respnumlookup->{$questnum-1}
 6814:         }
 6815:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6816:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6817:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6818:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6819:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6820:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6821:             my $doubleerror = 0;
 6822:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6823:                    (!$doubleerror)) {
 6824:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6825:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6826:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6827:                if (length(@currarray) > 2) {
 6828:                    $doubleerror = 1;
 6829:                } 
 6830:             }
 6831:             if ($doubleerror) {
 6832:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6833:             }
 6834:         } else {
 6835:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6836:         }
 6837:         my $item = $ansnum;
 6838:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6839:             $record->{"scantron.$item.answer"} = '';
 6840:             $item ++;
 6841:         }
 6842: 
 6843:         my @ans=@array;
 6844:         my $i=0;
 6845:         my $increment = 0;
 6846:         while ($#ans) {
 6847:             $i+=length($ans[0]) + $increment;
 6848:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6849:             my $bubble = $i%$$scantron_config{'Qlength'};
 6850:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6851:             shift(@ans);
 6852:             $increment = 1;
 6853:         }
 6854:         $ansnum += $answers_needed;
 6855:     }
 6856:     return $ansnum;
 6857: }
 6858: 
 6859: =pod
 6860: 
 6861: =item scantron_add_delay
 6862: 
 6863:    Adds an error message that occurred during the grading phase to a
 6864:    queue of messages to be shown after grading pass is complete
 6865: 
 6866:  Arguments:
 6867:    $delayqueue  - arrary ref of hash ref of error messages
 6868:    $scanline    - the scanline that caused the error
 6869:    $errormesage - the error message
 6870:    $errorcode   - a numeric code for the error
 6871: 
 6872:  Side Effects:
 6873:    updates the $delayqueue to have a new hash ref of the error
 6874: 
 6875: =cut
 6876: 
 6877: sub scantron_add_delay {
 6878:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6879:     push(@$delayqueue,
 6880: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6881: 	  'ecode' => $errorcode }
 6882: 	 );
 6883: }
 6884: 
 6885: =pod
 6886: 
 6887: =item scantron_find_student
 6888: 
 6889:    Finds the username for the current scanline
 6890: 
 6891:   Arguments:
 6892:    $scantron_record - hash result from scantron_parse_scanline
 6893:    $scan_data       - hash of correction information 
 6894:                       (see &scantron_getfile() form more information)
 6895:    $idmap           - hash from &username_to_idmap()
 6896:    $line            - number of current scanline
 6897:  
 6898:   Returns:
 6899:    Either 'username:domain' or undef if unknown
 6900: 
 6901: =cut
 6902: 
 6903: sub scantron_find_student {
 6904:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6905:     my $scanID=$$scantron_record{'scantron.ID'};
 6906:     if ($scanID =~ /^\s*$/) {
 6907:  	return &scan_data($scan_data,"$line.user");
 6908:     }
 6909:     foreach my $id (keys(%$idmap)) {
 6910:  	if (lc($id) eq lc($scanID)) {
 6911:  	    return $$idmap{$id};
 6912:  	}
 6913:     }
 6914:     return undef;
 6915: }
 6916: 
 6917: =pod
 6918: 
 6919: =item scantron_filter
 6920: 
 6921:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6922:    hidden resources was selected
 6923: 
 6924: =cut
 6925: 
 6926: sub scantron_filter {
 6927:     my ($curres)=@_;
 6928: 
 6929:     if (ref($curres) && $curres->is_problem()) {
 6930: 	# if the user has asked to not have either hidden
 6931: 	# or 'randomout' controlled resources to be graded
 6932: 	# don't include them
 6933: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6934: 	    && $curres->randomout) {
 6935: 	    return 0;
 6936: 	}
 6937: 	return 1;
 6938:     }
 6939:     return 0;
 6940: }
 6941: 
 6942: =pod
 6943: 
 6944: =item scantron_process_corrections
 6945: 
 6946:    Gets correction information out of submitted form data and corrects
 6947:    the scanline
 6948: 
 6949: =cut
 6950: 
 6951: sub scantron_process_corrections {
 6952:     my ($r) = @_;
 6953:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6954:     my ($scanlines,$scan_data)=&scantron_getfile();
 6955:     my $classlist=&Apache::loncoursedata::get_classlist();
 6956:     my $which=$env{'form.scantron_line'};
 6957:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6958:     my ($skip,$err,$errmsg);
 6959:     if ($env{'form.scantron_skip_record'}) {
 6960: 	$skip=1;
 6961:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6962: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6963: 	    $env{'form.scantron_domain'};
 6964: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6965: 	($line,$err,$errmsg)=
 6966: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6967: 				     'ID',{'newid'=>$newid,
 6968: 				    'username'=>$env{'form.scantron_username'},
 6969: 				    'domain'=>$env{'form.scantron_domain'}});
 6970:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6971: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6972: 	my $newCODE;
 6973: 	my %args;
 6974: 	if      ($resolution eq 'use_unfound') {
 6975: 	    $newCODE='use_unfound';
 6976: 	} elsif ($resolution eq 'use_found') {
 6977: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6978: 	} elsif ($resolution eq 'use_typed') {
 6979: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6980: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6981: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6982: 	}
 6983: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6984: 	    $args{'CODE_ignore_dup'}=1;
 6985: 	}
 6986: 	$args{'CODE'}=$newCODE;
 6987: 	($line,$err,$errmsg)=
 6988: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6989: 				     'CODE',\%args);
 6990:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6991: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6992: 	    ($line,$err,$errmsg)=
 6993: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6994: 					 $which,'answer',
 6995: 					 { 'question'=>$question,
 6996: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6997:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6998: 	    if ($err) { last; }
 6999: 	}
 7000:     }
 7001:     if ($err) {
 7002:         $r->print(
 7003:             '<p class="LC_error">'
 7004:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7005:                 $errmsg)
 7006:            .'</p>');
 7007:     } else {
 7008: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7009: 	&scantron_putfile($scanlines,$scan_data);
 7010:     }
 7011: }
 7012: 
 7013: =pod
 7014: 
 7015: =item reset_skipping_status
 7016: 
 7017:    Forgets the current set of remember skipped scanlines (and thus
 7018:    reverts back to considering all lines in the
 7019:    scantron_skipped_<filename> file)
 7020: 
 7021: =cut
 7022: 
 7023: sub reset_skipping_status {
 7024:     my ($scanlines,$scan_data)=&scantron_getfile();
 7025:     &scan_data($scan_data,'remember_skipping',undef,1);
 7026:     &scantron_putfile(undef,$scan_data);
 7027: }
 7028: 
 7029: =pod
 7030: 
 7031: =item start_skipping
 7032: 
 7033:    Marks a scanline to be skipped. 
 7034: 
 7035: =cut
 7036: 
 7037: sub start_skipping {
 7038:     my ($scan_data,$i)=@_;
 7039:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7040:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7041: 	$remembered{$i}=2;
 7042:     } else {
 7043: 	$remembered{$i}=1;
 7044:     }
 7045:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7046: }
 7047: 
 7048: =pod
 7049: 
 7050: =item should_be_skipped
 7051: 
 7052:    Checks whether a scanline should be skipped.
 7053: 
 7054: =cut
 7055: 
 7056: sub should_be_skipped {
 7057:     my ($scanlines,$scan_data,$i)=@_;
 7058:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7059: 	# not redoing old skips
 7060: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7061: 	return 0;
 7062:     }
 7063:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7064: 
 7065:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7066: 	return 0;
 7067:     }
 7068:     return 1;
 7069: }
 7070: 
 7071: =pod
 7072: 
 7073: =item remember_current_skipped
 7074: 
 7075:    Discovers what scanlines are in the scantron_skipped_<filename>
 7076:    file and remembers them into scan_data for later use.
 7077: 
 7078: =cut
 7079: 
 7080: sub remember_current_skipped {
 7081:     my ($scanlines,$scan_data)=&scantron_getfile();
 7082:     my %to_remember;
 7083:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7084: 	if ($scanlines->{'skipped'}[$i]) {
 7085: 	    $to_remember{$i}=1;
 7086: 	}
 7087:     }
 7088: 
 7089:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7090:     &scantron_putfile(undef,$scan_data);
 7091: }
 7092: 
 7093: =pod
 7094: 
 7095: =item check_for_error
 7096: 
 7097:     Checks if there was an error when attempting to remove a specific
 7098:     scantron_.. bubblesheet data file. Prints out an error if
 7099:     something went wrong.
 7100: 
 7101: =cut
 7102: 
 7103: sub check_for_error {
 7104:     my ($r,$result)=@_;
 7105:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7106: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7107:     }
 7108: }
 7109: 
 7110: =pod
 7111: 
 7112: =item scantron_warning_screen
 7113: 
 7114:    Interstitial screen to make sure the operator has selected the
 7115:    correct options before we start the validation phase.
 7116: 
 7117: =cut
 7118: 
 7119: sub scantron_warning_screen {
 7120:     my ($button_text,$symb)=@_;
 7121:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7122:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7123:     my $CODElist;
 7124:     if ($scantron_config{'CODElocation'} &&
 7125: 	$scantron_config{'CODEstart'} &&
 7126: 	$scantron_config{'CODElength'}) {
 7127: 	$CODElist=$env{'form.scantron_CODElist'};
 7128: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7129: 	$CODElist=
 7130: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7131: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7132:     }
 7133:     my $lastbubblepoints;
 7134:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7135:         $lastbubblepoints =
 7136:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7137:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7138:     }
 7139:     return '
 7140: <p>
 7141: <span class="LC_warning">
 7142: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7143: </p>
 7144: <table>
 7145: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7146: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7147: '.$CODElist.$lastbubblepoints.'
 7148: </table>
 7149: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7150: '.&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>
 7151: ';
 7152: }
 7153: 
 7154: =pod
 7155: 
 7156: =item scantron_do_warning
 7157: 
 7158:    Check if the operator has picked something for all required
 7159:    fields. Error out if something is missing.
 7160: 
 7161: =cut
 7162: 
 7163: sub scantron_do_warning {
 7164:     my ($r,$symb)=@_;
 7165:     if (!$symb) {return '';}
 7166:     my $default_form_data=&defaultFormData($symb);
 7167:     $r->print(&scantron_form_start().$default_form_data);
 7168:     if ( $env{'form.selectpage'} eq '' ||
 7169: 	 $env{'form.scantron_selectfile'} eq '' ||
 7170: 	 $env{'form.scantron_format'} eq '' ) {
 7171: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7172: 	if ( $env{'form.selectpage'} eq '') {
 7173: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7174: 	} 
 7175: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7176: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7177: 	}
 7178: 	if ( $env{'form.scantron_format'} eq '') {
 7179: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7180: 	}
 7181:     } else {
 7182: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7183:         my ($checksec,@possibles) = &gradable_sections();
 7184:         my $gradesections;
 7185:         if ($checksec) {
 7186:             my $file=$env{'form.scantron_selectfile'};
 7187:             if (&valid_file($file)) {
 7188:                 my %bysec = &scantron_get_sections();
 7189:                 my $table;
 7190:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7191:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7192:                     $table = &Apache::loncommon::start_data_table()."\n".
 7193:                              &Apache::loncommon::start_data_table_header_row().
 7194:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7195:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7196:                     if ($bysec{'none'}) {
 7197:                         $table .= &Apache::loncommon::start_data_table_row().
 7198:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7199:                                   &Apache::loncommon::end_data_table_row()."\n";
 7200:                     }
 7201:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7202:                         next if ($sec eq 'none');
 7203:                         $table .= &Apache::loncommon::start_data_table_row().
 7204:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7205:                                   &Apache::loncommon::end_data_table_row()."\n";
 7206:                     }
 7207:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7208:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7209:                                       '<p>'.$table.'</p>';
 7210:                     if (@possibles) {
 7211:                         $gradesections .= '<p>'.
 7212:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7213:                                               scalar(@possibles)).'<br />'.
 7214:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7215:                                               '<i>'.$checksec.'</i>').' ';
 7216:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7217:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7218:                         }
 7219:                         $gradesections .= '</p>';
 7220:                     }
 7221:                 }
 7222:             } else {
 7223:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7224:             }
 7225:         }
 7226:         my $bubbledbyhand=&hand_bubble_option();
 7227: 	$r->print('
 7228: '.$warning.$gradesections.$bubbledbyhand.'
 7229: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7230: <input type="hidden" name="command" value="scantron_validate" />
 7231: ');
 7232:     }
 7233:     $r->print("</form><br />");
 7234:     return '';
 7235: }
 7236: 
 7237: =pod
 7238: 
 7239: =item scantron_form_start
 7240: 
 7241:     html hidden input for remembering all selected grading options
 7242: 
 7243: =cut
 7244: 
 7245: sub scantron_form_start {
 7246:     my ($max_bubble)=@_;
 7247:     my $result= <<SCANTRONFORM;
 7248: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7249:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7250:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7251:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7252:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7253:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7254:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7255:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7256:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7257:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7258: SCANTRONFORM
 7259: 
 7260:   my $line = 0;
 7261:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7262:        my $chunk =
 7263: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7264:        $chunk .=
 7265: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7266:        $chunk .= 
 7267:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7268:        $chunk .=
 7269:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7270:        $chunk .=
 7271:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7272:        $result .= $chunk;
 7273:        $line++;
 7274:     }
 7275:     return $result;
 7276: }
 7277: 
 7278: =pod
 7279: 
 7280: =item scantron_validate_file
 7281: 
 7282:     Dispatch routine for doing validation of a bubblesheet data file.
 7283: 
 7284:     Also processes any necessary information resets that need to
 7285:     occur before validation begins (ignore previous corrections,
 7286:     restarting the skipped records processing)
 7287: 
 7288: =cut
 7289: 
 7290: sub scantron_validate_file {
 7291:     my ($r,$symb) = @_;
 7292:     if (!$symb) {return '';}
 7293:     my $default_form_data=&defaultFormData($symb);
 7294:     
 7295:     # do the detection of only doing skipped records first before we delete
 7296:     # them when doing the corrections reset
 7297:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7298: 	&reset_skipping_status();
 7299:     }
 7300:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7301: 	&remember_current_skipped();
 7302: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7303:     }
 7304: 
 7305:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7306: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7307: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7308: 	&check_for_error($r,&scantron_remove_scan_data());
 7309: 	$env{'form.scantron_options_ignore'}='done';
 7310:     }
 7311: 
 7312:     if ($env{'form.scantron_corrections'}) {
 7313: 	&scantron_process_corrections($r);
 7314:     }
 7315: 
 7316:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7317:     my ($checksec,@gradable);
 7318:     if ($env{'request.course.sec'}) {
 7319:         ($checksec,my @possibles) = &gradable_sections();
 7320:         if ($checksec) {
 7321:             if (@possibles) {
 7322:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7323:                 if (@chosensecs) {
 7324:                     foreach my $sec (@chosensecs) {
 7325:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7326:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7327:                                 push(@gradable,$sec);
 7328:                             }
 7329:                         }
 7330:                     }
 7331:                 }
 7332:             }
 7333:             $r->print('<p><table>');
 7334:             if (@gradable) {
 7335:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7336:                 $r->print(
 7337:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7338:             } else {
 7339:                 $r->print(
 7340:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7341:             }
 7342:             $r->print('</table></p>');
 7343:         }
 7344:     }
 7345:     $r->rflush();
 7346: 
 7347:     #get the student pick code ready
 7348:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7349:     my $nav_error;
 7350:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7351:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7352:     if ($nav_error) {
 7353:         $r->print(&navmap_errormsg());
 7354:         return '';
 7355:     }
 7356:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7357:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7358:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7359:     }
 7360:     $r->print($result);
 7361:     
 7362:     my @validate_phases=( 'sequence',
 7363: 			  'ID',
 7364: 			  'CODE',
 7365: 			  'doublebubble',
 7366: 			  'missingbubbles');
 7367:     if (!$env{'form.validatepass'}) {
 7368: 	$env{'form.validatepass'} = 0;
 7369:     }
 7370:     my $currentphase=$env{'form.validatepass'};
 7371:     my %skipbysec=();
 7372: 
 7373:     my $stop=0;
 7374:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7375: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7376: 	$r->rflush();
 7377:      
 7378: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7379: 	{
 7380: 	    no strict 'refs';
 7381:             my @extras=();
 7382:             if ($validate_phases[$currentphase] eq 'ID') {
 7383:                 @extras = (\%skipbysec,$checksec,@gradable);
 7384:             }
 7385: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7386: 	}
 7387:     }
 7388:     if (!$stop) {
 7389: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7390:         my $secinfo;
 7391:         if (keys(%skipbysec) > 0) {
 7392:             my $seclist = '<ul>';
 7393:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7394:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7395:             }
 7396:             $seclist .= '</ul>';
 7397:             $secinfo = '<p class="LC_info">'.
 7398:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7399:                            $seclist).
 7400:                        '</p>';
 7401:         }
 7402: 	$r->print(&mt('Validation process complete.').'<br />'.
 7403:                   $secinfo.$warning.
 7404:                   &mt('Perform verification for each student after storage of submissions?').
 7405:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7406:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7407:                   ('&nbsp;'x3).'<label>'.
 7408:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7409:                   '</label></span><br />'.
 7410:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7411:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7412:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7413:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7414:     } else {
 7415: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7416: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7417:     }
 7418:     if ($stop) {
 7419: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7420: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7421: 	    $r->print(' '.&mt('this error').' <br />');
 7422: 
 7423: 	    $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>');
 7424: 	} else {
 7425:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7426: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7427:             } else {
 7428:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7429:             }
 7430: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7431: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7432: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7433: 	}
 7434:     }
 7435:     $r->print(" </form><br />");
 7436:     return '';
 7437: }
 7438: 
 7439: 
 7440: =pod
 7441: 
 7442: =item scantron_remove_file
 7443: 
 7444:    Removes the requested bubblesheet data file, makes sure that
 7445:    scantron_original_<filename> is never removed
 7446: 
 7447: 
 7448: =cut
 7449: 
 7450: sub scantron_remove_file {
 7451:     my ($which)=@_;
 7452:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7453:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7454:     my $file='scantron_';
 7455:     if ($which eq 'corrected' || $which eq 'skipped') {
 7456: 	$file.=$which.'_';
 7457:     } else {
 7458: 	return 'refused';
 7459:     }
 7460:     $file.=$env{'form.scantron_selectfile'};
 7461:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7462: }
 7463: 
 7464: 
 7465: =pod
 7466: 
 7467: =item scantron_remove_scan_data
 7468: 
 7469:    Removes all scan_data correction for the requested bubblesheet
 7470:    data file.  (In the case that both the are doing skipped records we need
 7471:    to remember the old skipped lines for the time being so that element
 7472:    persists for a while.)
 7473: 
 7474: =cut
 7475: 
 7476: sub scantron_remove_scan_data {
 7477:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7478:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7479:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7480:     my @todelete;
 7481:     my $filename=$env{'form.scantron_selectfile'};
 7482:     foreach my $key (@keys) {
 7483: 	if ($key=~/^\Q$filename\E_/) {
 7484: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7485: 		$key=~/remember_skipping/) {
 7486: 		next;
 7487: 	    }
 7488: 	    push(@todelete,$key);
 7489: 	}
 7490:     }
 7491:     my $result;
 7492:     if (@todelete) {
 7493: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7494: 				       \@todelete,$cdom,$cname);
 7495:     } else {
 7496: 	$result = 'ok';
 7497:     }
 7498:     return $result;
 7499: }
 7500: 
 7501: 
 7502: =pod
 7503: 
 7504: =item scantron_getfile
 7505: 
 7506:     Fetches the requested bubblesheet data file (all 3 versions), and
 7507:     the scan_data hash
 7508:   
 7509:   Arguments:
 7510:     None
 7511: 
 7512:   Returns:
 7513:     2 hash references
 7514: 
 7515:      - first one has 
 7516:          orig      -
 7517:          corrected -
 7518:          skipped   -  each of which points to an array ref of the specified
 7519:                       file broken up into individual lines
 7520:          count     - number of scanlines
 7521:  
 7522:      - second is the scan_data hash possible keys are
 7523:        ($number refers to scanline numbered $number and thus the key affects
 7524:         only that scanline
 7525:         $bubline refers to the specific bubble line element and the aspects
 7526:         refers to that specific bubble line element)
 7527: 
 7528:        $number.user - username:domain to use
 7529:        $number.CODE_ignore_dup 
 7530:                     - ignore the duplicate CODE error 
 7531:        $number.useCODE
 7532:                     - use the CODE in the scanline as is
 7533:        $number.no_bubble.$bubline
 7534:                     - it is valid that there is no bubbled in bubble
 7535:                       at $number $bubline
 7536:        remember_skipping
 7537:                     - a frozen hash containing keys of $number and values
 7538:                       of either 
 7539:                         1 - we are on a 'do skipped records pass' and plan
 7540:                             on processing this line
 7541:                         2 - we are on a 'do skipped records pass' and this
 7542:                             scanline has been marked to skip yet again
 7543: 
 7544: =cut
 7545: 
 7546: sub scantron_getfile {
 7547:     #FIXME really would prefer a scantron directory
 7548:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7550:     my $lines;
 7551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7552: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7553:     my %scanlines;
 7554:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7555:     my $temp=$scanlines{'orig'};
 7556:     $scanlines{'count'}=$#$temp;
 7557: 
 7558:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7559: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7560:     if ($lines eq '-1') {
 7561: 	$scanlines{'corrected'}=[];
 7562:     } else {
 7563: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7564:     }
 7565:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7566: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7567:     if ($lines eq '-1') {
 7568: 	$scanlines{'skipped'}=[];
 7569:     } else {
 7570: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7571:     }
 7572:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7573:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7574:     my %scan_data = @tmp;
 7575:     return (\%scanlines,\%scan_data);
 7576: }
 7577: 
 7578: =pod
 7579: 
 7580: =item lonnet_putfile
 7581: 
 7582:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7583: 
 7584:  Arguments:
 7585:    $contents - data to store
 7586:    $filename - filename to store $contents into
 7587: 
 7588:  Returns:
 7589:    result value from &Apache::lonnet::finishuserfileupload
 7590: 
 7591: =cut
 7592: 
 7593: sub lonnet_putfile {
 7594:     my ($contents,$filename)=@_;
 7595:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7596:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7597:     $env{'form.sillywaytopassafilearound'}=$contents;
 7598:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7599: 
 7600: }
 7601: 
 7602: =pod
 7603: 
 7604: =item scantron_putfile
 7605: 
 7606:     Stores the current version of the bubblesheet data files, and the
 7607:     scan_data hash. (Does not modify the original version only the
 7608:     corrected and skipped versions.
 7609: 
 7610:  Arguments:
 7611:     $scanlines - hash ref that looks like the first return value from
 7612:                  &scantron_getfile()
 7613:     $scan_data - hash ref that looks like the second return value from
 7614:                  &scantron_getfile()
 7615: 
 7616: =cut
 7617: 
 7618: sub scantron_putfile {
 7619:     my ($scanlines,$scan_data) = @_;
 7620:     #FIXME really would prefer a scantron directory
 7621:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7622:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7623:     if ($scanlines) {
 7624: 	my $prefix='scantron_';
 7625: # no need to update orig, shouldn't change
 7626: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7627: #		    $env{'form.scantron_selectfile'});
 7628: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7629: 			$prefix.'corrected_'.
 7630: 			$env{'form.scantron_selectfile'});
 7631: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7632: 			$prefix.'skipped_'.
 7633: 			$env{'form.scantron_selectfile'});
 7634:     }
 7635:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7636: }
 7637: 
 7638: =pod
 7639: 
 7640: =item scantron_get_line
 7641: 
 7642:    Returns the correct version of the scanline
 7643: 
 7644:  Arguments:
 7645:     $scanlines - hash ref that looks like the first return value from
 7646:                  &scantron_getfile()
 7647:     $scan_data - hash ref that looks like the second return value from
 7648:                  &scantron_getfile()
 7649:     $i         - number of the requested line (starts at 0)
 7650: 
 7651:  Returns:
 7652:    A scanline, (either the original or the corrected one if it
 7653:    exists), or undef if the requested scanline should be
 7654:    skipped. (Either because it's an skipped scanline, or it's an
 7655:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7656:    pass.
 7657: 
 7658: =cut
 7659: 
 7660: sub scantron_get_line {
 7661:     my ($scanlines,$scan_data,$i)=@_;
 7662:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7663:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7664:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7665:     return $scanlines->{'orig'}[$i]; 
 7666: }
 7667: 
 7668: =pod
 7669: 
 7670: =item scantron_todo_count
 7671: 
 7672:     Counts the number of scanlines that need processing.
 7673: 
 7674:  Arguments:
 7675:     $scanlines - hash ref that looks like the first return value from
 7676:                  &scantron_getfile()
 7677:     $scan_data - hash ref that looks like the second return value from
 7678:                  &scantron_getfile()
 7679: 
 7680:  Returns:
 7681:     $count - number of scanlines to process
 7682: 
 7683: =cut
 7684: 
 7685: sub get_todo_count {
 7686:     my ($scanlines,$scan_data)=@_;
 7687:     my $count=0;
 7688:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7689: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7690: 	if ($line=~/^[\s\cz]*$/) { next; }
 7691: 	$count++;
 7692:     }
 7693:     return $count;
 7694: }
 7695: 
 7696: =pod
 7697: 
 7698: =item scantron_put_line
 7699: 
 7700:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7701:     data file.
 7702: 
 7703:  Arguments:
 7704:     $scanlines - hash ref that looks like the first return value from
 7705:                  &scantron_getfile()
 7706:     $scan_data - hash ref that looks like the second return value from
 7707:                  &scantron_getfile()
 7708:     $i         - line number to update
 7709:     $newline   - contents of the updated scanline
 7710:     $skip      - if true make the line for skipping and update the
 7711:                  'skipped' file
 7712: 
 7713: =cut
 7714: 
 7715: sub scantron_put_line {
 7716:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7717:     if ($skip) {
 7718: 	$scanlines->{'skipped'}[$i]=$newline;
 7719: 	&start_skipping($scan_data,$i);
 7720: 	return;
 7721:     }
 7722:     $scanlines->{'corrected'}[$i]=$newline;
 7723: }
 7724: 
 7725: =pod
 7726: 
 7727: =item scantron_clear_skip
 7728: 
 7729:    Remove a line from the 'skipped' file
 7730: 
 7731:  Arguments:
 7732:     $scanlines - hash ref that looks like the first return value from
 7733:                  &scantron_getfile()
 7734:     $scan_data - hash ref that looks like the second return value from
 7735:                  &scantron_getfile()
 7736:     $i         - line number to update
 7737: 
 7738: =cut
 7739: 
 7740: sub scantron_clear_skip {
 7741:     my ($scanlines,$scan_data,$i)=@_;
 7742:     if (exists($scanlines->{'skipped'}[$i])) {
 7743: 	undef($scanlines->{'skipped'}[$i]);
 7744: 	return 1;
 7745:     }
 7746:     return 0;
 7747: }
 7748: 
 7749: =pod
 7750: 
 7751: =item scantron_filter_not_exam
 7752: 
 7753:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7754:    filter out resources that are not marked as 'exam' mode
 7755: 
 7756: =cut
 7757: 
 7758: sub scantron_filter_not_exam {
 7759:     my ($curres)=@_;
 7760:     
 7761:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7762: 	# if the user has asked to not have either hidden
 7763: 	# or 'randomout' controlled resources to be graded
 7764: 	# don't include them
 7765: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7766: 	    && $curres->randomout) {
 7767: 	    return 0;
 7768: 	}
 7769: 	return 1;
 7770:     }
 7771:     return 0;
 7772: }
 7773: 
 7774: =pod
 7775: 
 7776: =item scantron_validate_sequence
 7777: 
 7778:     Validates the selected sequence, checking for resource that are
 7779:     not set to exam mode.
 7780: 
 7781: =cut
 7782: 
 7783: sub scantron_validate_sequence {
 7784:     my ($r,$currentphase) = @_;
 7785: 
 7786:     my $navmap=Apache::lonnavmaps::navmap->new();
 7787:     unless (ref($navmap)) {
 7788:         $r->print(&navmap_errormsg());
 7789:         return (1,$currentphase);
 7790:     }
 7791:     my (undef,undef,$sequence)=
 7792: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7793: 
 7794:     my $map=$navmap->getResourceByUrl($sequence);
 7795: 
 7796:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7797:                                     value="ignore" />');
 7798:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7799: 	my @resources=
 7800: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7801: 	if (@resources) {
 7802: 	    $r->print(
 7803:                 '<p class="LC_warning">'
 7804:                .&mt('Some resources in the sequence currently are not set to'
 7805:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7806:                    .' work correctly.')
 7807:                .'</p>'
 7808:             );
 7809: 	    return (1,$currentphase);
 7810: 	}
 7811:     }
 7812: 
 7813:     return (0,$currentphase+1);
 7814: }
 7815: 
 7816: 
 7817: 
 7818: sub scantron_validate_ID {
 7819:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7820:     
 7821:     #get student info
 7822:     my $classlist=&Apache::loncoursedata::get_classlist();
 7823:     my %idmap=&username_to_idmap($classlist);
 7824:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7825: 
 7826:     #get scantron line setup
 7827:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7828:     my ($scanlines,$scan_data)=&scantron_getfile();
 7829: 
 7830:     my $nav_error;
 7831:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7832:     if ($nav_error) {
 7833:         $r->print(&navmap_errormsg());
 7834:         return(1,$currentphase);
 7835:     }
 7836: 
 7837:     my %found=('ids'=>{},'usernames'=>{});
 7838:     my $unsavedskips = 0;
 7839:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7840: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7841: 	if ($line=~/^[\s\cz]*$/) { next; }
 7842: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7843: 						 $scan_data);
 7844: 	my $id=$$scan_record{'scantron.ID'};
 7845: 	my $found;
 7846: 	foreach my $checkid (keys(%idmap)) {
 7847: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7848: 	}
 7849: 	if ($found) {
 7850: 	    my $username=$idmap{$found};
 7851:             if ($checksec) {
 7852:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7853:                     my $stusec = $classlist->{$username}->[$secidx];
 7854:                     if ($stusec ne $checksec) {
 7855:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7856:                             my $skip=1;
 7857:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7858:                             if (ref($skipbysec) eq 'HASH') {
 7859:                                 if ($stusec eq '') {
 7860:                                     $skipbysec->{'none'} ++;
 7861:                                 } else {
 7862:                                     $skipbysec->{$stusec} ++;
 7863:                                 }
 7864:                             }
 7865:                             $unsavedskips ++;
 7866:                             next;
 7867:                         }
 7868:                     }
 7869:                 }
 7870:             }
 7871: 	    if ($found{'ids'}{$found}) {
 7872: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7873: 					 $line,'duplicateID',$found);
 7874:                 if ($unsavedskips) {
 7875:                     &scantron_putfile($scanlines,$scan_data);
 7876:                     $unsavedskips = 0;
 7877:                 }
 7878: 		return(1,$currentphase);
 7879: 	    } elsif ($found{'usernames'}{$username}) {
 7880: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7881: 					 $line,'duplicateID',$username);
 7882:                 if ($unsavedskips) {
 7883:                     &scantron_putfile($scanlines,$scan_data);
 7884:                     $unsavedskips = 0;
 7885:                 }
 7886: 		return(1,$currentphase);
 7887: 	    }
 7888: 	    #FIXME store away line we previously saw the ID on to use above
 7889: 	    $found{'ids'}{$found}++;
 7890: 	    $found{'usernames'}{$username}++;
 7891: 	} else {
 7892: 	    if ($id =~ /^\s*$/) {
 7893: 		my $username=&scan_data($scan_data,"$i.user");
 7894:                 if (($checksec && $username ne '')) {
 7895:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 7896:                         my $stusec = $classlist->{$username}->[$secidx];
 7897:                         if ($stusec ne $checksec) {
 7898:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7899:                                 my $skip=1;
 7900:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7901:                                 if (ref($skipbysec) eq 'HASH') {
 7902:                                     if ($stusec eq '') {
 7903:                                         $skipbysec->{'none'} ++;
 7904:                                     } else {
 7905:                                         $skipbysec->{$stusec} ++;
 7906:                                     }
 7907:                                 }
 7908:                                 $unsavedskips ++;
 7909:                                 next;
 7910:                             }
 7911:                         }
 7912:                     }
 7913: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 7914: 		    &scantron_get_correction($r,$i,$scan_record,
 7915: 					     \%scantron_config,
 7916: 					     $line,'duplicateID',$username);
 7917:                     if ($unsavedskips) {
 7918:                         &scantron_putfile($scanlines,$scan_data);
 7919:                         $unsavedskips = 0;
 7920:                     }
 7921: 		    return(1,$currentphase);
 7922: 		} elsif (!defined($username)) {
 7923: 		    &scantron_get_correction($r,$i,$scan_record,
 7924: 					     \%scantron_config,
 7925: 					     $line,'incorrectID');
 7926:                     if ($unsavedskips) {
 7927:                         &scantron_putfile($scanlines,$scan_data);
 7928:                         $unsavedskips = 0;
 7929:                     }
 7930: 		    return(1,$currentphase);
 7931: 		}
 7932: 		$found{'usernames'}{$username}++;
 7933: 	    } else {
 7934: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7935: 					 $line,'incorrectID');
 7936:                 if ($unsavedskips) {
 7937:                     &scantron_putfile($scanlines,$scan_data);
 7938:                     $unsavedskips = 0;
 7939:                 }
 7940: 		return(1,$currentphase);
 7941: 	    }
 7942: 	}
 7943:     }
 7944:     if ($unsavedskips) {
 7945:         &scantron_putfile($scanlines,$scan_data);
 7946:         $unsavedskips = 0;
 7947:     }
 7948:     return (0,$currentphase+1);
 7949: }
 7950: 
 7951: sub scantron_get_sections {
 7952:     my %bysec;
 7953:     if ($env{'form.scantron_format'} ne '') {
 7954:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7955:         my ($scanlines,$scan_data)=&scantron_getfile();
 7956:         my $classlist=&Apache::loncoursedata::get_classlist();
 7957:         my %idmap=&username_to_idmap($classlist);
 7958:         foreach my $key (keys(%idmap)) {
 7959:             my $lckey = lc($key);
 7960:             $idmap{$lckey} = $idmap{$key};
 7961:         }
 7962:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 7963:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7964:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7965:             if ($line=~/^[\s\cz]*$/) { next; }
 7966:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7967:                                                      $scan_data);
 7968:             my $id=lc($$scan_record{'scantron.ID'});
 7969:             if (exists($idmap{$id})) {
 7970:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 7971:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 7972:                     if ($stusec eq '') {
 7973:                         $bysec{'none'} ++;
 7974:                     } else {
 7975:                         $bysec{$stusec} ++;
 7976:                     }
 7977:                 }
 7978:             }
 7979:         }
 7980:     }
 7981:     return %bysec;
 7982: }
 7983: 
 7984: sub scantron_get_correction {
 7985:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7986:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7987: #FIXME in the case of a duplicated ID the previous line, probably need
 7988: #to show both the current line and the previous one and allow skipping
 7989: #the previous one or the current one
 7990: 
 7991:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7992:         $r->print(
 7993:             '<p class="LC_warning">'
 7994:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7995:                 "<b>$error</b>",
 7996:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7997:            ."</p> \n");
 7998:     } else {
 7999:         $r->print(
 8000:             '<p class="LC_warning">'
 8001:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8002:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8003:            ."</p> \n");
 8004:     }
 8005:     my $message =
 8006:         '<p>'
 8007:        .&mt('The ID on the form is [_1]',
 8008:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8009:        .'<br />'
 8010:        .&mt('The name on the paper is [_1], [_2]',
 8011:             $$scan_record{'scantron.LastName'},
 8012:             $$scan_record{'scantron.FirstName'})
 8013:        .'</p>';
 8014: 
 8015:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8016:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8017:                            # Array populated for doublebubble or
 8018:     my @lines_to_correct;  # missingbubble errors to build javascript
 8019:                            # to validate radio button checking   
 8020: 
 8021:     if ($error =~ /ID$/) {
 8022: 	if ($error eq 'incorrectID') {
 8023:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8024: 		      "</p>\n");
 8025: 	} elsif ($error eq 'duplicateID') {
 8026:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8027: 	}
 8028: 	$r->print($message);
 8029: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8030: 	$r->print("\n<ul><li> ");
 8031: 	#FIXME it would be nice if this sent back the user ID and
 8032: 	#could do partial userID matches
 8033: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8034: 				       'scantron_username','scantron_domain'));
 8035: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8036: 	$r->print("\n:\n".
 8037: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8038: 
 8039: 	$r->print('</li>');
 8040:     } elsif ($error =~ /CODE$/) {
 8041: 	if ($error eq 'incorrectCODE') {
 8042: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8043: 	} elsif ($error eq 'duplicateCODE') {
 8044: 	    $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");
 8045: 	}
 8046: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8047: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8048:                  ."</p>\n");
 8049: 	$r->print($message);
 8050: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8051: 	$r->print("\n<br /> ");
 8052: 	my $i=0;
 8053: 	if ($error eq 'incorrectCODE' 
 8054: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8055: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8056: 	    if ($closest > 0) {
 8057: 		foreach my $testcode (@{$closest}) {
 8058: 		    my $checked='';
 8059: 		    if (!$i) { $checked=' checked="checked"'; }
 8060: 		    $r->print("
 8061:    <label>
 8062:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8063:        ".&mt("Use the similar CODE [_1] instead.",
 8064: 	    "<b><tt>".$testcode."</tt></b>")."
 8065:     </label>
 8066:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8067: 		    $r->print("\n<br />");
 8068: 		    $i++;
 8069: 		}
 8070: 	    }
 8071: 	}
 8072: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8073: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8074: 	    $r->print("
 8075:     <label>
 8076:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8077:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8078: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8079:     </label>");
 8080: 	    $r->print("\n<br />");
 8081: 	}
 8082: 
 8083: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8084: function change_radio(field) {
 8085:     var slct=document.scantronupload.scantron_CODE_resolution;
 8086:     var i;
 8087:     for (i=0;i<slct.length;i++) {
 8088:         if (slct[i].value==field) { slct[i].checked=true; }
 8089:     }
 8090: }
 8091: ENDSCRIPT
 8092: 	my $href="/adm/pickcode?".
 8093: 	   "form=".&escape("scantronupload").
 8094: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8095: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8096: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8097: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8098: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8099: 	    $r->print("
 8100:     <label>
 8101:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8102:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8103: 	     "<a target='_blank' href='$href'>","</a>")."
 8104:     </label> 
 8105:     ".&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\')" />'));
 8106: 	    $r->print("\n<br />");
 8107: 	}
 8108: 	$r->print("
 8109:     <label>
 8110:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8111:        ".&mt("Use [_1] as the CODE.",
 8112: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8113: 	$r->print("\n<br /><br />");
 8114:     } elsif ($error eq 'doublebubble') {
 8115: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8116: 
 8117: 	# The form field scantron_questions is acutally a list of line numbers.
 8118: 	# represented by this form so:
 8119: 
 8120: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8121:                                                 $respnumlookup,$startline);
 8122: 
 8123: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8124: 		  $line_list.'" />');
 8125: 	$r->print($message);
 8126: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8127: 	foreach my $question (@{$arg}) {
 8128: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8129:                                                    $scan_record, $error,
 8130:                                                    $randomorder,$randompick,
 8131:                                                    $respnumlookup,$startline);
 8132:             push(@lines_to_correct,@linenums);
 8133: 	}
 8134:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8135:     } elsif ($error eq 'missingbubble') {
 8136: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8137: 	$r->print($message);
 8138: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8139: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8140: 
 8141: 	# The form field scantron_questions is actually a list of line numbers not
 8142: 	# a list of question numbers. Therefore:
 8143: 	#
 8144: 
 8145: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8146:                                                 $respnumlookup,$startline);
 8147: 
 8148: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8149: 		  $line_list.'" />');
 8150: 	foreach my $question (@{$arg}) {
 8151: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8152:                                                    $scan_record, $error,
 8153:                                                    $randomorder,$randompick,
 8154:                                                    $respnumlookup,$startline);
 8155:             push(@lines_to_correct,@linenums);
 8156: 	}
 8157:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8158:     } else {
 8159: 	$r->print("\n<ul>");
 8160:     }
 8161:     $r->print("\n</li></ul>");
 8162: }
 8163: 
 8164: sub verify_bubbles_checked {
 8165:     my (@ansnums) = @_;
 8166:     my $ansnumstr = join('","',@ansnums);
 8167:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8168:     &js_escape(\$warning);
 8169:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8170: function verify_bubble_radio(form) {
 8171:     var ansnumArray = new Array ("$ansnumstr");
 8172:     var need_bubble_count = 0;
 8173:     for (var i=0; i<ansnumArray.length; i++) {
 8174:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8175:             var bubble_picked = 0; 
 8176:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8177:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8178:                     bubble_picked = 1;
 8179:                 }
 8180:             }
 8181:             if (bubble_picked == 0) {
 8182:                 need_bubble_count ++;
 8183:             }
 8184:         }
 8185:     }
 8186:     if (need_bubble_count) {
 8187:         alert("$warning");
 8188:         return;
 8189:     }
 8190:     form.submit(); 
 8191: }
 8192: ENDSCRIPT
 8193:     return $output;
 8194: }
 8195: 
 8196: =pod
 8197: 
 8198: =item  questions_to_line_list
 8199: 
 8200: Converts a list of questions into a string of comma separated
 8201: line numbers in the answer sheet used by the questions.  This is
 8202: used to fill in the scantron_questions form field.
 8203: 
 8204:   Arguments:
 8205:      questions    - Reference to an array of questions.
 8206:      randomorder  - True if randomorder in use.
 8207:      randompick   - True if randompick in use.
 8208:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8209:                      for current line to question number used for same question
 8210:                      in "Master Seqence" (as seen by Course Coordinator).
 8211:      startline    - Reference to hash where key is question number (0 is first)
 8212:                     and key is number of first bubble line for current student
 8213:                     or code-based randompick and/or randomorder.
 8214: 
 8215: =cut
 8216: 
 8217: 
 8218: sub questions_to_line_list {
 8219:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8220:     my @lines;
 8221: 
 8222:     foreach my $item (@{$questions}) {
 8223:         my $question = $item;
 8224:         my ($first,$count,$last);
 8225:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8226:             $question = $1;
 8227:             my $subquestion = $2;
 8228:             my $responsenum = $question-1;
 8229:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8230:                 $responsenum = $respnumlookup->{$question-1};
 8231:                 if (ref($startline) eq 'HASH') {
 8232:                     $first = $startline->{$question-1} + 1;
 8233:                 }
 8234:             } else {
 8235:                 $first = $first_bubble_line{$responsenum} + 1;
 8236:             }
 8237:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8238:             my $subcount = 1;
 8239:             while ($subcount<$subquestion) {
 8240:                 $first += $subans[$subcount-1];
 8241:                 $subcount ++;
 8242:             }
 8243:             $count = $subans[$subquestion-1];
 8244:         } else {
 8245:             my $responsenum = $question-1;
 8246:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8247:                 $responsenum = $respnumlookup->{$question-1};
 8248:                 if (ref($startline) eq 'HASH') {
 8249:                     $first = $startline->{$question-1} + 1;
 8250:                 }
 8251:             } else {
 8252:                 $first = $first_bubble_line{$responsenum} + 1;
 8253:             }
 8254: 	    $count   = $bubble_lines_per_response{$responsenum};
 8255:         }
 8256:         $last = $first+$count-1;
 8257:         push(@lines, ($first..$last));
 8258:     }
 8259:     return join(',', @lines);
 8260: }
 8261: 
 8262: =pod 
 8263: 
 8264: =item prompt_for_corrections
 8265: 
 8266: Prompts for a potentially multiline correction to the
 8267: user's bubbling (factors out common code from scantron_get_correction
 8268: for multi and missing bubble cases).
 8269: 
 8270:  Arguments:
 8271:    $r           - Apache request object.
 8272:    $question    - The question number to prompt for.
 8273:    $scan_config - The scantron file configuration hash.
 8274:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8275:    $error       - Type of error
 8276:    $randomorder - True if randomorder in use.
 8277:    $randompick  - True if randompick in use.
 8278:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8279:                     for current line to question number used for same question
 8280:                     in "Master Seqence" (as seen by Course Coordinator).
 8281:    $startline   - Reference to hash where key is question number (0 is first)
 8282:                   and value is number of first bubble line for current student
 8283:                   or code-based randompick and/or randomorder.
 8284: 
 8285: 
 8286:  Implicit inputs:
 8287:    %bubble_lines_per_response   - Starting line numbers for each question.
 8288:                                   Numbered from 0 (but question numbers are from
 8289:                                   1.
 8290:    %first_bubble_line           - Starting bubble line for each question.
 8291:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8292:                                   type problems render as separate sub-questions, 
 8293:                                   in exam mode. This hash contains a 
 8294:                                   comma-separated list of the lines per 
 8295:                                   sub-question.
 8296:    %responsetype_per_response   - essayresponse, formularesponse,
 8297:                                   stringresponse, imageresponse, reactionresponse,
 8298:                                   and organicresponse type problem parts can have
 8299:                                   multiple lines per response if the weight
 8300:                                   assigned exceeds 10.  In this case, only
 8301:                                   one bubble per line is permitted, but more 
 8302:                                   than one line might contain bubbles, e.g.
 8303:                                   bubbling of: line 1 - J, line 2 - J, 
 8304:                                   line 3 - B would assign 22 points.  
 8305: 
 8306: =cut
 8307: 
 8308: sub prompt_for_corrections {
 8309:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8310:         $randompick, $respnumlookup, $startline) = @_;
 8311:     my ($current_line,$lines);
 8312:     my @linenums;
 8313:     my $questionnum = $question;
 8314:     my ($first,$responsenum);
 8315:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8316:         $question = $1;
 8317:         my $subquestion = $2;
 8318:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8319:             $responsenum = $respnumlookup->{$question-1};
 8320:             if (ref($startline) eq 'HASH') {
 8321:                 $first = $startline->{$question-1};
 8322:             }
 8323:         } else {
 8324:             $responsenum = $question-1;
 8325:             $first = $first_bubble_line{$responsenum};
 8326:         }
 8327:         $current_line = $first + 1 ;
 8328:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8329:         my $subcount = 1;
 8330:         while ($subcount<$subquestion) {
 8331:             $current_line += $subans[$subcount-1];
 8332:             $subcount ++;
 8333:         }
 8334:         $lines = $subans[$subquestion-1];
 8335:     } else {
 8336:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8337:             $responsenum = $respnumlookup->{$question-1};
 8338:             if (ref($startline) eq 'HASH') { 
 8339:                 $first = $startline->{$question-1};
 8340:             }
 8341:         } else {
 8342:             $responsenum = $question-1;
 8343:             $first = $first_bubble_line{$responsenum};
 8344:         }
 8345:         $current_line = $first + 1;
 8346:         $lines        = $bubble_lines_per_response{$responsenum};
 8347:     }
 8348:     if ($lines > 1) {
 8349:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8350:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8351:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8352:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8353:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8354:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8355:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8356:             $r->print(
 8357:                 &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)
 8358:                .'<br /><br />'
 8359:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8360:                .'<br />'
 8361:                .&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.')
 8362:                .'<br />'
 8363:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8364:                .'<br /><br />'
 8365:             );
 8366:         } else {
 8367:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8368:         }
 8369:     }
 8370:     for (my $i =0; $i < $lines; $i++) {
 8371:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8372: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8373: 	        		  $questionnum,$error,split('', $selected));
 8374:         push(@linenums,$current_line);
 8375: 	$current_line++;
 8376:     }
 8377:     if ($lines > 1) {
 8378: 	$r->print("<hr /><br />");
 8379:     }
 8380:     return @linenums;
 8381: }
 8382: 
 8383: =pod
 8384: 
 8385: =item scantron_bubble_selector
 8386:   
 8387:    Generates the html radiobuttons to correct a single bubble line
 8388:    possibly showing the existing the selected bubbles if known
 8389: 
 8390:  Arguments:
 8391:     $r           - Apache request object
 8392:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8393:     $line        - Number of the line being displayed.
 8394:     $questionnum - Question number (may include subquestion)
 8395:     $error       - Type of error.
 8396:     @selected    - Array of bubbles picked on this line.
 8397: 
 8398: =cut
 8399: 
 8400: sub scantron_bubble_selector {
 8401:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8402:     my $max=$$scan_config{'Qlength'};
 8403: 
 8404:     my $scmode=$$scan_config{'Qon'};
 8405:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8406:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8407:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8408:             $max=$$scan_config{'BubblesPerRow'};
 8409:             if (($scmode eq 'number') && ($max > 10)) {
 8410:                 $max = 10;
 8411:             } elsif (($scmode eq 'letter') && $max > 26) {
 8412:                 $max = 26;
 8413:             }
 8414:         } else {
 8415:             $max = 10;
 8416:         }
 8417:     }
 8418: 
 8419:     my @alphabet=('A'..'Z');
 8420:     $r->print(&Apache::loncommon::start_data_table().
 8421:               &Apache::loncommon::start_data_table_row());
 8422:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8423:     for (my $i=0;$i<$max+1;$i++) {
 8424: 	$r->print("\n".'<td align="center">');
 8425: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8426: 	else { $r->print('&nbsp;'); }
 8427: 	$r->print('</td>');
 8428:     }
 8429:     $r->print(&Apache::loncommon::end_data_table_row().
 8430:               &Apache::loncommon::start_data_table_row());
 8431:     for (my $i=0;$i<$max;$i++) {
 8432: 	$r->print("\n".
 8433: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8434: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8435:     }
 8436:     my $nobub_checked = ' ';
 8437:     if ($error eq 'missingbubble') {
 8438:         $nobub_checked = ' checked = "checked" ';
 8439:     }
 8440:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8441: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8442:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8443:               $line.'" value="'.$questionnum.'" /></td>');
 8444:     $r->print(&Apache::loncommon::end_data_table_row().
 8445:               &Apache::loncommon::end_data_table());
 8446: }
 8447: 
 8448: =pod
 8449: 
 8450: =item num_matches
 8451: 
 8452:    Counts the number of characters that are the same between the two arguments.
 8453: 
 8454:  Arguments:
 8455:    $orig - CODE from the scanline
 8456:    $code - CODE to match against
 8457: 
 8458:  Returns:
 8459:    $count - integer count of the number of same characters between the
 8460:             two arguments
 8461: 
 8462: =cut
 8463: 
 8464: sub num_matches {
 8465:     my ($orig,$code) = @_;
 8466:     my @code=split(//,$code);
 8467:     my @orig=split(//,$orig);
 8468:     my $same=0;
 8469:     for (my $i=0;$i<scalar(@code);$i++) {
 8470: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8471:     }
 8472:     return $same;
 8473: }
 8474: 
 8475: =pod
 8476: 
 8477: =item scantron_get_closely_matching_CODEs
 8478: 
 8479:    Cycles through all CODEs and finds the set that has the greatest
 8480:    number of same characters as the provided CODE
 8481: 
 8482:  Arguments:
 8483:    $allcodes - hash ref returned by &get_codes()
 8484:    $CODE     - CODE from the current scanline
 8485: 
 8486:  Returns:
 8487:    2 element list
 8488:     - first elements is number of how closely matching the best fit is 
 8489:       (5 means best set has 5 matching characters)
 8490:     - second element is an arrary ref containing the set of valid CODEs
 8491:       that best fit the passed in CODE
 8492: 
 8493: =cut
 8494: 
 8495: sub scantron_get_closely_matching_CODEs {
 8496:     my ($allcodes,$CODE)=@_;
 8497:     my @CODEs;
 8498:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8499: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8500:     }
 8501: 
 8502:     return ($#CODEs,$CODEs[-1]);
 8503: }
 8504: 
 8505: =pod
 8506: 
 8507: =item get_codes
 8508: 
 8509:    Builds a hash which has keys of all of the valid CODEs from the selected
 8510:    set of remembered CODEs.
 8511: 
 8512:  Arguments:
 8513:   $old_name - name of the set of remembered CODEs
 8514:   $cdom     - domain of the course
 8515:   $cnum     - internal course name
 8516: 
 8517:  Returns:
 8518:   %allcodes - keys are the valid CODEs, values are all 1
 8519: 
 8520: =cut
 8521: 
 8522: sub get_codes {
 8523:     my ($old_name, $cdom, $cnum) = @_;
 8524:     if (!$old_name) {
 8525: 	$old_name=$env{'form.scantron_CODElist'};
 8526:     }
 8527:     if (!$cdom) {
 8528: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8529:     }
 8530:     if (!$cnum) {
 8531: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8532:     }
 8533:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8534: 				    $cdom,$cnum);
 8535:     my %allcodes;
 8536:     if ($result{"type\0$old_name"} eq 'number') {
 8537: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8538:     } else {
 8539: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8540:     }
 8541:     return %allcodes;
 8542: }
 8543: 
 8544: =pod
 8545: 
 8546: =item scantron_validate_CODE
 8547: 
 8548:    Validates all scanlines in the selected file to not have any
 8549:    invalid or underspecified CODEs and that none of the codes are
 8550:    duplicated if this was requested.
 8551: 
 8552: =cut
 8553: 
 8554: sub scantron_validate_CODE {
 8555:     my ($r,$currentphase) = @_;
 8556:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8557:     if ($scantron_config{'CODElocation'} &&
 8558: 	$scantron_config{'CODEstart'} &&
 8559: 	$scantron_config{'CODElength'}) {
 8560: 	if (!defined($env{'form.scantron_CODElist'})) {
 8561: 	    &FIXME_blow_up()
 8562: 	}
 8563:     } else {
 8564: 	return (0,$currentphase+1);
 8565:     }
 8566:     
 8567:     my %usedCODEs;
 8568: 
 8569:     my %allcodes=&get_codes();
 8570: 
 8571:     my $nav_error;
 8572:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8573:     if ($nav_error) {
 8574:         $r->print(&navmap_errormsg());
 8575:         return(1,$currentphase);
 8576:     }
 8577: 
 8578:     my ($scanlines,$scan_data)=&scantron_getfile();
 8579:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8580: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8581: 	if ($line=~/^[\s\cz]*$/) { next; }
 8582: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8583: 						 $scan_data);
 8584: 	my $CODE=$$scan_record{'scantron.CODE'};
 8585: 	my $error=0;
 8586: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8587: 	    &scantron_get_correction($r,$i,$scan_record,
 8588: 				     \%scantron_config,
 8589: 				     $line,'incorrectCODE',\%allcodes);
 8590: 	    return(1,$currentphase);
 8591: 	}
 8592: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8593: 	    && !$$scan_record{'scantron.useCODE'}) {
 8594: 	    &scantron_get_correction($r,$i,$scan_record,
 8595: 				     \%scantron_config,
 8596: 				     $line,'incorrectCODE',\%allcodes);
 8597: 	    return(1,$currentphase);
 8598: 	}
 8599: 	if (exists($usedCODEs{$CODE}) 
 8600: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8601: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8602: 	    &scantron_get_correction($r,$i,$scan_record,
 8603: 				     \%scantron_config,
 8604: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8605: 	    return(1,$currentphase);
 8606: 	}
 8607: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8608:     }
 8609:     return (0,$currentphase+1);
 8610: }
 8611: 
 8612: =pod
 8613: 
 8614: =item scantron_validate_doublebubble
 8615: 
 8616:    Validates all scanlines in the selected file to not have any
 8617:    bubble lines with multiple bubbles marked.
 8618: 
 8619: =cut
 8620: 
 8621: sub scantron_validate_doublebubble {
 8622:     my ($r,$currentphase) = @_;
 8623:     #get student info
 8624:     my $classlist=&Apache::loncoursedata::get_classlist();
 8625:     my %idmap=&username_to_idmap($classlist);
 8626:     my (undef,undef,$sequence)=
 8627:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8628: 
 8629:     #get scantron line setup
 8630:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8631:     my ($scanlines,$scan_data)=&scantron_getfile();
 8632: 
 8633:     my $navmap = Apache::lonnavmaps::navmap->new();
 8634:     unless (ref($navmap)) {
 8635:         $r->print(&navmap_errormsg());
 8636:         return(1,$currentphase);
 8637:     }
 8638:     my $map=$navmap->getResourceByUrl($sequence);
 8639:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8640:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8641:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8642:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8643: 
 8644:     my $nav_error;
 8645:     if (ref($map)) {
 8646:         $randomorder = $map->randomorder();
 8647:         $randompick = $map->randompick();
 8648:         if ($randomorder || $randompick) {
 8649:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8650:             if ($nav_error) {
 8651:                 $r->print(&navmap_errormsg());
 8652:                 return(1,$currentphase);
 8653:             }
 8654:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8655:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8656:         }
 8657:     } else {
 8658:         $r->print(&navmap_errormsg());
 8659:         return(1,$currentphase);
 8660:     }
 8661: 
 8662:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8663:     if ($nav_error) {
 8664:         $r->print(&navmap_errormsg());
 8665:         return(1,$currentphase);
 8666:     }
 8667: 
 8668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8670: 	if ($line=~/^[\s\cz]*$/) { next; }
 8671: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8672: 						 $scan_data,undef,\%idmap,$randomorder,
 8673:                                                  $randompick,$sequence,\@master_seq,
 8674:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8675:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8676: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8677: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8678: 				 'doublebubble',
 8679: 				 $$scan_record{'scantron.doubleerror'},
 8680:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8681:     	return (1,$currentphase);
 8682:     }
 8683:     return (0,$currentphase+1);
 8684: }
 8685: 
 8686: 
 8687: sub scantron_get_maxbubble {
 8688:     my ($nav_error,$scantron_config) = @_;
 8689:     if (defined($env{'form.scantron_maxbubble'}) &&
 8690: 	$env{'form.scantron_maxbubble'}) {
 8691: 	&restore_bubble_lines();
 8692: 	return $env{'form.scantron_maxbubble'};
 8693:     }
 8694: 
 8695:     my (undef, undef, $sequence) =
 8696: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8697: 
 8698:     my $navmap=Apache::lonnavmaps::navmap->new();
 8699:     unless (ref($navmap)) {
 8700:         if (ref($nav_error)) {
 8701:             $$nav_error = 1;
 8702:         }
 8703:         return;
 8704:     }
 8705:     my $map=$navmap->getResourceByUrl($sequence);
 8706:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8707:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8708: 
 8709:     &Apache::lonxml::clear_problem_counter();
 8710: 
 8711:     my $uname       = $env{'user.name'};
 8712:     my $udom        = $env{'user.domain'};
 8713:     my $cid         = $env{'request.course.id'};
 8714:     my $total_lines = 0;
 8715:     %bubble_lines_per_response = ();
 8716:     %first_bubble_line         = ();
 8717:     %subdivided_bubble_lines   = ();
 8718:     %responsetype_per_response = ();
 8719:     %masterseq_id_responsenum  = ();
 8720: 
 8721:     my $response_number = 0;
 8722:     my $bubble_line     = 0;
 8723:     foreach my $resource (@resources) {
 8724:         my $resid = $resource->id(); 
 8725:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8726:                                                           $udom,undef,$bubbles_per_row);
 8727:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8728: 	    foreach my $part_id (@{$parts}) {
 8729:                 my $lines;
 8730: 
 8731: 	        # TODO - make this a persistent hash not an array.
 8732: 
 8733:                 # optionresponse, matchresponse and rankresponse type items 
 8734:                 # render as separate sub-questions in exam mode.
 8735:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8736:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8737:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8738:                     my ($numbub,$numshown);
 8739:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8740:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8741:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8742:                         }
 8743:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8744:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8745:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8746:                         }
 8747:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8748:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8749:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8750:                         }
 8751:                     }
 8752:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8753:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8754:                     }
 8755:                     my $bubbles_per_row =
 8756:                         &bubblesheet_bubbles_per_row($scantron_config);
 8757:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8758:                     if (($numbub % $bubbles_per_row) != 0) {
 8759:                         $inner_bubble_lines++;
 8760:                     }
 8761:                     for (my $i=0; $i<$numshown; $i++) {
 8762:                         $subdivided_bubble_lines{$response_number} .= 
 8763:                             $inner_bubble_lines.',';
 8764:                     }
 8765:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8766:                     $lines = $numshown * $inner_bubble_lines;
 8767:                 } else {
 8768:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8769:                 }
 8770: 
 8771:                 $first_bubble_line{$response_number} = $bubble_line;
 8772: 	        $bubble_lines_per_response{$response_number} = $lines;
 8773:                 $responsetype_per_response{$response_number} = 
 8774:                     $analysis->{$part_id.'.type'};
 8775:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8776: 	        $response_number++;
 8777: 
 8778: 	        $bubble_line +=  $lines;
 8779: 	        $total_lines +=  $lines;
 8780: 	    }
 8781:         }
 8782:     }
 8783:     &Apache::lonnet::delenv('scantron.');
 8784: 
 8785:     &save_bubble_lines();
 8786:     $env{'form.scantron_maxbubble'} =
 8787: 	$total_lines;
 8788:     return $env{'form.scantron_maxbubble'};
 8789: }
 8790: 
 8791: sub bubblesheet_bubbles_per_row {
 8792:     my ($scantron_config) = @_;
 8793:     my $bubbles_per_row;
 8794:     if (ref($scantron_config) eq 'HASH') {
 8795:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8796:     }
 8797:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8798:         $bubbles_per_row = 10;
 8799:     }
 8800:     return $bubbles_per_row;
 8801: }
 8802: 
 8803: sub scantron_validate_missingbubbles {
 8804:     my ($r,$currentphase) = @_;
 8805:     #get student info
 8806:     my $classlist=&Apache::loncoursedata::get_classlist();
 8807:     my %idmap=&username_to_idmap($classlist);
 8808:     my (undef,undef,$sequence)=
 8809:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8810: 
 8811:     #get scantron line setup
 8812:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8813:     my ($scanlines,$scan_data)=&scantron_getfile();
 8814: 
 8815:     my $navmap = Apache::lonnavmaps::navmap->new();
 8816:     unless (ref($navmap)) {
 8817:         $r->print(&navmap_errormsg());
 8818:         return(1,$currentphase);
 8819:     }
 8820: 
 8821:     my $map=$navmap->getResourceByUrl($sequence);
 8822:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8823:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8824:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8825:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8826: 
 8827:     my $nav_error;
 8828:     if (ref($map)) {
 8829:         $randomorder = $map->randomorder();
 8830:         $randompick = $map->randompick();
 8831:         if ($randomorder || $randompick) {
 8832:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8833:             if ($nav_error) {
 8834:                 $r->print(&navmap_errormsg());
 8835:                 return(1,$currentphase);
 8836:             }
 8837:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8838:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8839:         }
 8840:     } else {
 8841:         $r->print(&navmap_errormsg());
 8842:         return(1,$currentphase);
 8843:     }
 8844: 
 8845: 
 8846:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8847:     if ($nav_error) {
 8848:         $r->print(&navmap_errormsg());
 8849:         return(1,$currentphase);
 8850:     }
 8851: 
 8852:     if (!$max_bubble) { $max_bubble=2**31; }
 8853:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8854: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8855: 	if ($line=~/^[\s\cz]*$/) { next; }
 8856: 	my $scan_record =
 8857:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8858: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8859:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8860:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8861: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8862: 	my @to_correct;
 8863: 	
 8864: 	# Probably here's where the error is...
 8865: 
 8866: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8867:             my $lastbubble;
 8868:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8869:                my $question = $1;
 8870:                my $subquestion = $2;
 8871:                my ($first,$responsenum);
 8872:                if ($randomorder || $randompick) {
 8873:                    $responsenum = $respnumlookup{$question-1};
 8874:                    $first = $startline{$question-1};
 8875:                } else {
 8876:                    $responsenum = $question-1; 
 8877:                    $first = $first_bubble_line{$responsenum};
 8878:                }
 8879:                if (!defined($first)) { next; }
 8880:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8881:                my $subcount = 1;
 8882:                while ($subcount<$subquestion) {
 8883:                    $first += $subans[$subcount-1];
 8884:                    $subcount ++;
 8885:                }
 8886:                my $count = $subans[$subquestion-1];
 8887:                $lastbubble = $first + $count;
 8888:             } else {
 8889:                my ($first,$responsenum);
 8890:                if ($randomorder || $randompick) {
 8891:                    $responsenum = $respnumlookup{$missing-1};
 8892:                    $first = $startline{$missing-1};
 8893:                } else {
 8894:                    $responsenum = $missing-1;
 8895:                    $first = $first_bubble_line{$responsenum};
 8896:                }
 8897:                if (!defined($first)) { next; }
 8898:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8899:             }
 8900:             if ($lastbubble > $max_bubble) { next; }
 8901: 	    push(@to_correct,$missing);
 8902: 	}
 8903: 	if (@to_correct) {
 8904: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8905: 				     $line,'missingbubble',\@to_correct,
 8906:                                      $randomorder,$randompick,\%respnumlookup,
 8907:                                      \%startline);
 8908: 	    return (1,$currentphase);
 8909: 	}
 8910: 
 8911:     }
 8912:     return (0,$currentphase+1);
 8913: }
 8914: 
 8915: sub hand_bubble_option {
 8916:     my (undef, undef, $sequence) =
 8917:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8918:     return if ($sequence eq '');
 8919:     my $navmap = Apache::lonnavmaps::navmap->new();
 8920:     unless (ref($navmap)) {
 8921:         return;
 8922:     }
 8923:     my $needs_hand_bubbles;
 8924:     my $map=$navmap->getResourceByUrl($sequence);
 8925:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8926:     foreach my $res (@resources) {
 8927:         if (ref($res)) {
 8928:             if ($res->is_problem()) {
 8929:                 my $partlist = $res->parts();
 8930:                 foreach my $part (@{ $partlist }) {
 8931:                     my @types = $res->responseType($part);
 8932:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8933:                         $needs_hand_bubbles = 1;
 8934:                         last;
 8935:                     }
 8936:                 }
 8937:             }
 8938:         }
 8939:     }
 8940:     if ($needs_hand_bubbles) {
 8941:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8942:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8943:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8944:                &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 />').
 8945:                '<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;'.
 8946:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8947:     }
 8948:     return;
 8949: }
 8950: 
 8951: sub scantron_process_students {
 8952:     my ($r,$symb) = @_;
 8953: 
 8954:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8955:     if (!$symb) {
 8956: 	return '';
 8957:     }
 8958:     my $default_form_data=&defaultFormData($symb);
 8959: 
 8960:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8961:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8962:     my ($scanlines,$scan_data)=&scantron_getfile();
 8963:     my $classlist=&Apache::loncoursedata::get_classlist();
 8964:     my %idmap=&username_to_idmap($classlist);
 8965:     my $navmap=Apache::lonnavmaps::navmap->new();
 8966:     unless (ref($navmap)) {
 8967:         $r->print(&navmap_errormsg());
 8968:         return '';
 8969:     }
 8970:     my $map=$navmap->getResourceByUrl($sequence);
 8971:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8972:         %grader_randomlists_by_symb);
 8973:     if (ref($map)) {
 8974:         $randomorder = $map->randomorder();
 8975:         $randompick = $map->randompick();
 8976:     } else {
 8977:         $r->print(&navmap_errormsg());
 8978:         return '';
 8979:     }
 8980:     my $nav_error;
 8981:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8982:     if ($randomorder || $randompick) {
 8983:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8984:         if ($nav_error) {
 8985:             $r->print(&navmap_errormsg());
 8986:             return '';
 8987:         }
 8988:     }
 8989:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8990:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8991: 
 8992:     my ($uname,$udom);
 8993:     my $result= <<SCANTRONFORM;
 8994: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8995:   <input type="hidden" name="command" value="scantron_configphase" />
 8996:   $default_form_data
 8997: SCANTRONFORM
 8998:     $r->print($result);
 8999: 
 9000:     my ($checksec,@possibles)=&gradable_sections();
 9001:     my @delayqueue;
 9002:     my (%completedstudents,%scandata);
 9003: 
 9004:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9005:     my $count=&get_todo_count($scanlines,$scan_data);
 9006:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9007:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9008:     $r->print('<br />');
 9009:     my $start=&Time::HiRes::time();
 9010:     my $i=-1;
 9011:     my $started;
 9012: 
 9013:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9014:     if ($nav_error) {
 9015:         $r->print(&navmap_errormsg());
 9016:         return '';
 9017:     }
 9018: 
 9019:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9020:     # the user and return.
 9021: 
 9022:     if ($ssi_error) {
 9023: 	$r->print("</form>");
 9024: 	&ssi_print_error($r);
 9025:         &Apache::lonnet::remove_lock($lock);
 9026: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9027:     }
 9028: 
 9029:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9030:     my $numletts = scalar(keys(%lettdig));
 9031:     my %orderedforcode;
 9032: 
 9033:     while ($i<$scanlines->{'count'}) {
 9034:  	($uname,$udom)=('','');
 9035:  	$i++;
 9036:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9037:  	if ($line=~/^[\s\cz]*$/) { next; }
 9038: 	if ($started) {
 9039: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9040: 	}
 9041: 	$started=1;
 9042:         my %respnumlookup = ();
 9043:         my %startline = ();
 9044:         my $total;
 9045:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9046:                                                  $scan_data,undef,\%idmap,$randomorder,
 9047:                                                  $randompick,$sequence,\@master_seq,
 9048:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9049:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9050:                                                  \$total);
 9051:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9052:  					      \%idmap,$i)) {
 9053:   	    &scantron_add_delay(\@delayqueue,$line,
 9054:  				'Unable to find a student that matches',1);
 9055:  	    next;
 9056:   	}
 9057:  	if (exists $completedstudents{$uname}) {
 9058:  	    &scantron_add_delay(\@delayqueue,$line,
 9059:  				'Student '.$uname.' has multiple sheets',2);
 9060:  	    next;
 9061:  	}
 9062:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9063:         if (($checksec ne '') && ($checksec ne $usec)) {
 9064:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9065:                 &scantron_add_delay(\@delayqueue,$line,
 9066:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9067:                 next;
 9068:             }
 9069:         }
 9070:         my $user = $uname.':'.$usec;
 9071:   	($uname,$udom)=split(/:/,$uname);
 9072: 
 9073:         my $scancode;
 9074:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9075:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9076:             $scancode = $scan_record->{'scantron.CODE'};
 9077:         } else {
 9078:             $scancode = '';
 9079:         }
 9080: 
 9081:         my @mapresources = @resources;
 9082:         if ($randomorder || $randompick) {
 9083:             @mapresources = 
 9084:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9085:                              \%orderedforcode);
 9086:         }
 9087:         my (%partids_by_symb,$res_error);
 9088:         foreach my $resource (@mapresources) {
 9089:             my $ressymb;
 9090:             if (ref($resource)) {
 9091:                 $ressymb = $resource->symb();
 9092:             } else {
 9093:                 $res_error = 1;
 9094:                 last;
 9095:             }
 9096:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9097:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9098:                 my $currcode;
 9099:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9100:                     $currcode = $scancode;
 9101:                 }
 9102:                 my ($analysis,$parts) =
 9103:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9104:                                               $uname,$udom,undef,$bubbles_per_row,
 9105:                                               $currcode);
 9106:                 $partids_by_symb{$ressymb} = $parts;
 9107:             } else {
 9108:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9109:             }
 9110:         }
 9111: 
 9112:         if ($res_error) {
 9113:             &scantron_add_delay(\@delayqueue,$line,
 9114:                                 'An error occurred while grading student '.$uname,2);
 9115:             next;
 9116:         }
 9117: 
 9118: 	&Apache::lonxml::clear_problem_counter();
 9119:   	&Apache::lonnet::appenv($scan_record);
 9120: 
 9121: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9122: 	    &scantron_putfile($scanlines,$scan_data);
 9123: 	}
 9124: 	
 9125:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9126:                                    \@mapresources,\%partids_by_symb,
 9127:                                    $bubbles_per_row,$randomorder,$randompick,
 9128:                                    \%respnumlookup,\%startline) 
 9129:             eq 'ssi_error') {
 9130:             $ssi_error = 0; # So end of handler error message does not trigger.
 9131:             $r->print("</form>");
 9132:             &ssi_print_error($r);
 9133:             &Apache::lonnet::remove_lock($lock);
 9134:             return '';      # Why return ''?  Beats me.
 9135:         }
 9136: 
 9137:         if (($scancode) && ($randomorder || $randompick)) {
 9138:             my $parmresult =
 9139:                 &Apache::lonparmset::storeparm_by_symb($symb,
 9140:                                                        '0_examcode',2,$scancode,
 9141:                                                        'string_examcode',$uname,
 9142:                                                        $udom);
 9143:         }
 9144: 	$completedstudents{$uname}={'line'=>$line};
 9145:         if ($env{'form.verifyrecord'}) {
 9146:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9147:             if ($randompick) {
 9148:                 if ($total) {
 9149:                     $lastpos = $total*$scantron_config{'Qlength'};
 9150:                 }
 9151:             }
 9152: 
 9153:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9154:             chomp($studentdata);
 9155:             $studentdata =~ s/\r$//;
 9156:             my $studentrecord = '';
 9157:             my $counter = -1;
 9158:             foreach my $resource (@mapresources) {
 9159:                 my $ressymb = $resource->symb();
 9160:                 ($counter,my $recording) =
 9161:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9162:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9163:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9164:                                              $randompick,\%respnumlookup,\%startline);
 9165:                 $studentrecord .= $recording;
 9166:             }
 9167:             if ($studentrecord ne $studentdata) {
 9168:                 &Apache::lonxml::clear_problem_counter();
 9169:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9170:                                            \@mapresources,\%partids_by_symb,
 9171:                                            $bubbles_per_row,$randomorder,$randompick,
 9172:                                            \%respnumlookup,\%startline) 
 9173:                     eq 'ssi_error') {
 9174:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9175:                     $r->print("</form>");
 9176:                     &ssi_print_error($r);
 9177:                     &Apache::lonnet::remove_lock($lock);
 9178:                     delete($completedstudents{$uname});
 9179:                     return '';
 9180:                 }
 9181:                 $counter = -1;
 9182:                 $studentrecord = '';
 9183:                 foreach my $resource (@mapresources) {
 9184:                     my $ressymb = $resource->symb();
 9185:                     ($counter,my $recording) =
 9186:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9187:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9188:                                                  \%scantron_config,\%lettdig,$numletts,
 9189:                                                  $randomorder,$randompick,\%respnumlookup,
 9190:                                                  \%startline);
 9191:                     $studentrecord .= $recording;
 9192:                 }
 9193:                 if ($studentrecord ne $studentdata) {
 9194:                     $r->print('<p><span class="LC_warning">');
 9195:                     if ($scancode eq '') {
 9196:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9197:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9198:                     } else {
 9199:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9200:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9201:                     }
 9202:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9203:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9204:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9205:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9206:                               &Apache::loncommon::start_data_table_row().
 9207:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9208:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9209:                               &Apache::loncommon::end_data_table_row().
 9210:                               &Apache::loncommon::start_data_table_row().
 9211:                               '<td>'.&mt('Stored submissions').'</td>'.
 9212:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9213:                               &Apache::loncommon::end_data_table_row().
 9214:                               &Apache::loncommon::end_data_table().'</p>');
 9215:                 } else {
 9216:                     $r->print('<br /><span class="LC_warning">'.
 9217:                              &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 />'.
 9218:                              &mt("As a consequence, this user's submission history records two tries.").
 9219:                                  '</span><br />');
 9220:                 }
 9221:             }
 9222:         }
 9223:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9224:     } continue {
 9225: 	&Apache::lonxml::clear_problem_counter();
 9226: 	&Apache::lonnet::delenv('scantron.');
 9227:     }
 9228:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9229:     &Apache::lonnet::remove_lock($lock);
 9230: #    my $lasttime = &Time::HiRes::time()-$start;
 9231: #    $r->print("<p>took $lasttime</p>");
 9232: 
 9233:     $r->print("</form>");
 9234:     return '';
 9235: }
 9236: 
 9237: sub graders_resources_pass {
 9238:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9239:         $bubbles_per_row) = @_;
 9240:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9241:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9242:         foreach my $resource (@{$resources}) {
 9243:             my $ressymb = $resource->symb();
 9244:             my ($analysis,$parts) =
 9245:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9246:                                           $env{'user.name'},$env{'user.domain'},
 9247:                                           1,$bubbles_per_row);
 9248:             $grader_partids_by_symb->{$ressymb} = $parts;
 9249:             if (ref($analysis) eq 'HASH') {
 9250:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9251:                     $grader_randomlists_by_symb->{$ressymb} =
 9252:                         $analysis->{'parts_withrandomlist'};
 9253:                 }
 9254:             }
 9255:         }
 9256:     }
 9257:     return;
 9258: }
 9259: 
 9260: =pod
 9261: 
 9262: =item users_order
 9263: 
 9264:   Returns array of resources in current map, ordered based on either CODE,
 9265:   if this is a CODEd exam, or based on student's identity if this is a 
 9266:   "NAMEd" exam.
 9267: 
 9268:   Should be used when randomorder and/or randompick applied when the 
 9269:   corresponding exam was printed, prior to students completing bubblesheets 
 9270:   for the version of the exam the student received.
 9271: 
 9272: =cut
 9273: 
 9274: sub users_order  {
 9275:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9276:     my @mapresources;
 9277:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9278:         return @mapresources;
 9279:     }
 9280:     if ($scancode) {
 9281:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9282:             @mapresources = @{$orderedforcode->{$scancode}};
 9283:         } else {
 9284:             $env{'form.CODE'} = $scancode;
 9285:             my $actual_seq =
 9286:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9287:                                                                $master_seq,
 9288:                                                                $user,$scancode,1);
 9289:             if (ref($actual_seq) eq 'ARRAY') {
 9290:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9291:                 if (ref($orderedforcode) eq 'HASH') {
 9292:                     if (@mapresources > 0) { 
 9293:                         $orderedforcode->{$scancode} = \@mapresources;
 9294:                     }
 9295:                 }
 9296:             }
 9297:             delete($env{'form.CODE'});
 9298:         }
 9299:     } else {
 9300:         my $actual_seq =
 9301:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9302:                                                            $master_seq,
 9303:                                                            $user,undef,1);
 9304:         if (ref($actual_seq) eq 'ARRAY') {
 9305:             @mapresources = 
 9306:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9307:         }
 9308:     }
 9309:     return @mapresources;
 9310: }
 9311: 
 9312: sub grade_student_bubbles {
 9313:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9314:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9315:     my $uselookup = 0;
 9316:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9317:         (ref($startline) eq 'HASH')) {
 9318:         $uselookup = 1;
 9319:     }
 9320: 
 9321:     if (ref($resources) eq 'ARRAY') {
 9322:         my $count = 0;
 9323:         foreach my $resource (@{$resources}) {
 9324:             my $ressymb = $resource->symb();
 9325:             my %form = ('submitted'      => 'scantron',
 9326:                         'grade_target'   => 'grade',
 9327:                         'grade_username' => $uname,
 9328:                         'grade_domain'   => $udom,
 9329:                         'grade_courseid' => $env{'request.course.id'},
 9330:                         'grade_symb'     => $ressymb,
 9331:                         'CODE'           => $scancode
 9332:                        );
 9333:             if ($bubbles_per_row ne '') {
 9334:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9335:             }
 9336:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9337:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9338:             }
 9339:             if (ref($parts) eq 'HASH') {
 9340:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9341:                     foreach my $part (@{$parts->{$ressymb}}) {
 9342:                         if ($uselookup) {
 9343:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9344:                         } else {
 9345:                             $form{'scantron_questnum_start.'.$part} =
 9346:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9347:                         }
 9348:                         $count++;
 9349:                     }
 9350:                 }
 9351:             }
 9352:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9353:             return 'ssi_error' if ($ssi_error);
 9354:             last if (&Apache::loncommon::connection_aborted($r));
 9355:         }
 9356:     }
 9357:     return;
 9358: }
 9359: 
 9360: sub scantron_upload_scantron_data {
 9361:     my ($r,$symb) = @_;
 9362:     my $dom = $env{'request.role.domain'};
 9363:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9364:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9365:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9366:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9367: 							  'domainid',
 9368: 							  'coursename',$dom);
 9369:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9370:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9371:     my $default_form_data=&defaultFormData($symb);
 9372:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9373:     &js_escape(\$nofile_alert);
 9374:     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.");
 9375:     &js_escape(\$nocourseid_alert);
 9376:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9377:     function checkUpload(formname) {
 9378: 	if (formname.upfile.value == "") {
 9379: 	    alert("'.$nofile_alert.'");
 9380: 	    return false;
 9381: 	}
 9382:         if (formname.courseid.value == "") {
 9383:             alert("'.$nocourseid_alert.'");
 9384:             return false;
 9385:         }
 9386: 	formname.submit();
 9387:     }
 9388: 
 9389:     function ToSyllabus() {
 9390:         var cdom = '."'$dom'".';
 9391:         var cnum = document.rules.courseid.value;
 9392:         if (cdom == "" || cdom == null) {
 9393:             return;
 9394:         }
 9395:         if (cnum == "" || cnum == null) {
 9396:            return;
 9397:         }
 9398:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9399:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9400:         return;
 9401:     }
 9402: 
 9403:     '.$formatjs.'
 9404: '));
 9405:     $r->print('
 9406: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9407: 
 9408: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9409: '.$default_form_data.
 9410:   &Apache::lonhtmlcommon::start_pick_box().
 9411:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9412:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9413:   &Apache::lonhtmlcommon::row_closure().
 9414:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9415:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9416:   &Apache::lonhtmlcommon::row_closure().
 9417:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9418:   '<input name="domainid" type="hidden" />'.$domdesc.
 9419:   &Apache::lonhtmlcommon::row_closure());
 9420:     if ($formatoptions) {
 9421:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9422:                   &Apache::lonhtmlcommon::row_closure());
 9423:     }
 9424:     $r->print(
 9425:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9426:   '<input type="file" name="upfile" size="50" />'.
 9427:   &Apache::lonhtmlcommon::row_closure(1).
 9428:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9429: 
 9430: <input name="command" value="scantronupload_save" type="hidden" />
 9431: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9432: </form>
 9433: ');
 9434:     return '';
 9435: }
 9436: 
 9437: sub scantron_upload_dataformat {
 9438:     my ($dom) = @_;
 9439:     my ($formatoptions,$formattitle,$formatjs);
 9440:     $formatjs = <<'END';
 9441: function toggleScantab(form) {
 9442:    return;
 9443: }
 9444: END
 9445:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9446:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9447:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9448:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9449:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9450:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9451:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9452:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9453:                             my ($onclick,$formatextra,$singleline);
 9454:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9455:                             my $count = 0;
 9456:                             foreach my $line (@lines) {
 9457:                                 next if ($line =~ /^#/);
 9458:                                 $singleline = $line;
 9459:                                 $count ++;
 9460:                             }
 9461:                             if ($count > 1) {
 9462:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9463:                                                '<span class="LC_nobreak">'.
 9464:                                                &mt('Bubblesheet type:').'&nbsp;'.
 9465:                                                &scantron_scantab().'</span></div>';
 9466:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9467:                                 $formatjs = <<"END";
 9468: function toggleScantab(form) {
 9469:     var divid = 'bubbletype';
 9470:     if (document.getElementById(divid)) {
 9471:         var radioname = 'fileformat';
 9472:         var num = form.elements[radioname].length;
 9473:         if (num) {
 9474:             for (var i=0; i<num; i++) {
 9475:                 if (form.elements[radioname][i].checked) {
 9476:                     var chosen = form.elements[radioname][i].value;
 9477:                     if (chosen == 'dat') {
 9478:                         document.getElementById(divid).style.display = 'none';
 9479:                     } else if (chosen == 'csv') {
 9480:                         document.getElementById(divid).style.display = 'block';
 9481:                     }
 9482:                 }
 9483:             }
 9484:         }
 9485:     }
 9486:     return;
 9487: }
 9488: 
 9489: END
 9490:                             } elsif ($count == 1) {
 9491:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9492:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9493:                             }
 9494:                             $formattitle = &mt('File format');
 9495:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9496:                                              &mt('Plain Text (no delimiters)').
 9497:                                              '</label>'.('&nbsp;'x2).
 9498:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9499:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9500:                         }
 9501:                     }
 9502:                 }
 9503:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9504:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9505:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9506:                         $formattitle = &mt('Bubblesheet type');
 9507:                         $formatoptions = &scantron_scantab();
 9508:                     }
 9509:                 }
 9510:             }
 9511:         }
 9512:     }
 9513:     return ($formatoptions,$formattitle,$formatjs);
 9514: }
 9515: 
 9516: sub scantron_upload_scantron_data_save {
 9517:     my ($r,$symb) = @_;
 9518:     my $doanotherupload=
 9519: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9520: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9521: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9522: 	'</form>'."\n";
 9523:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9524: 	!&Apache::lonnet::allowed('usc',
 9525: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9526:         !&Apache::lonnet::allowed('usc',
 9527:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9528: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9529: 	unless ($symb) {
 9530: 	    $r->print($doanotherupload);
 9531: 	}
 9532: 	return '';
 9533:     }
 9534:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9535:     my $uploadedfile;
 9536:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9537:     if (length($env{'form.upfile'}) < 2) {
 9538:         $r->print(
 9539:             &Apache::lonhtmlcommon::confirm_success(
 9540:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9541:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9542:     } else {
 9543:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9544:         my $parser;
 9545:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9546:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9547:                 my $is_csv;
 9548:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9549:                 if (@possibles > 1) {
 9550:                     if ($env{'form.fileformat'} eq 'csv') {
 9551:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9552:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9553:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9554:                                     $is_csv = 1;
 9555:                                 }
 9556:                             }
 9557:                         }
 9558:                     }
 9559:                 } elsif (@possibles == 1) {
 9560:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9561:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9562:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9563:                                 $is_csv = 1;
 9564:                             }
 9565:                         }
 9566:                     }
 9567:                 }
 9568:                 if ($is_csv) {
 9569:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9570:                 }
 9571:             }
 9572:         }
 9573:         my $result =
 9574:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9575:                                             $env{'form.courseid'},$env{'form.domainid'});
 9576:         if ($result =~ m{^/uploaded/}) {
 9577:             $r->print(
 9578:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9579:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9580:                         (length($env{'form.upfile'})-1),
 9581:                         '<span class="LC_filename">'.$result.'</span>'));
 9582:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9583:             if ($uploadedfile =~ /^scantron_orig_/) {
 9584:                 my $logname = $uploadedfile;
 9585:                 $logname =~ s/^scantron_orig_//;
 9586:                 if ($logname ne '') {
 9587:                     my $now = time;
 9588:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9589:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9590:                 }
 9591:             }
 9592:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9593:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9594:         } else {
 9595:             $r->print(
 9596:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9597:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9598:                           $result,
 9599: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9600: 	}
 9601:     }
 9602:     if ($symb) {
 9603: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9604:     } else {
 9605: 	$r->print($doanotherupload);
 9606:     }
 9607:     return '';
 9608: }
 9609: 
 9610: sub validate_uploaded_scantron_file {
 9611:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9612: 
 9613:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9614:     my @lines;
 9615:     if ($scanlines ne '-1') {
 9616:         @lines=split("\n",$scanlines,-1);
 9617:     }
 9618:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9619:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9620:     if ($context eq 'download') {
 9621:         $priv = 'mgr';
 9622:     } else {
 9623:         $priv = 'usc';
 9624:     }
 9625:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9626:             (($env{'request.course.id'}) &&
 9627:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9628:         if ($env{'request.course.sec'} ne '') {
 9629:             unless (&Apache::lonnet::allowed($priv,
 9630:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9631:                 unless ($context eq 'download') {
 9632:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9633:                 }
 9634:                 return $output;
 9635:             }
 9636:             ($checksec,@possibles)=&gradable_sections();
 9637:         }
 9638:     }
 9639:     if (@lines) {
 9640:         my (%counts,$max_match_format);
 9641:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9642:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9643:         my %idmap = &username_to_idmap($classlist);
 9644:         foreach my $key (keys(%idmap)) {
 9645:             my $lckey = lc($key);
 9646:             $idmap{$lckey} = $idmap{$key};
 9647:         }
 9648:         my %unique_formats;
 9649:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9650:         foreach my $line (@formatlines) {
 9651:             chomp($line);
 9652:             my @config = split(/:/,$line);
 9653:             my $idstart = $config[5];
 9654:             my $idlength = $config[6];
 9655:             if (($idstart ne '') && ($idlength > 0)) {
 9656:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9657:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9658:                 } else {
 9659:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9660:                 }
 9661:             }
 9662:         }
 9663:         foreach my $key (keys(%unique_formats)) {
 9664:             my ($idstart,$idlength) = split(':',$key);
 9665:             %{$counts{$key}} = (
 9666:                                'found'   => 0,
 9667:                                'total'   => 0,
 9668:                                'totalanysec' => 0,
 9669:                                'othersec' => 0,
 9670:                               );
 9671:             foreach my $line (@lines) {
 9672:                 next if ($line =~ /^#/);
 9673:                 next if ($line =~ /^[\s\cz]*$/);
 9674:                 my $id = substr($line,$idstart-1,$idlength);
 9675:                 $id = lc($id);
 9676:                 if (exists($idmap{$id})) {
 9677:                     if ($checksec ne '') {
 9678:                         $counts{$key}{'totalanysec'} ++;
 9679:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9680:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9681:                             if ($stusec ne $checksec) {
 9682:                                 if (@possibles) {
 9683:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9684:                                         $counts{$key}{'othersec'} ++;
 9685:                                         next;
 9686:                                     }
 9687:                                 } else {
 9688:                                     $counts{$key}{'othersec'} ++;
 9689:                                     next;
 9690:                                 }
 9691:                             }
 9692:                         }
 9693:                     }
 9694:                     $counts{$key}{'found'} ++;
 9695:                 }
 9696:                 $counts{$key}{'total'} ++;
 9697:             }
 9698:             if ($counts{$key}{'total'}) {
 9699:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9700:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9701:                     $max_match_pct = $percent_match;
 9702:                     $max_match_format = $key;
 9703:                     $found_match_count = $counts{$key}{'found'};
 9704:                     $max_match_count = $counts{$key}{'total'};
 9705:                 }
 9706:             }
 9707:         }
 9708:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9709:             my $format_descs;
 9710:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9711:             for (my $i=0; $i<$numwithformat; $i++) {
 9712:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9713:                 if ($i<$numwithformat-2) {
 9714:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9715:                 } elsif ($i==$numwithformat-2) {
 9716:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9717:                 } elsif ($i==$numwithformat-1) {
 9718:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9719:                 }
 9720:             }
 9721:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9722:             $output .= '<br />';
 9723:             if ($found_match_count == $max_match_count) {
 9724:                 # 100% matching entries
 9725:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9726:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9727:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9728:                 &mt('Comparison of student IDs in the uploaded file with'.
 9729:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9730:                     ' in the file (for the format defined for [_3]).',
 9731:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9732:             } else {
 9733:                 # Not all entries matching? -> Show warning and additional info
 9734:                 $output .=
 9735:                     &Apache::lonhtmlcommon::confirm_success(
 9736:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9737:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9738:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9739:                     &mt('Comparison of student IDs in the uploaded file with'.
 9740:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9741:                         ' in the file (for the format defined for [_3]).',
 9742:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9743:                     '<p class="LC_info">'.
 9744:                     &mt('A low percentage of matches results from one of the following:').
 9745:                     '</p><ul>'.
 9746:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9747:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9748:                                '<i>'.$cdom.'</i>').'</li>'.
 9749:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9750:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9751:                     '</ul>';
 9752:             }
 9753:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9754:                 if ($counts{$max_match_format}{'othersec'}) {
 9755:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9756:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9757:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9758:                     &js_escape(\$confirmdel);
 9759:                     $output .= '<p class="LC_warning">'.
 9760:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
 9761:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9762:                                '<br />'.
 9763:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
 9764:                                '</p><p>'.
 9765:                                &mt('If you prefer to delete the file now, use: [_1]').
 9766:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9767:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9768:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9769:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9770:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9771:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9772:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9773:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9774:                                '</form></p>';
 9775:                 }
 9776:             }
 9777:         }
 9778:         if (($context eq 'download') && ($checksec ne '')) {
 9779:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9780:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9781:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9782:             }
 9783:         } 
 9784:     } elsif ($context ne 'download') {
 9785:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9786:     }
 9787:     return $output;
 9788: }
 9789: 
 9790: sub gradable_sections {
 9791:     my $checksec = $env{'request.course.sec'};
 9792:     my @oksecs;
 9793:     if ($checksec) {
 9794:         my %availablesecs = &sections_grade_privs();
 9795:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9796:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9797:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9798:                     push(@oksecs,$sec);
 9799:                 }
 9800:             }
 9801:             if (grep(/^all$/,@oksecs)) {
 9802:                 undef($checksec);
 9803:             }
 9804:         }
 9805:     }
 9806:     return($checksec,@oksecs);
 9807: }
 9808: 
 9809: sub sections_grade_privs {
 9810:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9811:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9812:     my %availablesecs = (
 9813:                           mgr => [],
 9814:                           vgr => [],
 9815:                           usc => [],
 9816:                         );
 9817:     my $ccrole = 'cc';
 9818:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9819:         $ccrole = 'co';
 9820:     }
 9821:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9822:                                                      'userroles',['active'],
 9823:                                                      [$ccrole,'in','cr'],$cdom,1);
 9824:     my $crsid = $cnum.':'.$cdom;
 9825:     foreach my $item (keys(%crsroleshash)) {
 9826:         next unless ($item =~ /^$crsid\:/);
 9827:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9828:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9829:         if ($sec ne '') {
 9830:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9831:         }
 9832:         if (($role eq $ccrole) || ($role eq 'in')) {
 9833:             foreach my $priv ('mgr','vgr','usc') { 
 9834:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9835:                     if ($sec eq '') {
 9836:                         $availablesecs{$priv} = ['all'];
 9837:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9838:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9839:                             push(@{$availablesecs{$priv}},$sec);
 9840:                         }
 9841:                     }
 9842:                 }
 9843:             }
 9844:         } elsif ($role =~ m{^cr/}) {
 9845:             foreach my $priv ('mgr','vgr','usc') {
 9846:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9847:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9848:                         if ($sec eq '') {
 9849:                             $availablesecs{$priv} = ['all'];
 9850:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9851:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9852:                                 push(@{$availablesecs{$priv}},$sec);
 9853:                             }
 9854:                         }
 9855:                     }
 9856:                 }
 9857:             }
 9858:         }
 9859:     }
 9860:     return %availablesecs;
 9861: }
 9862: 
 9863: sub scantron_upload_delete {
 9864:     my ($r,$symb) = @_;
 9865:     my $filename = $env{'form.uploadedfile'};
 9866:     if ($filename =~ /^scantron_orig_/) {
 9867:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9868:             &Apache::lonnet::allowed('usc',
 9869:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9870:             &Apache::lonnet::allowed('usc',
 9871:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9872:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9873:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9874:             if ($retrieval eq '-1') {
 9875:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9876:                           &mt('File requested for deletion not found.'));
 9877:             } else {
 9878:                 $filename =~ s/^scantron_orig_//;
 9879:                 if ($filename ne '') {
 9880:                     my ($is_valid,$numleft);
 9881:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9882:                     if (keys(%info)) {
 9883:                         if (ref($info{$filename}) eq 'HASH') {
 9884:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9885:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9886:                                     $is_valid = 1;
 9887:                                     delete($info{$filename}{$timestamp}); 
 9888:                                 }
 9889:                             }
 9890:                             $numleft = scalar(keys(%{$info{$filename}}));
 9891:                         }
 9892:                     }
 9893:                     if ($is_valid) {
 9894:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
 9895:                         if ($result eq 'ok') {
 9896:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
 9897:                             if ($numleft) {
 9898:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9899:                             } else {
 9900:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9901:                             }
 9902:                         } else {
 9903:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9904:                                       &mt('Result was [_1]',$result));
 9905:                         }
 9906:                     } else {
 9907:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9908:                                   &mt('File requested for deletion was uploaded by a different user.'));
 9909:                     }
 9910:                 } else {
 9911:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9912:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9913:                 }
 9914:             }
 9915:         } else {
 9916:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
 9917:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
 9918:         }
 9919:     } else {
 9920:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9921:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9922:     }
 9923:     return;
 9924: }
 9925: 
 9926: sub valid_file {
 9927:     my ($requested_file)=@_;
 9928:     foreach my $filename (sort(&scantron_filenames())) {
 9929: 	if ($requested_file eq $filename) { return 1; }
 9930:     }
 9931:     return 0;
 9932: }
 9933: 
 9934: sub scantron_download_scantron_data {
 9935:     my ($r,$symb) = @_;
 9936:     my $default_form_data=&defaultFormData($symb);
 9937:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9938:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9939:     my $file=$env{'form.scantron_selectfile'};
 9940:     if (! &valid_file($file)) {
 9941: 	$r->print('
 9942: 	<p>
 9943: 	    '.&mt('The requested filename was invalid.').'
 9944:         </p>
 9945: ');
 9946: 	return;
 9947:     }
 9948:     my (%uploader,$is_owner,%counts,$percent);
 9949:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
 9950:     if (ref($uploader{$file}) eq 'HASH') {
 9951:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
 9952:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9953:                 $is_owner = 1;
 9954:                 last;
 9955:             }
 9956:         }
 9957:     }
 9958:     unless ($is_owner) {
 9959:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
 9960:         if ($counts{'totalanysec'}) {
 9961:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
 9962:             if ($percent_othersec >= 10) {
 9963:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
 9964:                 $r->print('<p class="LC_warning">'.
 9965:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
 9966:                           '</p>');
 9967:                 return;
 9968:             }
 9969:         }
 9970:     }
 9971:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9972:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9973:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9974:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9975:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9976:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9977:     $r->print('
 9978:     <p>
 9979: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9980: 	      '<a href="'.$orig.'">','</a>').'
 9981:     </p>
 9982:     <p>
 9983: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9984: 	      '<a href="'.$corrected.'">','</a>').'
 9985:     </p>
 9986:     <p>
 9987: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9988: 	      '<a href="'.$skipped.'">','</a>').'
 9989:     </p>
 9990: ');
 9991:     return '';
 9992: }
 9993: 
 9994: sub checkscantron_results {
 9995:     my ($r,$symb) = @_;
 9996:     if (!$symb) {return '';}
 9997:     my $cid = $env{'request.course.id'};
 9998:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9999:     my $numletts = scalar(keys(%lettdig));
10000:     my $cnum = $env{'course.'.$cid.'.num'};
10001:     my $cdom = $env{'course.'.$cid.'.domain'};
10002:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10003:     my %record;
10004:     my %scantron_config =
10005:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10006:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10007:     my ($scanlines,$scan_data)=&scantron_getfile();
10008:     my $classlist=&Apache::loncoursedata::get_classlist();
10009:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10010:     my $navmap=Apache::lonnavmaps::navmap->new();
10011:     unless (ref($navmap)) {
10012:         $r->print(&navmap_errormsg());
10013:         return '';
10014:     }
10015:     my $map=$navmap->getResourceByUrl($sequence);
10016:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10017:         %grader_randomlists_by_symb,%orderedforcode);
10018:     if (ref($map)) { 
10019:         $randomorder=$map->randomorder();
10020:         $randompick=$map->randompick();
10021:     }
10022:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10023:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10024:     if ($nav_error) {
10025:         $r->print(&navmap_errormsg());
10026:         return '';
10027:     }
10028:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10029:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10030:     my ($uname,$udom);
10031:     my (%scandata,%lastname,%bylast);
10032:     $r->print('
10033: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10034: 
10035:     my @delayqueue;
10036:     my %completedstudents;
10037: 
10038:     my $count=&get_todo_count($scanlines,$scan_data);
10039:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10040:     my ($username,$domain,$started);
10041:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10042:     if ($nav_error) {
10043:         $r->print(&navmap_errormsg());
10044:         return '';
10045:     }
10046: 
10047:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10048:     my $start=&Time::HiRes::time();
10049:     my $i=-1;
10050: 
10051:     while ($i<$scanlines->{'count'}) {
10052:         ($username,$domain,$uname)=('','','');
10053:         $i++;
10054:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10055:         if ($line=~/^[\s\cz]*$/) { next; }
10056:         if ($started) {
10057:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10058:         }
10059:         $started=1;
10060:         my $scan_record=
10061:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10062:                                                      $scan_data);
10063:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10064:                                               \%idmap,$i)) {
10065:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10066:                                 'Unable to find a student that matches',1);
10067:             next;
10068:         }
10069:         if (exists $completedstudents{$uname}) {
10070:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10071:                                 'Student '.$uname.' has multiple sheets',2);
10072:             next;
10073:         }
10074:         my $pid = $scan_record->{'scantron.ID'};
10075:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10076:         push(@{$bylast{$lastname{$pid}}},$pid);
10077:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10078:         my $user = $uname.':'.$usec;
10079:         ($username,$domain)=split(/:/,$uname);
10080: 
10081:         my $scancode;
10082:         if ((exists($scan_record->{'scantron.CODE'})) &&
10083:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10084:             $scancode = $scan_record->{'scantron.CODE'};
10085:         } else {
10086:             $scancode = '';
10087:         }
10088: 
10089:         my @mapresources = @resources;
10090:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10091:         my %respnumlookup=();
10092:         my %startline=();
10093:         if ($randomorder || $randompick) {
10094:             @mapresources =
10095:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10096:                              \%orderedforcode);
10097:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10098:                                              $scan_record,\@master_seq,\%symb_to_resource,
10099:                                              \%grader_partids_by_symb,\%orderedforcode,
10100:                                              \%respnumlookup,\%startline);
10101:             if ($randompick && $total) {
10102:                 $lastpos = $total*$scantron_config{'Qlength'};
10103:             }
10104:         }
10105:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10106:         chomp($scandata{$pid});
10107:         $scandata{$pid} =~ s/\r$//;
10108: 
10109:         my $counter = -1;
10110:         foreach my $resource (@mapresources) {
10111:             my $parts;
10112:             my $ressymb = $resource->symb();
10113:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10114:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10115:                 my $currcode;
10116:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10117:                     $currcode = $scancode;
10118:                 }
10119:                 (my $analysis,$parts) =
10120:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10121:                                               $username,$domain,undef,
10122:                                               $bubbles_per_row,$currcode);
10123:             } else {
10124:                 $parts = $grader_partids_by_symb{$ressymb};
10125:             }
10126:             ($counter,my $recording) =
10127:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10128:                                          $scandata{$pid},$parts,
10129:                                          \%scantron_config,\%lettdig,$numletts,
10130:                                          $randomorder,$randompick,
10131:                                          \%respnumlookup,\%startline);
10132:             $record{$pid} .= $recording;
10133:         }
10134:     }
10135:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10136:     $r->print('<br />');
10137:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10138:     $passed = 0;
10139:     $failed = 0;
10140:     $numstudents = 0;
10141:     foreach my $last (sort(keys(%bylast))) {
10142:         if (ref($bylast{$last}) eq 'ARRAY') {
10143:             foreach my $pid (sort(@{$bylast{$last}})) {
10144:                 my $showscandata = $scandata{$pid};
10145:                 my $showrecord = $record{$pid};
10146:                 $showscandata =~ s/\s/&nbsp;/g;
10147:                 $showrecord =~ s/\s/&nbsp;/g;
10148:                 if ($scandata{$pid} eq $record{$pid}) {
10149:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10150:                     $okstudents .= '<tr class="'.$css_class.'">'.
10151: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10152: '</tr>'."\n".
10153: '<tr class="'.$css_class.'">'."\n".
10154: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10155:                     $passed ++;
10156:                 } else {
10157:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10158:                     $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".
10159: '</tr>'."\n".
10160: '<tr class="'.$css_class.'">'."\n".
10161: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10162: '</tr>'."\n";
10163:                     $failed ++;
10164:                 }
10165:                 $numstudents ++;
10166:             }
10167:         }
10168:     }
10169:     $r->print(
10170:         '<p>'
10171:        .&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).',
10172:             '<b>',
10173:             $numstudents,
10174:             '</b>',
10175:             $env{'form.scantron_maxbubble'})
10176:        .'</p>'
10177:     );
10178:     $r->print('<p>'
10179:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10180:              .'<br />'
10181:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10182:              .'</p>'
10183:     );
10184:     if ($passed) {
10185:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10186:         $r->print(&Apache::loncommon::start_data_table()."\n".
10187:                  &Apache::loncommon::start_data_table_header_row()."\n".
10188:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10189:                  &Apache::loncommon::end_data_table_header_row()."\n".
10190:                  $okstudents."\n".
10191:                  &Apache::loncommon::end_data_table().'<br />');
10192:     }
10193:     if ($failed) {
10194:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10195:         $r->print(&Apache::loncommon::start_data_table()."\n".
10196:                  &Apache::loncommon::start_data_table_header_row()."\n".
10197:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10198:                  &Apache::loncommon::end_data_table_header_row()."\n".
10199:                  $badstudents."\n".
10200:                  &Apache::loncommon::end_data_table()).'<br />'.
10201:                  &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.');  
10202:     }
10203:     $r->print('</form><br />');
10204:     return;
10205: }
10206: 
10207: sub verify_scantron_grading {
10208:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10209:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10210:         $respnumlookup,$startline) = @_;
10211:     my ($record,%expected,%startpos);
10212:     return ($counter,$record) if (!ref($resource));
10213:     return ($counter,$record) if (!$resource->is_problem());
10214:     my $symb = $resource->symb();
10215:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10216:     foreach my $part_id (@{$partids}) {
10217:         $counter ++;
10218:         $expected{$part_id} = 0;
10219:         my $respnum = $counter;
10220:         if ($randomorder || $randompick) {
10221:             $respnum = $respnumlookup->{$counter};
10222:             $startpos{$part_id} = $startline->{$counter} + 1;
10223:         } else {
10224:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10225:         }
10226:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10227:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10228:             foreach my $item (@sub_lines) {
10229:                 $expected{$part_id} += $item;
10230:             }
10231:         } else {
10232:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10233:         }
10234:     }
10235:     if ($symb) {
10236:         my %recorded;
10237:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10238:         if ($returnhash{'version'}) {
10239:             my %lasthash=();
10240:             my $version;
10241:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10242:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10243:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10244:                 }
10245:             }
10246:             foreach my $key (keys(%lasthash)) {
10247:                 if ($key =~ /\.scantron$/) {
10248:                     my $value = &unescape($lasthash{$key});
10249:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10250:                     if ($value eq '') {
10251:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10252:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10253:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10254:                             }
10255:                         }
10256:                     } else {
10257:                         my @tocheck;
10258:                         my @items = split(//,$value);
10259:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10260:                             ($scantron_config->{'Qon'} eq 'number')) {
10261:                             if (@items < $expected{$part_id}) {
10262:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10263:                                 my @singles = split(//,$fragment);
10264:                                 foreach my $pos (@singles) {
10265:                                     if ($pos eq ' ') {
10266:                                         push(@tocheck,$pos);
10267:                                     } else {
10268:                                         my $next = shift(@items);
10269:                                         push(@tocheck,$next);
10270:                                     }
10271:                                 }
10272:                             } else {
10273:                                 @tocheck = @items;
10274:                             }
10275:                             foreach my $letter (@tocheck) {
10276:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10277:                                     if ($letter !~ /^[A-J]$/) {
10278:                                         $letter = $scantron_config->{'Qoff'};
10279:                                     }
10280:                                     $recorded{$part_id} .= $letter;
10281:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10282:                                     my $digit;
10283:                                     if ($letter !~ /^[A-J]$/) {
10284:                                         $digit = $scantron_config->{'Qoff'};
10285:                                     } else {
10286:                                         $digit = $lettdig->{$letter};
10287:                                     }
10288:                                     $recorded{$part_id} .= $digit;
10289:                                 }
10290:                             }
10291:                         } else {
10292:                             @tocheck = @items;
10293:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10294:                                 my $curr_sub = shift(@tocheck);
10295:                                 my $digit;
10296:                                 if ($curr_sub =~ /^[A-J]$/) {
10297:                                     $digit = $lettdig->{$curr_sub}-1;
10298:                                 }
10299:                                 if ($curr_sub eq 'J') {
10300:                                     $digit += scalar($numletts);
10301:                                 }
10302:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10303:                                     if ($j == $digit) {
10304:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10305:                                     } else {
10306:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10307:                                     }
10308:                                 }
10309:                             }
10310:                         }
10311:                     }
10312:                 }
10313:             }
10314:         }
10315:         foreach my $part_id (@{$partids}) {
10316:             if ($recorded{$part_id} eq '') {
10317:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10318:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10319:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10320:                     }
10321:                 }
10322:             }
10323:             $record .= $recorded{$part_id};
10324:         }
10325:     }
10326:     return ($counter,$record);
10327: }
10328: 
10329: #-------- end of section for handling grading scantron forms -------
10330: #
10331: #-------------------------------------------------------------------
10332: 
10333: #-------------------------- Menu interface -------------------------
10334: #
10335: #--- Href with symb and command ---
10336: 
10337: sub href_symb_cmd {
10338:     my ($symb,$cmd)=@_;
10339:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10340: }
10341: 
10342: sub grading_menu {
10343:     my ($request,$symb) = @_;
10344:     if (!$symb) {return '';}
10345: 
10346:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10347:                   'command'=>'individual');
10348:     
10349:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10350: 
10351:     $fields{'command'}='ungraded';
10352:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10353: 
10354:     $fields{'command'}='table';
10355:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10356: 
10357:     $fields{'command'}='all_for_one';
10358:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10359: 
10360:     $fields{'command'}='downloadfilesselect';
10361:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10362: 
10363:     $fields{'command'} = 'csvform';
10364:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10365:     
10366:     $fields{'command'} = 'processclicker';
10367:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10368:     
10369:     $fields{'command'} = 'scantron_selectphase';
10370:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10371: 
10372:     $fields{'command'} = 'initialverifyreceipt';
10373:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10374:     
10375:     my @menu = ({	categorytitle=>'Hand Grading',
10376:             items =>[
10377:                         {	linktext => 'Select individual students to grade',
10378:                     		url => $url1a,
10379:                     		permission => 'F',
10380:                     		icon => 'grade_students.png',
10381:                     		linktitle => 'Grade current resource for a selection of students.'
10382:                         }, 
10383:                         {       linktext => 'Grade ungraded submissions',
10384:                                 url => $url1b,
10385:                                 permission => 'F',
10386:                                 icon => 'ungrade_sub.png',
10387:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10388:                         },
10389: 
10390:                         {       linktext => 'Grading table',
10391:                                 url => $url1c,
10392:                                 permission => 'F',
10393:                                 icon => 'grading_table.png',
10394:                                 linktitle => 'Grade current resource for all students.'
10395:                         },
10396:                         {       linktext => 'Grade page/folder for one student',
10397:                                 url => $url1d,
10398:                                 permission => 'F',
10399:                                 icon => 'grade_PageFolder.png',
10400:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10401:                         },
10402:                         {       linktext => 'Download submissions',
10403:                                 url => $url1e,
10404:                                 permission => 'F',
10405:                                 icon => 'download_sub.png',
10406:                                 linktitle => 'Download all students submissions.'
10407:                         }]},
10408:                          { categorytitle=>'Automated Grading',
10409:                items =>[
10410: 
10411:                 	    {	linktext => 'Upload Scores',
10412:                     		url => $url2,
10413:                     		permission => 'F',
10414:                     		icon => 'uploadscores.png',
10415:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10416:                 	    },
10417:                 	    {	linktext => 'Process Clicker',
10418:                     		url => $url3,
10419:                     		permission => 'F',
10420:                     		icon => 'addClickerInfoFile.png',
10421:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10422:                 	    },
10423:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10424:                     		url => $url4,
10425:                     		permission => 'F',
10426:                     		icon => 'bubblesheet.png',
10427:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10428:                 	    },
10429:                             {   linktext => 'Verify Receipt Number',
10430:                                 url => $url5,
10431:                                 permission => 'F',
10432:                                 icon => 'receipt_number.png',
10433:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10434:                             }
10435: 
10436:                     ]
10437:             });
10438: 
10439:     # Create the menu
10440:     my $Str;
10441:     $Str .= '<form method="post" action="" name="gradingMenu">';
10442:     $Str .= '<input type="hidden" name="command" value="" />'.
10443:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10444: 
10445:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10446:     return $Str;    
10447: }
10448: 
10449: sub ungraded {
10450:     my ($request)=@_;
10451:     &submit_options($request);
10452: }
10453: 
10454: sub submit_options_sequence {
10455:     my ($request,$symb) = @_;
10456:     if (!$symb) {return '';}
10457:     &commonJSfunctions($request);
10458:     my $result;
10459: 
10460:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10461:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10462:     $result.=&selectfield(0).
10463:             '<input type="hidden" name="command" value="pickStudentPage" />
10464:             <div>
10465:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10466:             </div>
10467:         </div>
10468:   </form>';
10469:     return $result;
10470: }
10471: 
10472: sub submit_options_table {
10473:     my ($request,$symb) = @_;
10474:     if (!$symb) {return '';}
10475:     &commonJSfunctions($request);
10476:     my $is_tool = ($symb =~ /ext\.tool$/);
10477:     my $result;
10478: 
10479:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10480:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10481: 
10482:     $result.=&selectfield(1,$is_tool).
10483:             '<input type="hidden" name="command" value="viewgrades" />
10484:             <div>
10485:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10486:             </div>
10487:         </div>
10488:   </form>';
10489:     return $result;
10490: }
10491: 
10492: sub submit_options_download {
10493:     my ($request,$symb) = @_;
10494:     if (!$symb) {return '';}
10495: 
10496:     my $res_error;
10497:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10498:         &response_type($symb,\$res_error);
10499:     if ($res_error) {
10500:         $request->print(&mt('An error occurred retrieving response types'));
10501:         return;
10502:     }
10503:     unless ($numessay) {
10504:         $request->print(&mt('No essayresponse items found'));
10505:         return;
10506:     }
10507:     my $table;
10508:     if (ref($partlist) eq 'ARRAY') {
10509:         if (scalar(@$partlist) > 1 ) {
10510:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10511:         }
10512:     }
10513: 
10514:     my $is_tool = ($symb =~ /ext\.tool$/);
10515:     &commonJSfunctions($request);
10516: 
10517:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10518:                $table."\n".
10519:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10520:     $result.='
10521: <h2>
10522:   '.&mt('Select Students for whom to Download Submissions').'
10523: </h2>'.&selectfield(1,$is_tool).'
10524:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10525:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10526:             </div>
10527:           </div>
10528: 
10529: 
10530:   </form>';
10531:     return $result;
10532: }
10533: 
10534: #--- Displays the submissions first page -------
10535: sub submit_options {
10536:     my ($request,$symb) = @_;
10537:     if (!$symb) {return '';}
10538: 
10539:     my $is_tool = ($symb =~ /ext\.tool$/);
10540:     &commonJSfunctions($request);
10541:     my $result;
10542: 
10543:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10544: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10545:     $result.=&selectfield(1,$is_tool).'
10546:                 <input type="hidden" name="command" value="submission" /> 
10547: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10548:             </div>
10549:           </div>
10550:   </form>';
10551:     return $result;
10552: }
10553: 
10554: sub selectfield {
10555:    my ($full,$is_tool)=@_;
10556:    my %options;
10557:    if ($is_tool) {
10558:        %options =
10559:            (&transtatus_options,
10560:             'select_form_order' => ['yes','incorrect','all']);
10561:    } else {
10562:        %options = 
10563:            (&substatus_options,
10564:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10565:    }
10566:    my $result='<div class="LC_columnSection">
10567:   
10568:     <fieldset>
10569:       <legend>
10570:        '.&mt('Sections').'
10571:       </legend>
10572:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10573:     </fieldset>
10574:   
10575:     <fieldset>
10576:       <legend>
10577:         '.&mt('Groups').'
10578:       </legend>
10579:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10580:     </fieldset>
10581:   
10582:     <fieldset>
10583:       <legend>
10584:         '.&mt('Access Status').'
10585:       </legend>
10586:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10587:     </fieldset>';
10588:     if ($full) {
10589:         my $heading = &mt('Submission Status');
10590:         if ($is_tool) {
10591:             $heading = &mt('Transaction Status');
10592:         }
10593:         $result.='
10594:     <fieldset>
10595:       <legend>
10596:         '.$heading.'
10597:       </legend>'.
10598:        &Apache::loncommon::select_form('all','submitonly',\%options).
10599:    '</fieldset>';
10600:     }
10601:     $result.='</div><br />';
10602:     return $result;
10603: }
10604: 
10605: sub substatus_options {
10606:     return &Apache::lonlocal::texthash(
10607:                                       'yes'       => 'with submissions',
10608:                                       'queued'    => 'in grading queue',
10609:                                       'graded'    => 'with ungraded submissions',
10610:                                       'incorrect' => 'with incorrect submissions',
10611:                                       'all'       => 'with any status',
10612:                                       );
10613: }
10614: 
10615: sub transtatus_options {
10616:     return &Apache::lonlocal::texthash(
10617:                                        'yes'       => 'with score transactions',
10618:                                        'incorrect' => 'with less than full credit',
10619:                                        'all'       => 'with any status',
10620:                                       );
10621: }
10622: 
10623: sub reset_perm {
10624:     undef(%perm);
10625: }
10626: 
10627: sub init_perm {
10628:     &reset_perm();
10629:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10630: 
10631: 	my $scope = $env{'request.course.id'};
10632: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10633: 
10634: 	    $scope .= '/'.$env{'request.course.sec'};
10635: 	    if ( $perm{$test_perm}=
10636: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10637: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10638: 	    } else {
10639: 		delete($perm{$test_perm});
10640: 	    }
10641: 	}
10642:     }
10643: }
10644: 
10645: sub init_old_essays {
10646:     my ($symb,$apath,$adom,$aname) = @_;
10647:     if ($symb ne '') {
10648:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10649:         if (keys(%essays) > 0) {
10650:             $old_essays{$symb} = \%essays;
10651:         }
10652:     }
10653:     return;
10654: }
10655: 
10656: sub reset_old_essays {
10657:     undef(%old_essays);
10658: }
10659: 
10660: sub gather_clicker_ids {
10661:     my %clicker_ids;
10662: 
10663:     my $classlist = &Apache::loncoursedata::get_classlist();
10664: 
10665:     # Set up a couple variables.
10666:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10667:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10668:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10669: 
10670:     foreach my $student (keys(%$classlist)) {
10671:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10672:         my $username = $classlist->{$student}->[$username_idx];
10673:         my $domain   = $classlist->{$student}->[$domain_idx];
10674:         my $clickers =
10675: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10676:         foreach my $id (split(/\,/,$clickers)) {
10677:             $id=~s/^[\#0]+//;
10678:             $id=~s/[\-\:]//g;
10679:             if (exists($clicker_ids{$id})) {
10680: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10681:             } else {
10682: 		$clicker_ids{$id}=$username.':'.$domain;
10683:             }
10684:         }
10685:     }
10686:     return %clicker_ids;
10687: }
10688: 
10689: sub gather_adv_clicker_ids {
10690:     my %clicker_ids;
10691:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10692:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10693:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10694:     foreach my $element (sort(keys(%coursepersonnel))) {
10695:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10696:             my ($puname,$pudom)=split(/\:/,$person);
10697:             my $clickers =
10698: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10699:             foreach my $id (split(/\,/,$clickers)) {
10700: 		$id=~s/^[\#0]+//;
10701:                 $id=~s/[\-\:]//g;
10702: 		if (exists($clicker_ids{$id})) {
10703: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10704: 		} else {
10705: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10706: 		}
10707:             }
10708:         }
10709:     }
10710:     return %clicker_ids;
10711: }
10712: 
10713: sub clicker_grading_parameters {
10714:     return ('gradingmechanism' => 'scalar',
10715:             'upfiletype' => 'scalar',
10716:             'specificid' => 'scalar',
10717:             'pcorrect' => 'scalar',
10718:             'pincorrect' => 'scalar');
10719: }
10720: 
10721: sub process_clicker {
10722:     my ($r,$symb)=@_;
10723:     if (!$symb) {return '';}
10724:     my $result=&checkforfile_js();
10725:     $result.=&Apache::loncommon::start_data_table().
10726:              &Apache::loncommon::start_data_table_header_row().
10727:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10728:              &Apache::loncommon::end_data_table_header_row().
10729:              &Apache::loncommon::start_data_table_row()."<td>\n";
10730: # Attempt to restore parameters from last session, set defaults if not present
10731:     my %Saveable_Parameters=&clicker_grading_parameters();
10732:     &Apache::loncommon::restore_course_settings('grades_clicker',
10733:                                                  \%Saveable_Parameters);
10734:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10735:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10736:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10737:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10738: 
10739:     my %checked;
10740:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10741:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10742:           $checked{$gradingmechanism}=' checked="checked"';
10743:        }
10744:     }
10745: 
10746:     my $upload=&mt("Evaluate File");
10747:     my $type=&mt("Type");
10748:     my $attendance=&mt("Award points just for participation");
10749:     my $personnel=&mt("Correctness determined from response by course personnel");
10750:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10751:     my $given=&mt("Correctness determined from given list of answers").' '.
10752:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10753:     my $pcorrect=&mt("Percentage points for correct solution");
10754:     my $pincorrect=&mt("Percentage points for incorrect solution");
10755:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10756: 						   {'iclicker' => 'i>clicker',
10757:                                                     'interwrite' => 'interwrite PRS',
10758:                                                     'turning' => 'Turning Technologies'});
10759:     $symb = &Apache::lonenc::check_encrypt($symb);
10760:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10761: function sanitycheck() {
10762: // Accept only integer percentages
10763:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10764:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10765: // Find out grading choice
10766:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10767:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10768:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10769:       }
10770:    }
10771: // By default, new choice equals user selection
10772:    newgradingchoice=gradingchoice;
10773: // Not good to give more points for false answers than correct ones
10774:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10775:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10776:    }
10777: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10778:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10779:       document.forms.gradesupload.pcorrect.value=100;
10780:       document.forms.gradesupload.pincorrect.value=100;
10781:    }
10782: // If the values are different, cannot be attendance only
10783:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10784:        (gradingchoice=='attendance')) {
10785:        newgradingchoice='personnel';
10786:    }
10787: // Change grading choice to new one
10788:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10789:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10790:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10791:       } else {
10792:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10793:       }
10794:    }
10795: // Remember the old state
10796:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10797: }
10798: ENDUPFORM
10799:     $result.= <<ENDUPFORM;
10800: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10801: <input type="hidden" name="symb" value="$symb" />
10802: <input type="hidden" name="command" value="processclickerfile" />
10803: <input type="file" name="upfile" size="50" />
10804: <br /><label>$type: $selectform</label>
10805: ENDUPFORM
10806:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10807:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10808:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10809: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10810: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10811: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10812: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10813: <br />&nbsp;&nbsp;&nbsp;
10814: <input type="text" name="givenanswer" size="50" />
10815: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10816: ENDGRADINGFORM
10817:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10818:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10819:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10820: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10821: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10822: </form>
10823: ENDPERCFORM
10824:     $result.='</td>'.
10825:              &Apache::loncommon::end_data_table_row().
10826:              &Apache::loncommon::end_data_table();
10827:     return $result;
10828: }
10829: 
10830: sub process_clicker_file {
10831:     my ($r,$symb) = @_;
10832:     if (!$symb) {return '';}
10833: 
10834:     my %Saveable_Parameters=&clicker_grading_parameters();
10835:     &Apache::loncommon::store_course_settings('grades_clicker',
10836:                                               \%Saveable_Parameters);
10837:     my $result='';
10838:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10839: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10840: 	return $result;
10841:     }
10842:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10843:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10844:         return $result;
10845:     }
10846:     my $foundgiven=0;
10847:     if ($env{'form.gradingmechanism'} eq 'given') {
10848:         $env{'form.givenanswer'}=~s/^\s*//gs;
10849:         $env{'form.givenanswer'}=~s/\s*$//gs;
10850:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10851:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10852:         my @answers=split(/\,/,$env{'form.givenanswer'});
10853:         $foundgiven=$#answers+1;
10854:     }
10855:     my %clicker_ids=&gather_clicker_ids();
10856:     my %correct_ids;
10857:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10858: 	%correct_ids=&gather_adv_clicker_ids();
10859:     }
10860:     if ($env{'form.gradingmechanism'} eq 'specific') {
10861: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10862: 	   $correct_id=~tr/a-z/A-Z/;
10863: 	   $correct_id=~s/\s//gs;
10864: 	   $correct_id=~s/^[\#0]+//;
10865:            $correct_id=~s/[\-\:]//g;
10866:            if ($correct_id) {
10867: 	      $correct_ids{$correct_id}='specified';
10868:            }
10869:         }
10870:     }
10871:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10872: 	$result.=&mt('Score based on attendance only');
10873:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10874:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10875:     } else {
10876: 	my $number=0;
10877: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10878: 	foreach my $id (sort(keys(%correct_ids))) {
10879: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10880: 	    if ($correct_ids{$id} eq 'specified') {
10881: 		$result.=&mt('specified');
10882: 	    } else {
10883: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10884: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10885: 	    }
10886: 	    $number++;
10887: 	}
10888:         $result.="</p>\n";
10889:         if ($number==0) {
10890:             $result .=
10891:                  &Apache::lonhtmlcommon::confirm_success(
10892:                      &mt('No IDs found to determine correct answer'),1);
10893:             return $result;
10894:         }
10895:     }
10896:     if (length($env{'form.upfile'}) < 2) {
10897:         $result .=
10898:             &Apache::lonhtmlcommon::confirm_success(
10899:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10900:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10901:         return $result;
10902:     }
10903:     my $mimetype;
10904:     if ($env{'form.upfiletype'} eq 'iclicker') {
10905:         my $mm = new File::MMagic;
10906:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10907:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10908:             $result.= '<p>'.
10909:                 &Apache::lonhtmlcommon::confirm_success(
10910:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10911:             return $result;
10912:         }
10913:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10914:         $result .= '<p>'.
10915:             &Apache::lonhtmlcommon::confirm_success(
10916:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10917:         return $result;
10918:     }
10919: 
10920: # Were able to get all the info needed, now analyze the file
10921: 
10922:     $result.=&Apache::loncommon::studentbrowser_javascript();
10923:     $symb = &Apache::lonenc::check_encrypt($symb);
10924:     $result.=&Apache::loncommon::start_data_table().
10925:              &Apache::loncommon::start_data_table_header_row().
10926:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10927:              &Apache::loncommon::end_data_table_header_row().
10928:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10929: <td>
10930: <form method="post" action="/adm/grades" name="clickeranalysis">
10931: <input type="hidden" name="symb" value="$symb" />
10932: <input type="hidden" name="command" value="assignclickergrades" />
10933: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10934: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10935: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10936: ENDHEADER
10937:     if ($env{'form.gradingmechanism'} eq 'given') {
10938:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10939:     } 
10940:     my %responses;
10941:     my @questiontitles;
10942:     my $errormsg='';
10943:     my $number=0;
10944:     if ($env{'form.upfiletype'} eq 'iclicker') {
10945:         if ($mimetype eq 'text/plain') {
10946:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10947:         } elsif ($mimetype eq 'text/html') {
10948:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10949:         }
10950:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10951:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10952:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10953:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10954:     }
10955:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10956:              '<input type="hidden" name="number" value="'.$number.'" />'.
10957:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10958:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10959:              '<br />';
10960:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10961:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10962:        return $result;
10963:     } 
10964: # Remember Question Titles
10965: # FIXME: Possibly need delimiter other than ":"
10966:     for (my $i=0;$i<$number;$i++) {
10967:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10968:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10969:     }
10970:     my $correct_count=0;
10971:     my $student_count=0;
10972:     my $unknown_count=0;
10973: # Match answers with usernames
10974: # FIXME: Possibly need delimiter other than ":"
10975:     foreach my $id (keys(%responses)) {
10976:        if ($correct_ids{$id}) {
10977:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10978:           $correct_count++;
10979:        } elsif ($clicker_ids{$id}) {
10980:           if ($clicker_ids{$id}=~/\,/) {
10981: # More than one user with the same clicker!
10982:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10983:                            &Apache::loncommon::start_data_table_row()."<td>".
10984:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10985:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10986:                            "<select name='multi".$id."'>";
10987:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10988:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10989:              }
10990:              $result.='</select>';
10991:              $unknown_count++;
10992:           } else {
10993: # Good: found one and only one user with the right clicker
10994:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10995:              $student_count++;
10996:           }
10997:        } else {
10998:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10999:                            &Apache::loncommon::start_data_table_row()."<td>".
11000:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11001:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11002:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11003:                    "\n".&mt("Domain").": ".
11004:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11005:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11006:           $unknown_count++;
11007:        }
11008:     }
11009:     $result.='<hr />'.
11010:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11011:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11012:        if ($correct_count==0) {
11013:           $errormsg.="Found no correct answers for grading!";
11014:        } elsif ($correct_count>1) {
11015:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11016:        }
11017:     }
11018:     if ($number<1) {
11019:        $errormsg.="Found no questions.";
11020:     }
11021:     if ($errormsg) {
11022:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11023:     } else {
11024:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11025:     }
11026:     $result.='</form></td>'.
11027:              &Apache::loncommon::end_data_table_row().
11028:              &Apache::loncommon::end_data_table();
11029:     return $result;
11030: }
11031: 
11032: sub iclicker_eval {
11033:     my ($questiontitles,$responses)=@_;
11034:     my $number=0;
11035:     my $errormsg='';
11036:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11037:         my %components=&Apache::loncommon::record_sep($line);
11038:         my @entries=map {$components{$_}} (sort(keys(%components)));
11039: 	if ($entries[0] eq 'Question') {
11040: 	    for (my $i=3;$i<$#entries;$i+=6) {
11041: 		$$questiontitles[$number]=$entries[$i];
11042: 		$number++;
11043: 	    }
11044: 	}
11045: 	if ($entries[0]=~/^\#/) {
11046: 	    my $id=$entries[0];
11047: 	    my @idresponses;
11048: 	    $id=~s/^[\#0]+//;
11049: 	    for (my $i=0;$i<$number;$i++) {
11050: 		my $idx=3+$i*6;
11051:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11052: 		push(@idresponses,$entries[$idx]);
11053: 	    }
11054: 	    $$responses{$id}=join(',',@idresponses);
11055: 	}
11056:     }
11057:     return ($errormsg,$number);
11058: }
11059: 
11060: sub iclickerxml_eval {
11061:     my ($questiontitles,$responses)=@_;
11062:     my $number=0;
11063:     my $errormsg='';
11064:     my @state;
11065:     my %respbyid;
11066:     my $p = HTML::Parser->new
11067:     (
11068:         xml_mode => 1,
11069:         start_h =>
11070:             [sub {
11071:                  my ($tagname,$attr) = @_;
11072:                  push(@state,$tagname);
11073:                  if ("@state" eq "ssn p") {
11074:                      my $title = $attr->{qn};
11075:                      $title =~ s/(^\s+|\s+$)//g;
11076:                      $questiontitles->[$number]=$title;
11077:                  } elsif ("@state" eq "ssn p v") {
11078:                      my $id = $attr->{id};
11079:                      my $entry = $attr->{ans};
11080:                      $id=~s/^[\#0]+//;
11081:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11082:                      $respbyid{$id}[$number] = $entry;
11083:                  }
11084:             }, "tagname, attr"],
11085:          end_h =>
11086:                [sub {
11087:                    my ($tagname) = @_;
11088:                    if ("@state" eq "ssn p") {
11089:                        $number++;
11090:                    }
11091:                    pop(@state);
11092:                 }, "tagname"],
11093:     );
11094: 
11095:     $p->parse($env{'form.upfile'});
11096:     $p->eof;
11097:     foreach my $id (keys(%respbyid)) {
11098:         $responses->{$id}=join(',',@{$respbyid{$id}});
11099:     }
11100:     return ($errormsg,$number);
11101: }
11102: 
11103: sub interwrite_eval {
11104:     my ($questiontitles,$responses)=@_;
11105:     my $number=0;
11106:     my $errormsg='';
11107:     my $skipline=1;
11108:     my $questionnumber=0;
11109:     my %idresponses=();
11110:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11111:         my %components=&Apache::loncommon::record_sep($line);
11112:         my @entries=map {$components{$_}} (sort(keys(%components)));
11113:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11114:         if ($entries[1] eq 'Response') { $skipline=1; }
11115:         next if $skipline;
11116:         if ($entries[0]!=$questionnumber) {
11117:            $questionnumber=$entries[0];
11118:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11119:            $number++;
11120:         }
11121:         my $id=$entries[4];
11122:         $id=~s/^[\#0]+//;
11123:         $id=~s/^v\d*\://i;
11124:         $id=~s/[\-\:]//g;
11125:         $idresponses{$id}[$number]=$entries[6];
11126:     }
11127:     foreach my $id (keys(%idresponses)) {
11128:        $$responses{$id}=join(',',@{$idresponses{$id}});
11129:        $$responses{$id}=~s/^\s*\,//;
11130:     }
11131:     return ($errormsg,$number);
11132: }
11133: 
11134: sub turning_eval {
11135:     my ($questiontitles,$responses)=@_;
11136:     my $number=0;
11137:     my $errormsg='';
11138:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11139:         my %components=&Apache::loncommon::record_sep($line);
11140:         my @entries=map {$components{$_}} (sort(keys(%components)));
11141:         if ($#entries>$number) { $number=$#entries; }
11142:         my $id=$entries[0];
11143:         my @idresponses;
11144:         $id=~s/^[\#0]+//;
11145:         unless ($id) { next; }
11146:         for (my $idx=1;$idx<=$#entries;$idx++) {
11147:             $entries[$idx]=~s/\,/\;/g;
11148:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11149:             push(@idresponses,$entries[$idx]);
11150:         }
11151:         $$responses{$id}=join(',',@idresponses);
11152:     }
11153:     for (my $i=1; $i<=$number; $i++) {
11154:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11155:     }
11156:     return ($errormsg,$number);
11157: }
11158: 
11159: 
11160: sub assign_clicker_grades {
11161:     my ($r,$symb) = @_;
11162:     if (!$symb) {return '';}
11163: # See which part we are saving to
11164:     my $res_error;
11165:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11166:     if ($res_error) {
11167:         return &navmap_errormsg();
11168:     }
11169: # FIXME: This should probably look for the first handgradeable part
11170:     my $part=$$partlist[0];
11171: # Start screen output
11172:     my $result = &Apache::loncommon::start_data_table().
11173:                  &Apache::loncommon::start_data_table_header_row().
11174:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11175:                  &Apache::loncommon::end_data_table_header_row().
11176:                  &Apache::loncommon::start_data_table_row().'<td>';
11177: # Get correct result
11178: # FIXME: Possibly need delimiter other than ":"
11179:     my @correct=();
11180:     my $gradingmechanism=$env{'form.gradingmechanism'};
11181:     my $number=$env{'form.number'};
11182:     if ($gradingmechanism ne 'attendance') {
11183:        foreach my $key (keys(%env)) {
11184:           if ($key=~/^form\.correct\:/) {
11185:              my @input=split(/\,/,$env{$key});
11186:              for (my $i=0;$i<=$#input;$i++) {
11187:                  if (($correct[$i]) && ($input[$i]) &&
11188:                      ($correct[$i] ne $input[$i])) {
11189:                     $result.='<br /><span class="LC_warning">'.
11190:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11191:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11192:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11193:                     $correct[$i]=$input[$i];
11194:                  }
11195:              }
11196:           }
11197:        }
11198:        for (my $i=0;$i<$number;$i++) {
11199:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11200:              $result.='<br /><span class="LC_error">'.
11201:                       &mt('No correct result given for question "[_1]"!',
11202:                           $env{'form.question:'.$i}).'</span>';
11203:           }
11204:        }
11205:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11206:     }
11207: # Start grading
11208:     my $pcorrect=$env{'form.pcorrect'};
11209:     my $pincorrect=$env{'form.pincorrect'};
11210:     my $storecount=0;
11211:     my %users=();
11212:     foreach my $key (keys(%env)) {
11213:        my $user='';
11214:        if ($key=~/^form\.student\:(.*)$/) {
11215:           $user=$1;
11216:        }
11217:        if ($key=~/^form\.unknown\:(.*)$/) {
11218:           my $id=$1;
11219:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11220:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11221:           } elsif ($env{'form.multi'.$id}) {
11222:              $user=$env{'form.multi'.$id};
11223:           }
11224:        }
11225:        if ($user) {
11226:           if ($users{$user}) {
11227:              $result.='<br /><span class="LC_warning">'.
11228:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11229:                       '</span><br />';
11230:           }
11231:           $users{$user}=1; 
11232:           my @answer=split(/\,/,$env{$key});
11233:           my $sum=0;
11234:           my $realnumber=$number;
11235:           for (my $i=0;$i<$number;$i++) {
11236:              if  ($correct[$i] eq '-') {
11237:                 $realnumber--;
11238:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11239:                 if ($gradingmechanism eq 'attendance') {
11240:                    $sum+=$pcorrect;
11241:                 } elsif ($correct[$i] eq '*') {
11242:                    $sum+=$pcorrect;
11243:                 } else {
11244: # We actually grade if correct or not
11245:                    my $increment=$pincorrect;
11246: # Special case: numerical answer "0"
11247:                    if ($correct[$i] eq '0') {
11248:                       if ($answer[$i]=~/^[0\.]+$/) {
11249:                          $increment=$pcorrect;
11250:                       }
11251: # General numerical answer, both evaluate to something non-zero
11252:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11253:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11254:                          $increment=$pcorrect;
11255:                       }
11256: # Must be just alphanumeric
11257:                    } elsif ($answer[$i] eq $correct[$i]) {
11258:                       $increment=$pcorrect;
11259:                    }
11260:                    $sum+=$increment;
11261:                 }
11262:              }
11263:           }
11264:           my $ave=$sum/(100*$realnumber);
11265: # Store
11266:           my ($username,$domain)=split(/\:/,$user);
11267:           my %grades=();
11268:           $grades{"resource.$part.solved"}='correct_by_override';
11269:           $grades{"resource.$part.awarded"}=$ave;
11270:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11271:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11272:                                                  $env{'request.course.id'},
11273:                                                  $domain,$username);
11274:           if ($returncode ne 'ok') {
11275:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11276:           } else {
11277:              $storecount++;
11278:           }
11279:        }
11280:     }
11281: # We are done
11282:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11283:              '</td>'.
11284:              &Apache::loncommon::end_data_table_row().
11285:              &Apache::loncommon::end_data_table();
11286:     return $result;
11287: }
11288: 
11289: sub navmap_errormsg {
11290:     return '<div class="LC_error">'.
11291:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11292:            &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>').
11293:            '</div>';
11294: }
11295: 
11296: sub startpage {
11297:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
11298:     my %args;
11299:     if ($onload) {
11300:          my %loaditems = (
11301:                         'onload' => $onload,
11302:                       );
11303:          $args{'add_entries'} = \%loaditems;
11304:     }
11305:     if ($nomenu) {
11306:         $args{'only_body'} = 1; 
11307:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
11308:     } else {
11309:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11310:         $args{'bread_crumbs'} = $crumbs;
11311:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
11312:         if ($env{'request.course.id'}) {
11313:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11314:         }
11315:     }
11316:     unless ($nodisplayflag) {
11317:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11318:     }
11319: }
11320: 
11321: sub select_problem {
11322:     my ($r)=@_;
11323:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11324:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11325:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11326:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11327: }
11328: 
11329: sub handler {
11330:     my $request=$_[0];
11331:     &reset_caches();
11332:     if ($request->header_only) {
11333:         &Apache::loncommon::content_type($request,'text/html');
11334:         $request->send_http_header;
11335:         return OK;
11336:     }
11337:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11338: 
11339: # see what command we need to execute
11340: 
11341:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11342:     my $command=$commands[0];
11343: 
11344:     &init_perm();
11345:     if (!$env{'request.course.id'}) {
11346:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11347:                 ($command =~ /^scantronupload/)) {
11348:             # Not in a course.
11349:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11350:             return HTTP_NOT_ACCEPTABLE;
11351:         }
11352:     } elsif (!%perm) {
11353:         $request->internal_redirect('/adm/quickgrades');
11354:         return OK;
11355:     }
11356:     &Apache::loncommon::content_type($request,'text/html');
11357:     $request->send_http_header;
11358: 
11359:     if ($#commands > 0) {
11360: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11361:     }
11362: 
11363: # see what the symb is
11364: 
11365:     my $symb=$env{'form.symb'};
11366:     unless ($symb) {
11367:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11368:        $symb=&Apache::lonnet::symbread($url);
11369:     }
11370:     &Apache::lonenc::check_decrypt(\$symb);
11371: 
11372:     $ssi_error = 0;
11373:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11374: #
11375: # Not called from a resource, but inside a course
11376: #    
11377:         &startpage($request,undef,[],1,1);
11378:         &select_problem($request);
11379:     } else {
11380: 	if ($command eq 'submission' && $perm{'vgr'}) {
11381:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11382:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11383:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11384:                     &choose_task_version_form($symb,$env{'form.student'},
11385:                                               $env{'form.userdom'});
11386:             }
11387:             my $divforres;
11388:             if ($env{'form.student'} eq '') {
11389:                 $js .= &part_selector_js();
11390:                 $onload = "toggleParts('gradesub');";
11391:             } else {
11392:                 $divforres = 1;
11393:             }
11394:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
11395:             if ($versionform) {
11396:                 $request->print($versionform);
11397:             }
11398: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11399:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11400:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11401:                 &choose_task_version_form($symb,$env{'form.student'},
11402:                                           $env{'form.userdom'},
11403:                                           $env{'form.inhibitmenu'});
11404:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
11405:             if ($versionform) {
11406:                 $request->print($versionform);
11407:             }
11408:             $request->print('<br clear="all" />');
11409:             $request->print(&show_previous_task_version($request,$symb));
11410: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11411:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11412:                                        {href=>'',text=>'Select student'}],1,1);
11413: 	    &pickStudentPage($request,$symb);
11414: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11415:             &startpage($request,$symb,
11416:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11417:                                        {href=>'',text=>'Select student'},
11418:                                        {href=>'',text=>'Grade student'}],1,1);
11419: 	    &displayPage($request,$symb);
11420: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11421:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11422:                                        {href=>'',text=>'Select student'},
11423:                                        {href=>'',text=>'Grade student'},
11424:                                        {href=>'',text=>'Store grades'}],1,1);
11425: 	    &updateGradeByPage($request,$symb);
11426: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11427:             &startpage($request,$symb,[{href=>'',text=>'...'},
11428:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
11429: 	    &processGroup($request,$symb);
11430: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11431:             &startpage($request,$symb);
11432: 	    $request->print(&grading_menu($request,$symb));
11433: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11434:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11435: 	    $request->print(&submit_options($request,$symb));
11436:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11437:             my $js = &part_selector_js();
11438:             my $onload = "toggleParts('gradesub');";
11439:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11440:                        undef,undef,undef,undef,undef,$js,$onload);
11441:             $request->print(&listStudents($request,$symb,'graded'));
11442:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11443:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11444:             $request->print(&submit_options_table($request,$symb));
11445:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11446:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11447:             $request->print(&submit_options_sequence($request,$symb));
11448: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11449:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11450: 	    $request->print(&viewgrades($request,$symb));
11451: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11452:             &startpage($request,$symb,[{href=>'',text=>'...'},
11453:                                        {href=>'',text=>'Store grades'}]);
11454: 	    $request->print(&processHandGrade($request,$symb));
11455: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11456:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11457:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11458:                                                                              text=>"Modify grades"},
11459:                                        {href=>'', text=>"Store grades"}]);
11460: 	    $request->print(&editgrades($request,$symb));
11461:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11462:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11463:             $request->print(&initialverifyreceipt($request,$symb));
11464: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11465:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11466:                                        {href=>'',text=>'Verification Result'}]);
11467: 	    $request->print(&verifyreceipt($request,$symb));
11468:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11469:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11470:             $request->print(&process_clicker($request,$symb));
11471:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11472:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11473:                                        {href=>'', text=>'Process clicker file'}]);
11474:             $request->print(&process_clicker_file($request,$symb));
11475:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11476:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11477:                                        {href=>'', text=>'Process clicker file'},
11478:                                        {href=>'', text=>'Store grades'}]);
11479:             $request->print(&assign_clicker_grades($request,$symb));
11480: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11481:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11482: 	    $request->print(&upcsvScores_form($request,$symb));
11483: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11484:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11485: 	    $request->print(&csvupload($request,$symb));
11486: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11487:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11488: 	    $request->print(&csvuploadmap($request,$symb));
11489: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11490: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11491:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11492: 		$request->print(&csvuploadoptions($request,$symb));
11493: 	    } else {
11494: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11495: 		    $env{'form.upfile_associate'} = 'reverse';
11496: 		} else {
11497: 		    $env{'form.upfile_associate'} = 'forward';
11498: 		}
11499:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11500: 		$request->print(&csvuploadmap($request,$symb));
11501: 	    }
11502: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11503:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11504: 	    $request->print(&csvuploadassign($request,$symb));
11505: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11506:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11507:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11508: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11509:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11510:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11511:  	    $request->print(&scantron_do_warning($request,$symb));
11512: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11513:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11514: 	    $request->print(&scantron_validate_file($request,$symb));
11515: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11516:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11517: 	    $request->print(&scantron_process_students($request,$symb));
11518:  	} elsif ($command eq 'scantronupload' && 
11519:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11520:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11521:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11522:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11523:  	} elsif ($command eq 'scantronupload_save' &&
11524:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11525:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11526:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11527:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11528:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11529:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11530:         } elsif ($command eq 'scantronupload_delete' &&
11531:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11532:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11533:             &scantron_upload_delete($request,$symb);
11534:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11535:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11536:             $request->print(&checkscantron_results($request,$symb));
11537:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11538:             my $js = &part_selector_js();
11539:             my $onload = "toggleParts('gradingMenu');";
11540:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11541:                        undef,undef,undef,undef,undef,$js,$onload);
11542:             $request->print(&submit_options_download($request,$symb));
11543:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11544:             &startpage($request,$symb,
11545:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11546:     {href=>'', text=>'Download submitted files'}],
11547:                undef,undef,undef,undef,undef,undef,undef,1);
11548:             &submit_download_link($request,$symb);
11549: 	} elsif ($command) {
11550:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11551: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11552: 	}
11553:     }
11554:     if ($ssi_error) {
11555: 	&ssi_print_error($request);
11556:     }
11557:     if ($env{'form.inhibitmenu'}) {
11558:         $request->print(&Apache::loncommon::end_page());
11559:     } elsif ($env{'request.course.id'}) {
11560:         &Apache::lonquickgrades::endGradeScreen($request);
11561:     }
11562:     &reset_caches();
11563:     return OK;
11564: }
11565: 
11566: 1;
11567: 
11568: __END__;
11569: 
11570: 
11571: =head1 NAME
11572: 
11573: Apache::grades
11574: 
11575: =head1 SYNOPSIS
11576: 
11577: Handles the viewing of grades.
11578: 
11579: This is part of the LearningOnline Network with CAPA project
11580: described at http://www.lon-capa.org.
11581: 
11582: =head1 OVERVIEW
11583: 
11584: Do an ssi with retries:
11585: While I'd love to factor out this with the version in lonprintout,
11586: 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
11587: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11588: 
11589: At least the logic that drives this has been pulled out into loncommon.
11590: 
11591: 
11592: 
11593: ssi_with_retries - Does the server side include of a resource.
11594:                      if the ssi call returns an error we'll retry it up to
11595:                      the number of times requested by the caller.
11596:                      If we still have a problem, no text is appended to the
11597:                      output and we set some global variables.
11598:                      to indicate to the caller an SSI error occurred.  
11599:                      All of this is supposed to deal with the issues described
11600:                      in LON-CAPA BZ 5631 see:
11601:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11602:                      by informing the user that this happened.
11603: 
11604: Parameters:
11605:   resource   - The resource to include.  This is passed directly, without
11606:                interpretation to lonnet::ssi.
11607:   form       - The form hash parameters that guide the interpretation of the resource
11608:                
11609:   retries    - Number of retries allowed before giving up completely.
11610: Returns:
11611:   On success, returns the rendered resource identified by the resource parameter.
11612: Side Effects:
11613:   The following global variables can be set:
11614:    ssi_error                - If an unrecoverable error occurred this becomes true.
11615:                               It is up to the caller to initialize this to false
11616:                               if desired.
11617:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11618:                               of the resource that could not be rendered by the ssi
11619:                               call.
11620:    ssi_error_message   - The error string fetched from the ssi response
11621:                               in the event of an error.
11622: 
11623: 
11624: =head1 HANDLER SUBROUTINE
11625: 
11626: ssi_with_retries()
11627: 
11628: =head1 SUBROUTINES
11629: 
11630: =over
11631: 
11632: =head1 Routines to display previous version of a Task for a specific student
11633: 
11634: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11635: can receive another opportunity. Access to tasks is slot-based. If a slot
11636: requires a proctor to check-in the student, a new version of the Task will
11637: be created when the student is checked in to the new opportunity.
11638: 
11639: If a particular student has tried two or more versions of a particular task,
11640: the submission screen provides a user with vgr privileges (e.g., a Course
11641: Coordinator) the ability to display a previous version worked on by the
11642: student.  By default, the current version is displayed. If a previous version
11643: has been selected for display, submission data are only shown that pertain
11644: to that particular version, and the interface to submit grades is not shown.
11645: 
11646: =over 4
11647: 
11648: =item show_previous_task_version()
11649: 
11650: Displays a specified version of a student's Task, as the student sees it.
11651: 
11652: Inputs: 2
11653:         request - request object
11654:         symb    - unique symb for current instance of resource
11655: 
11656: Output: None.
11657: 
11658: Side Effects: calls &show_problem() to print version of Task, with
11659:               version contained in form item: $env{'form.previousversion'}
11660: 
11661: =item choose_task_version_form()
11662: 
11663: Displays a web form used to select which version of a student's view of a
11664: Task should be displayed.  Either launches a pop-up window, or replaces
11665: content in existing pop-up, or replaces page in main window.
11666: 
11667: Inputs: 4
11668:         symb    - unique symb for current instance of resource
11669:         uname   - username of student
11670:         udom    - domain of student
11671:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11672:                   breadcrumbs etc., are displayed
11673: 
11674: Output: 4
11675:         current   - student's current version
11676:         displayed - student's version being displayed
11677:         result    - scalar containing HTML for web form used to switch to
11678:                     a different version (or a link to close window, if pop-up).
11679:         js        - javascript for processing selection in versions web form
11680: 
11681: Side Effects: None.
11682: 
11683: =item previous_display_javascript()
11684: 
11685: Inputs: 2
11686:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11687:                   breadcrumbs etc., are displayed.
11688:         current - student's current version number.
11689: 
11690: Output: 1
11691:         js      - javascript for processing selection in versions web form.
11692: 
11693: Side Effects: None.
11694: 
11695: =back
11696: 
11697: =head1 Routines to process bubblesheet data.
11698: 
11699: =over 4
11700: 
11701: =item scantron_get_correction() : 
11702: 
11703:    Builds the interface screen to interact with the operator to fix a
11704:    specific error condition in a specific scanline
11705: 
11706:  Arguments:
11707:     $r           - Apache request object
11708:     $i           - number of the current scanline
11709:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11710:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11711:     $line        - full contents of the current scanline
11712:     $error       - error condition, valid values are
11713:                    'incorrectCODE', 'duplicateCODE',
11714:                    'doublebubble', 'missingbubble',
11715:                    'duplicateID', 'incorrectID'
11716:     $arg         - extra information needed
11717:        For errors:
11718:          - duplicateID   - paper number that this studentID was seen before on
11719:          - duplicateCODE - array ref of the paper numbers this CODE was
11720:                            seen on before
11721:          - incorrectCODE - current incorrect CODE 
11722:          - doublebubble  - array ref of the bubble lines that have double
11723:                            bubble errors
11724:          - missingbubble - array ref of the bubble lines that have missing
11725:                            bubble errors
11726: 
11727:    $randomorder - True if exam folder has randomorder set
11728:    $randompick  - True if exam folder has randompick set
11729:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11730:                      for current line to question number used for same question
11731:                      in "Master Seqence" (as seen by Course Coordinator).
11732:    $startline   - Reference to hash where key is question number (0 is first)
11733:                   and value is number of first bubble line for current student
11734:                   or code-based randompick and/or randomorder.
11735: 
11736: 
11737: 
11738: =item  scantron_get_maxbubble() : 
11739: 
11740:    Arguments:
11741:        $nav_error  - Reference to scalar which is a flag to indicate a
11742:                       failure to retrieve a navmap object.
11743:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11744:        calling routine should trap the error condition and display the warning
11745:        found in &navmap_errormsg().
11746: 
11747:        $scantron_config - Reference to bubblesheet format configuration hash.
11748: 
11749:    Returns the maximum number of bubble lines that are expected to
11750:    occur. Does this by walking the selected sequence rendering the
11751:    resource and then checking &Apache::lonxml::get_problem_counter()
11752:    for what the current value of the problem counter is.
11753: 
11754:    Caches the results to $env{'form.scantron_maxbubble'},
11755:    $env{'form.scantron.bubble_lines.n'}, 
11756:    $env{'form.scantron.first_bubble_line.n'} and
11757:    $env{"form.scantron.sub_bubblelines.n"}
11758:    which are the total number of bubble lines, the number of bubble
11759:    lines for response n and number of the first bubble line for response n,
11760:    and a comma separated list of numbers of bubble lines for sub-questions
11761:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11762: 
11763: 
11764: =item  scantron_validate_missingbubbles() : 
11765: 
11766:    Validates all scanlines in the selected file to not have any
11767:     answers that don't have bubbles that have not been verified
11768:     to be bubble free.
11769: 
11770: =item  scantron_process_students() : 
11771: 
11772:    Routine that does the actual grading of the bubblesheet information.
11773: 
11774:    The parsed scanline hash is added to %env 
11775: 
11776:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11777:    foreach resource , with the form data of
11778: 
11779: 	'submitted'     =>'scantron' 
11780: 	'grade_target'  =>'grade',
11781: 	'grade_username'=> username of student
11782: 	'grade_domain'  => domain of student
11783: 	'grade_courseid'=> of course
11784: 	'grade_symb'    => symb of resource to grade
11785: 
11786:     This triggers a grading pass. The problem grading code takes care
11787:     of converting the bubbled letter information (now in %env) into a
11788:     valid submission.
11789: 
11790: =item  scantron_upload_scantron_data() :
11791: 
11792:     Creates the screen for adding a new bubblesheet data file to a course.
11793: 
11794: =item  scantron_upload_scantron_data_save() : 
11795: 
11796:    Adds a provided bubble information data file to the course if user
11797:    has the correct privileges to do so.
11798: 
11799: = item scantron_upload_delete() :
11800: 
11801:    Deletes a previously uploaded bubble information data file, if user
11802:    was the one who uploaded the file, and has the privileges to do so.
11803: 
11804: =item  valid_file() :
11805: 
11806:    Validates that the requested bubble data file exists in the course.
11807: 
11808: =item  scantron_download_scantron_data() : 
11809: 
11810:    Shows a list of the three internal files (original, corrected,
11811:    skipped) for a specific bubblesheet data file that exists in the
11812:    course.
11813: 
11814: =item  scantron_validate_ID() : 
11815: 
11816:    Validates all scanlines in the selected file to not have any
11817:    invalid or underspecified student/employee IDs
11818: 
11819: =item navmap_errormsg() :
11820: 
11821:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11822:    Should be called whenever the request to instantiate a navmap object fails.
11823: 
11824: =back
11825: 
11826: =back
11827: 
11828: =cut

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