File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.787: download - view: text, annotated - select for diffs
Fri Dec 17 20:10:21 2021 UTC (2 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- In &updateGradeByPage() routine, need to declare %queueable and replace
  scalar used for partID. (fix changes in rev. 1.786).

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.787 2021/12/17 20:10:21 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:     if (!keys(%partsseen)) {
  297:         $result = '';
  298:         if ($uploads) {
  299:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  300:                    '<p class="LC_info">'.
  301:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  302:                    '</p>';
  303:         } else {
  304:             return '<br clear="all" />';
  305:         }
  306:     }
  307:     return $result;
  308: }
  309: 
  310: sub part_selector_js {
  311:     my $js = <<"END";
  312: function toggleParts(formname) {
  313:     if (document.getElementById('LC_partselector')) {
  314:         var index = '';
  315:         if (document.forms.length) {
  316:             for (var i=0; i<document.forms.length; i++) {
  317:                 if (document.forms[i].name == formname) {
  318:                     index = i;
  319:                     break;
  320:                 }
  321:             }
  322:         }
  323:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  324:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  325:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  326:                    var val = document.forms[index].elements['chooseparts'][i].value;
  327:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  328:                         document.getElementById('LC_partselector').style.display = 'block';
  329:                     } else {
  330:                         document.getElementById('LC_partselector').style.display = 'none';
  331:                     }
  332:                 }
  333:             }
  334:         }
  335:     }
  336: }
  337: END
  338:     return &Apache::lonhtmlcommon::scripttag($js);
  339: }
  340: 
  341: sub reset_caches {
  342:     &reset_analyze_cache();
  343:     &reset_perm();
  344:     &reset_old_essays();
  345: }
  346: 
  347: {
  348:     my %analyze_cache;
  349:     my %analyze_cache_formkeys;
  350: 
  351:     sub reset_analyze_cache {
  352: 	undef(%analyze_cache);
  353:         undef(%analyze_cache_formkeys);
  354:     }
  355: 
  356:     sub get_analyze {
  357: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  358: 	my $key = "$symb\0$uname\0$udom";
  359:         if ($type eq 'randomizetry') {
  360:             if ($trial ne '') {
  361:                 $key .= "\0".$trial;
  362:             }
  363:         }
  364: 	if (exists($analyze_cache{$key})) {
  365:             my $getupdate = 0;
  366:             if (ref($add_to_hash) eq 'HASH') {
  367:                 foreach my $item (keys(%{$add_to_hash})) {
  368:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  369:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  370:                             $getupdate = 1;
  371:                             last;
  372:                         }
  373:                     } else {
  374:                         $getupdate = 1;
  375:                     }
  376:                 }
  377:             }
  378:             if (!$getupdate) {
  379:                 return $analyze_cache{$key};
  380:             }
  381:         }
  382: 
  383: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  384: 	$url=&Apache::lonnet::clutter($url);
  385:         my %form = ('grade_target'      => 'analyze',
  386:                     'grade_domain'      => $udom,
  387:                     'grade_symb'        => $symb,
  388:                     'grade_courseid'    =>  $env{'request.course.id'},
  389:                     'grade_username'    => $uname,
  390:                     'grade_noincrement' => $no_increment);
  391:         if ($bubbles_per_row ne '') {
  392:             $form{'bubbles_per_row'} = $bubbles_per_row;
  393:         }
  394:         if ($type eq 'randomizetry') {
  395:             $form{'grade_questiontype'} = $type;
  396:             if ($rndseed ne '') {
  397:                 $form{'grade_rndseed'} = $rndseed;
  398:             }
  399:         }
  400:         if (ref($add_to_hash)) {
  401:             %form = (%form,%{$add_to_hash});
  402:         }
  403: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  404: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  406:         if (ref($add_to_hash) eq 'HASH') {
  407:             $analyze_cache_formkeys{$key} = $add_to_hash;
  408:         } else {
  409:             $analyze_cache_formkeys{$key} = {};
  410:         }
  411: 	return $analyze_cache{$key} = \%analyze;
  412:     }
  413: 
  414:     sub get_order {
  415: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  416: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  417: 	return $analyze->{"$partid.$respid.shown"};
  418:     }
  419: 
  420:     sub get_radiobutton_correct_foil {
  421: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  422: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  423:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  424:         if (ref($foils) eq 'ARRAY') {
  425: 	    foreach my $foil (@{$foils}) {
  426: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  427: 		    return $foil;
  428: 	        }
  429: 	    }
  430: 	}
  431:     }
  432: 
  433:     sub scantron_partids_tograde {
  434:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  435:         my (%analysis,@parts);
  436:         if (ref($resource)) {
  437:             my $symb = $resource->symb();
  438:             my $add_to_form;
  439:             if ($check_for_randomlist) {
  440:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  441:             }
  442:             if ($scancode) {
  443:                 if (ref($add_to_form) eq 'HASH') {
  444:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  445:                 } else {
  446:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  447:                 }
  448:             }
  449:             my $analyze =
  450:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  451:                              undef,undef,undef,$bubbles_per_row);
  452:             if (ref($analyze) eq 'HASH') {
  453:                 %analysis = %{$analyze};
  454:             }
  455:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  456:                 foreach my $part (@{$analysis{'parts'}}) {
  457:                     my ($id,$respid) = split(/\./,$part);
  458:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  459:                         push(@parts,$part);
  460:                     }
  461:                 }
  462:             }
  463:         }
  464:         return (\%analysis,\@parts);
  465:     }
  466: 
  467: }
  468: 
  469: #--- Clean response type for display
  470: #--- Currently filters option/rank/radiobutton/match/essay/Task
  471: #        response types only.
  472: sub cleanRecord {
  473:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  474: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  475:     my $grayFont = '<span class="LC_internal_info">';
  476:     if ($response =~ /^(option|rank)$/) {
  477: 	my %answer=&Apache::lonnet::str2hash($answer);
  478:         my @answer = %answer;
  479:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  480: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  481: 	my ($toprow,$bottomrow);
  482: 	foreach my $foil (@$order) {
  483: 	    if ($grading{$foil} == 1) {
  484: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  485: 	    } else {
  486: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  487: 	    }
  488: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  489: 	}
  490: 	return '<blockquote><table border="1">'.
  491: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  492: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  493: 	    $bottomrow.'</tr></table></blockquote>';
  494:     } elsif ($response eq 'match') {
  495: 	my %answer=&Apache::lonnet::str2hash($answer);
  496:         my @answer = %answer;
  497:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  498: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  499: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  500: 	my ($toprow,$middlerow,$bottomrow);
  501: 	foreach my $foil (@$order) {
  502: 	    my $item=shift(@items);
  503: 	    if ($grading{$foil} == 1) {
  504: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  505: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  506: 	    } else {
  507: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  508: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  509: 	    }
  510: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  511: 	}
  512: 	return '<blockquote><table border="1">'.
  513: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  514: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  515: 	    $middlerow.'</tr>'.
  516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  517: 	    $bottomrow.'</tr></table></blockquote>';
  518:     } elsif ($response eq 'radiobutton') {
  519: 	my %answer=&Apache::lonnet::str2hash($answer);
  520:         my @answer = %answer;
  521:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  522: 	my ($toprow,$bottomrow);
  523: 	my $correct = 
  524: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  525: 	foreach my $foil (@$order) {
  526: 	    if (exists($answer{$foil})) {
  527: 		if ($foil eq $correct) {
  528: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  529: 		} else {
  530: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  531: 		}
  532: 	    } else {
  533: 		$toprow.='<td>'.&mt('false').'</td>';
  534: 	    }
  535: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  536: 	}
  537: 	return '<blockquote><table border="1">'.
  538: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  539: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  540: 	    $bottomrow.'</tr></table></blockquote>';
  541:     } elsif ($response eq 'essay') {
  542: 	if (! exists ($env{'form.'.$symb})) {
  543: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  544: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  545: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  546: 
  547: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  548: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  549: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  550: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  551: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  552: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  553: 	}
  554:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  555: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  556:     } elsif ( $response eq 'organic') {
  557:         my $result=&mt('Smile representation: [_1]',
  558:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  559: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  560: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  561: 	return $result;
  562:     } elsif ( $response eq 'Task') {
  563: 	if ( $answer eq 'SUBMITTED') {
  564: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  565: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  566: 	    return $result;
  567: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  568: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  569: 			       keys(%{$record}));
  570: 	    return join('<br />',($version,@matches));
  571: 			       
  572: 			       
  573: 	} else {
  574: 	    my $result =
  575: 		'<p>'
  576: 		.&mt('Overall result: [_1]',
  577: 		     $record->{$version."resource.$respid.$partid.status"})
  578: 		.'</p>';
  579: 	    
  580: 	    $result .= '<ul>';
  581: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  582: 			     keys(%{$record}));
  583: 	    foreach my $grade (sort(@grade)) {
  584: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  585: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  586: 				     $dim, $record->{$grade}).
  587: 			  '</li>';
  588: 	    }
  589: 	    $result.='</ul>';
  590: 	    return $result;
  591: 	}
  592:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  593:         # Respect multiple input fields, see Bug #5409
  594: 	$answer = 
  595: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  596: 							      $answer);
  597: 	return $answer;
  598:     }
  599:     return &HTML::Entities::encode($answer, '"<>&');
  600: }
  601: 
  602: #-- A couple of common js functions
  603: sub commonJSfunctions {
  604:     my $request = shift;
  605:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  606:     function radioSelection(radioButton) {
  607: 	var selection=null;
  608: 	if (radioButton.length > 1) {
  609: 	    for (var i=0; i<radioButton.length; i++) {
  610: 		if (radioButton[i].checked) {
  611: 		    return radioButton[i].value;
  612: 		}
  613: 	    }
  614: 	} else {
  615: 	    if (radioButton.checked) return radioButton.value;
  616: 	}
  617: 	return selection;
  618:     }
  619: 
  620:     function pullDownSelection(selectOne) {
  621: 	var selection="";
  622: 	if (selectOne.length > 1) {
  623: 	    for (var i=0; i<selectOne.length; i++) {
  624: 		if (selectOne[i].selected) {
  625: 		    return selectOne[i].value;
  626: 		}
  627: 	    }
  628: 	} else {
  629:             // only one value it must be the selected one
  630: 	    return selectOne.value;
  631: 	}
  632:     }
  633: COMMONJSFUNCTIONS
  634: }
  635: 
  636: #--- Dumps the class list with usernames,list of sections,
  637: #--- section, ids and fullnames for each user.
  638: sub getclasslist {
  639:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  640:     my @getsec;
  641:     my @getgroup;
  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  643:     if (!ref($getsec)) {
  644: 	if ($getsec ne '' && $getsec ne 'all') {
  645: 	    @getsec=($getsec);
  646: 	}
  647:     } else {
  648: 	@getsec=@{$getsec};
  649:     }
  650:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  651:     if (!ref($getgroup)) {
  652: 	if ($getgroup ne '' && $getgroup ne 'all') {
  653: 	    @getgroup=($getgroup);
  654: 	}
  655:     } else {
  656: 	@getgroup=@{$getgroup};
  657:     }
  658:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  659: 
  660:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  661:     # Bail out if we were unable to get the classlist
  662:     return if (! defined($classlist));
  663:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  664:     #
  665:     my %sections;
  666:     my %fullnames;
  667:     my ($cdom,$cnum,$partlist);
  668:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  669:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  670:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  671:         my $res_error;
  672:         ($partlist) = &response_type($symb,\$res_error);
  673:     }
  674:     foreach my $student (keys(%$classlist)) {
  675:         my $end      = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  677:         my $start    = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  679:         my $id       = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  681:         my $section  = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  683:         my $fullname = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  685:         my $status   = 
  686:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  687:         my $group   = 
  688:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  689: 	# filter students according to status selected
  690: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  691: 	    if (!($stu_status =~ $status)) {
  692: 		delete($classlist->{$student});
  693: 		next;
  694: 	    }
  695: 	}
  696: 	# filter students according to groups selected
  697: 	my @stu_groups = split(/,/,$group);
  698: 	if (@getgroup) {
  699: 	    my $exclude = 1;
  700: 	    foreach my $grp (@getgroup) {
  701: 	        foreach my $stu_group (@stu_groups) {
  702: 	            if ($stu_group eq $grp) {
  703: 	                $exclude = 0;
  704:     	            } 
  705: 	        }
  706:     	        if (($grp eq 'none') && !$group) {
  707:         	    $exclude = 0;
  708:         	}
  709: 	    }
  710: 	    if ($exclude) {
  711: 	        delete($classlist->{$student});
  712: 		next;
  713: 	    }
  714: 	}
  715:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  716:             my $udom =
  717:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  718:             my $uname =
  719:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  720:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  721:                 if ($submitonly eq 'queued') {
  722:                     my %queue_status =
  723:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  724:                                                                 $udom,$uname);
  725:                     if (!defined($queue_status{'gradingqueue'})) {
  726:                         delete($classlist->{$student});
  727:                         next;
  728:                     }
  729:                 } else {
  730:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  731:                     my $submitted = 0;
  732:                     my $graded = 0;
  733:                     my $incorrect = 0;
  734:                     foreach (keys(%status)) {
  735:                         $submitted = 1 if ($status{$_} ne 'nothing');
  736:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  737:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  738: 
  739:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  740:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  741:                             $submitted = 0;
  742:                         }
  743:                     }
  744:                     if (!$submitted && ($submitonly eq 'yes' ||
  745:                                         $submitonly eq 'incorrect' ||
  746:                                         $submitonly eq 'graded')) {
  747:                         delete($classlist->{$student});
  748:                         next;
  749:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  750:                         delete($classlist->{$student});
  751:                         next;
  752:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  753:                         delete($classlist->{$student});
  754:                         next;
  755:                     }
  756:                 }
  757:             }
  758:         }
  759: 	$section = ($section ne '' ? $section : 'none');
  760: 	if (&canview($section)) {
  761: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  762: 		$sections{$section}++;
  763: 		if ($classlist->{$student}) {
  764: 		    $fullnames{$student}=$fullname;
  765: 		}
  766: 	    } else {
  767: 		delete($classlist->{$student});
  768: 	    }
  769: 	} else {
  770: 	    delete($classlist->{$student});
  771: 	}
  772:     }
  773:     my @sections = sort(keys(%sections));
  774:     return ($classlist,\@sections,\%fullnames);
  775: }
  776: 
  777: sub canmodify {
  778:     my ($sec)=@_;
  779:     if ($perm{'mgr'}) {
  780: 	if (!defined($perm{'mgr_section'})) {
  781: 	    # can modify whole class
  782: 	    return 1;
  783: 	} else {
  784: 	    if ($sec eq $perm{'mgr_section'}) {
  785: 		#can modify the requested section
  786: 		return 1;
  787: 	    } else {
  788: 		# can't modify the requested section
  789: 		return 0;
  790: 	    }
  791: 	}
  792:     }
  793:     #can't modify
  794:     return 0;
  795: }
  796: 
  797: sub canview {
  798:     my ($sec)=@_;
  799:     if ($perm{'vgr'}) {
  800: 	if (!defined($perm{'vgr_section'})) {
  801: 	    # can view whole class
  802: 	    return 1;
  803: 	} else {
  804: 	    if ($sec eq $perm{'vgr_section'}) {
  805: 		#can view the requested section
  806: 		return 1;
  807: 	    } else {
  808: 		# can't view the requested section
  809: 		return 0;
  810: 	    }
  811: 	}
  812:     }
  813:     #can't view
  814:     return 0;
  815: }
  816: 
  817: #--- Retrieve the grade status of a student for all the parts
  818: sub student_gradeStatus {
  819:     my ($symb,$udom,$uname,$partlist) = @_;
  820:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  821:     my %partstatus = ();
  822:     foreach (@$partlist) {
  823: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  824: 	$status              = 'nothing' if ($status eq '');
  825: 	$partstatus{$_}      = $status;
  826: 	my $subkey           = "resource.$_.submitted_by";
  827: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  828:     }
  829:     return %partstatus;
  830: }
  831: 
  832: # hidden form and javascript that calls the form
  833: # Use by verifyscript and viewgrades
  834: # Shows a student's view of problem and submission
  835: sub jscriptNform {
  836:     my ($symb) = @_;
  837:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  838:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  839: 	'    function viewOneStudent(user,domain) {'."\n".
  840: 	'	document.onestudent.student.value = user;'."\n".
  841: 	'	document.onestudent.userdom.value = domain;'."\n".
  842: 	'	document.onestudent.submit();'."\n".
  843: 	'    }'."\n".
  844: 	"\n");
  845:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  846: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  847: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  848: 	'<input type="hidden" name="command" value="submission" />'."\n".
  849: 	'<input type="hidden" name="student" value="" />'."\n".
  850: 	'<input type="hidden" name="userdom" value="" />'."\n".
  851: 	'</form>'."\n";
  852:     return $jscript;
  853: }
  854: 
  855: 
  856: 
  857: # Given the score (as a number [0-1] and the weight) what is the final
  858: # point value? This function will round to the nearest tenth, third,
  859: # or quarter if one of those is within the tolerance of .00001.
  860: sub compute_points {
  861:     my ($score, $weight) = @_;
  862:     
  863:     my $tolerance = .00001;
  864:     my $points = $score * $weight;
  865: 
  866:     # Check for nearness to 1/x.
  867:     my $check_for_nearness = sub {
  868:         my ($factor) = @_;
  869:         my $num = ($points * $factor) + $tolerance;
  870:         my $floored_num = floor($num);
  871:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  872:             return $floored_num / $factor;
  873:         }
  874:         return $points;
  875:     };
  876: 
  877:     $points = $check_for_nearness->(10);
  878:     $points = $check_for_nearness->(3);
  879:     $points = $check_for_nearness->(4);
  880:     
  881:     return $points;
  882: }
  883: 
  884: #------------------ End of general use routines --------------------
  885: 
  886: #
  887: # Find most similar essay
  888: #
  889: 
  890: sub most_similar {
  891:     my ($uname,$udom,$symb,$uessay)=@_;
  892: 
  893:     unless ($symb) { return ''; }
  894: 
  895:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  896: 
  897: # ignore spaces and punctuation
  898: 
  899:     $uessay=~s/\W+/ /gs;
  900: 
  901: # ignore empty submissions (occuring when only files are sent)
  902: 
  903:     unless ($uessay=~/\w+/s) { return ''; }
  904: 
  905: # these will be returned. Do not care if not at least 50 percent similar
  906:     my $limit=0.6;
  907:     my $sname='';
  908:     my $sdom='';
  909:     my $scrsid='';
  910:     my $sessay='';
  911: # go through all essays ...
  912:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  913: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  914: # ... except the same student
  915:         next if (($tname eq $uname) && ($tdom eq $udom));
  916: 	my $tessay=$old_essays{$symb}{$tkey};
  917: 	$tessay=~s/\W+/ /gs;
  918: # String similarity gives up if not even limit
  919: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  920: # Found one
  921: 	if ($tsimilar>$limit) {
  922: 	    $limit=$tsimilar;
  923: 	    $sname=$tname;
  924: 	    $sdom=$tdom;
  925: 	    $scrsid=$tcrsid;
  926: 	    $sessay=$old_essays{$symb}{$tkey};
  927: 	}
  928:     }
  929:     if ($limit>0.6) {
  930:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  931:     } else {
  932:        return ('','','','',0);
  933:     }
  934: }
  935: 
  936: #-------------------------------------------------------------------
  937: 
  938: #------------------------------------ Receipt Verification Routines
  939: #
  940: 
  941: sub initialverifyreceipt {
  942:    my ($request,$symb) = @_;
  943:    &commonJSfunctions($request);
  944:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  945:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  946:         '-<input type="text" name="receipt" size="4" />'.
  947:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  948:         '<input type="hidden" name="command" value="verify" />'.
  949:         "</form>\n";
  950: }
  951: 
  952: #--- Check whether a receipt number is valid.---
  953: sub verifyreceipt {
  954:     my ($request,$symb) = @_;
  955: 
  956:     my $courseid = $env{'request.course.id'};
  957:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  958: 	$env{'form.receipt'};
  959:     $receipt     =~ s/[^\-\d]//g;
  960: 
  961:     my $title =
  962: 	'<h3><span class="LC_info">'.
  963: 	&mt('Verifying Receipt Number [_1]',$receipt).
  964: 	'</span></h3>'."\n";
  965: 
  966:     my ($string,$contents,$matches) = ('','',0);
  967:     my (undef,undef,$fullname) = &getclasslist('all','0');
  968:     
  969:     my $receiptparts=0;
  970:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  971: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  972:     my $parts=['0'];
  973:     if ($receiptparts) {
  974:         my $res_error; 
  975:         ($parts)=&response_type($symb,\$res_error);
  976:         if ($res_error) {
  977:             return &navmap_errormsg();
  978:         } 
  979:     }
  980:     
  981:     my $header = 
  982: 	&Apache::loncommon::start_data_table().
  983: 	&Apache::loncommon::start_data_table_header_row().
  984: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  985: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  986: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  987:     if ($receiptparts) {
  988: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  989:     }
  990:     $header.=
  991: 	&Apache::loncommon::end_data_table_header_row();
  992: 
  993:     foreach (sort 
  994: 	     {
  995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  997: 		 }
  998: 		 return $a cmp $b;
  999: 	     } (keys(%$fullname))) {
 1000: 	my ($uname,$udom)=split(/\:/);
 1001: 	foreach my $part (@$parts) {
 1002: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
 1003: 		$contents.=
 1004: 		    &Apache::loncommon::start_data_table_row().
 1005: 		    '<td>&nbsp;'."\n".
 1006: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1007: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1008: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1009: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1010: 		if ($receiptparts) {
 1011: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1012: 		}
 1013: 		$contents.= 
 1014: 		    &Apache::loncommon::end_data_table_row()."\n";
 1015: 		
 1016: 		$matches++;
 1017: 	    }
 1018: 	}
 1019:     }
 1020:     if ($matches == 0) {
 1021:         $string = $title
 1022:                  .'<p class="LC_warning">'
 1023:                  .&mt('No match found for the above receipt number.')
 1024:                  .'</p>';
 1025:     } else {
 1026: 	$string = &jscriptNform($symb).$title.
 1027: 	    '<p>'.
 1028: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1029: 	    '</p>'.
 1030: 	    $header.
 1031: 	    $contents.
 1032: 	    &Apache::loncommon::end_data_table()."\n";
 1033:     }
 1034:     return $string;
 1035: }
 1036: 
 1037: #--- This is called by a number of programs.
 1038: #--- Called from the Grading Menu - View/Grade an individual student
 1039: #--- Also called directly when one clicks on the subm button 
 1040: #    on the problem page.
 1041: sub listStudents {
 1042:     my ($request,$symb,$submitonly,$divforres) = @_;
 1043: 
 1044:     my $is_tool   = ($symb =~ /ext\.tool$/);
 1045:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1046:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1047:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1048:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1049:     unless ($submitonly) {
 1050:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1051:     }
 1052: 
 1053:     my $result='';
 1054:     my $res_error;
 1055:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1056: 
 1057:     my $table;
 1058:     if (ref($partlist) eq 'ARRAY') {
 1059:         if (scalar(@$partlist) > 1 ) {
 1060:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1061:         } elsif ($divforres) {
 1062:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1063:         } else {
 1064:             $table = '<br clear="all" />';
 1065:         }
 1066:     }
 1067: 
 1068:     my %js_lt = &Apache::lonlocal::texthash (
 1069: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1070: 		'single'   => 'Please select the student before clicking on the Next button.',
 1071: 	     );
 1072:     &js_escape(\%js_lt);
 1073:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1074:     function checkSelect(checkBox) {
 1075: 	var ctr=0;
 1076: 	var sense="";
 1077: 	if (checkBox.length > 1) {
 1078: 	    for (var i=0; i<checkBox.length; i++) {
 1079: 		if (checkBox[i].checked) {
 1080: 		    ctr++;
 1081: 		}
 1082: 	    }
 1083: 	    sense = '$js_lt{'multiple'}';
 1084: 	} else {
 1085: 	    if (checkBox.checked) {
 1086: 		ctr = 1;
 1087: 	    }
 1088: 	    sense = '$js_lt{'single'}';
 1089: 	}
 1090: 	if (ctr == 0) {
 1091: 	    alert(sense);
 1092: 	    return false;
 1093: 	}
 1094: 	document.gradesub.submit();
 1095:     }
 1096: 
 1097:     function reLoadList(formname) {
 1098: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1099: 	formname.command.value = 'submission';
 1100: 	formname.submit();
 1101:     }
 1102: LISTJAVASCRIPT
 1103: 
 1104:     &commonJSfunctions($request);
 1105:     $request->print($result);
 1106: 
 1107:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1108: 	"\n".$table;
 1109: 
 1110:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1111:     unless ($is_tool) {
 1112:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1113:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1114:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1115:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1116:                       .&Apache::lonhtmlcommon::row_closure();
 1117:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1118:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1119:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1120:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1121:                       .&Apache::lonhtmlcommon::row_closure();
 1122:     }
 1123: 
 1124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1125:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1126:     $env{'form.Status'} = $saveStatus;
 1127:     my %optiontext;
 1128:     if ($is_tool) {
 1129:         %optiontext = &Apache::lonlocal::texthash (
 1130:                           lastonly => 'last transaction',
 1131:                           last     => 'last transaction with details',
 1132:                           datesub  => 'all transactions',
 1133:                           all      => 'all transactions with details',
 1134:                       );
 1135:     } else {
 1136:         %optiontext = &Apache::lonlocal::texthash (
 1137:                           lastonly => 'last submission',
 1138:                           last     => 'last submission with details',
 1139:                           datesub  => 'all submissions',
 1140:                           all      => 'all submissions with details',
 1141:                       );
 1142:     }
 1143:     my $submission_options =
 1144:         '<span class="LC_nobreak">'.
 1145:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1146:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1147:         '<span class="LC_nobreak">'.
 1148:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1149:         $optiontext{'last'}.' </label></span>'."\n".
 1150:         '<span class="LC_nobreak">'.
 1151:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1152:         $optiontext{'datesub'}.'</label></span>'."\n".
 1153:         '<span class="LC_nobreak">'.
 1154:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1155:         $optiontext{'all'}.'</label></span>';
 1156:     my $viewtitle;
 1157:     if ($is_tool) {
 1158:         $viewtitle = &mt('View Transactions');
 1159:     } else {
 1160:         $viewtitle = &mt('View Submissions');
 1161:     }
 1162:     my ($compmsg,$nocompmsg);
 1163:     $nocompmsg = ' checked="checked"';
 1164:     if ($numessay) {
 1165:         $compmsg = $nocompmsg;
 1166:         $nocompmsg = '';
 1167:     }
 1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1169:                   .$submission_options;
 1170: # Check if any gradable
 1171:     my $showmore;
 1172:     if ($perm{'mgr'}) {
 1173:         my @sections;
 1174:         if ($env{'request.course.sec'} ne '') {
 1175:             @sections = ($env{'request.course.sec'});
 1176:         } elsif ($env{'form.section'} eq '') {
 1177:             @sections = ('all');
 1178:         } else {
 1179:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1180:         }
 1181:         if (grep(/^all$/,@sections)) {
 1182:             $showmore = 1;
 1183:         } else {
 1184:             foreach my $sec (@sections) {
 1185:                 if (&canmodify($sec)) {
 1186:                     $showmore = 1;
 1187:                     last;
 1188:                 }
 1189:             }
 1190:         }
 1191:     }
 1192: 
 1193:     if ($showmore) {
 1194:         $gradeTable .=
 1195:                    &Apache::lonhtmlcommon::row_closure()
 1196:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1197:                   .'<span class="LC_nobreak">'
 1198:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1199:                   .&mt('No').('&nbsp;'x2).'</label>'
 1200:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1201:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1202:                   .&Apache::lonhtmlcommon::row_closure();
 1203: 
 1204:         $gradeTable .= 
 1205:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1206:                   .'<select name="increment">'
 1207:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1208:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1209:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1210:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1211:                   .'</select>';
 1212:     }
 1213:     $gradeTable .= 
 1214:         &build_section_inputs().
 1215: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1216: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1217: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1218:     if (exists($env{'form.Status'})) {
 1219: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
 1220:     } else {
 1221:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1222:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1223:                       .&Apache::lonhtmlcommon::StatusOptions(
 1224:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1225:     }
 1226:     if ($numessay) {
 1227:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1228:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1229:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1230:     }
 1231:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1232:                   .&Apache::lonhtmlcommon::end_pick_box();
 1233:     my $regrademsg;
 1234:     if ($is_tool) {
 1235:         $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.");
 1236:     } else {
 1237:         $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.");
 1238:     }
 1239:     $gradeTable .= '<p>'
 1240:                   .$regrademsg."\n"
 1241:                   .'<input type="hidden" name="command" value="processGroup" />'
 1242:                   .'</p>';
 1243: 
 1244: # checkall buttons
 1245:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1246:     $gradeTable.='<input type="button" '."\n".
 1247:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1248:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1249:     $gradeTable.=&check_buttons();
 1250:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1251:     $gradeTable.= &Apache::loncommon::start_data_table().
 1252: 	&Apache::loncommon::start_data_table_header_row();
 1253:     my $loop = 0;
 1254:     while ($loop < 2) {
 1255: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1256: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1257: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1258: 	    foreach my $part (sort(@$partlist)) {
 1259: 		my $display_part=
 1260: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1261: 		$gradeTable.=
 1262: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1263: 	    }
 1264: 	} elsif ($submitonly eq 'queued') {
 1265: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1266: 	}
 1267: 	$loop++;
 1268: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1269:     }
 1270:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1271: 
 1272:     my $ctr = 0;
 1273:     foreach my $student (sort 
 1274: 			 {
 1275: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1276: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1277: 			     }
 1278: 			     return $a cmp $b;
 1279: 			 }
 1280: 			 (keys(%$fullname))) {
 1281: 	my ($uname,$udom) = split(/:/,$student);
 1282: 
 1283: 	my %status = ();
 1284: 
 1285: 	if ($submitonly eq 'queued') {
 1286: 	    my %queue_status = 
 1287: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1288: 							$udom,$uname);
 1289: 	    next if (!defined($queue_status{'gradingqueue'}));
 1290: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1291: 	}
 1292: 
 1293: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1294: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1295: 	    my $submitted = 0;
 1296: 	    my $graded = 0;
 1297: 	    my $incorrect = 0;
 1298: 	    foreach (keys(%status)) {
 1299: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1300: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1301: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1302: 		
 1303: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1304: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1305: 		    $submitted = 0;
 1306: 		    my ($part)=split(/\./,$partid);
 1307: 		    $gradeTable.='<input type="hidden" name="'.
 1308: 			$student.':'.$part.':submitted_by" value="'.
 1309: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1310: 		}
 1311: 	    }
 1312: 	    
 1313: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1314: 				     $submitonly eq 'incorrect' ||
 1315: 				     $submitonly eq 'graded'));
 1316: 	    next if (!$graded && ($submitonly eq 'graded'));
 1317: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1318: 	}
 1319: 
 1320: 	$ctr++;
 1321: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1322:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1323: 	if ( $perm{'vgr'} eq 'F' ) {
 1324: 	    if ($ctr%2 ==1) {
 1325: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1326: 	    }
 1327: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1328:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1329:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1330: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1331: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1332: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1333: 
 1334: 	    if ($submitonly ne 'all') {
 1335: 		foreach (sort(keys(%status))) {
 1336: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1337: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1338: 		}
 1339: 	    }
 1340: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1341: 	    if ($ctr%2 ==0) {
 1342: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1343: 	    }
 1344: 	}
 1345:     }
 1346:     if ($ctr%2 ==1) {
 1347: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1348: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1349: 		foreach (@$partlist) {
 1350: 		    $gradeTable.='<td>&nbsp;</td>';
 1351: 		}
 1352: 	    } elsif ($submitonly eq 'queued') {
 1353: 		$gradeTable.='<td>&nbsp;</td>';
 1354: 	    }
 1355: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1356:     }
 1357: 
 1358:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1359:         '<input type="button" '.
 1360:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1361:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1362:     if ($ctr == 0) {
 1363: 	my $num_students=(scalar(keys(%$fullname)));
 1364: 	if ($num_students eq 0) {
 1365: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1366: 	} else {
 1367: 	    my $submissions='submissions';
 1368: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1369: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1370: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1371: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1372: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1373: 		    $num_students).
 1374: 		'</span><br />';
 1375: 	}
 1376:     } elsif ($ctr == 1) {
 1377: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1378:     }
 1379:     $request->print($gradeTable);
 1380:     return '';
 1381: }
 1382: 
 1383: #---- Called from the listStudents routine
 1384: 
 1385: sub check_script {
 1386:     my ($form,$type) = @_;
 1387:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1388:     function checkall() {
 1389:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1390:             ele = document.forms.'.$form.'.elements[i];
 1391:             if (ele.name == "'.$type.'") {
 1392:             document.forms.'.$form.'.elements[i].checked=true;
 1393:                                        }
 1394:         }
 1395:     }
 1396: 
 1397:     function checksec() {
 1398:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1399:             ele = document.forms.'.$form.'.elements[i];
 1400:            string = document.forms.'.$form.'.chksec.value;
 1401:            if
 1402:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1403:               document.forms.'.$form.'.elements[i].checked=true;
 1404:             }
 1405:         }
 1406:     }
 1407: 
 1408: 
 1409:     function uncheckall() {
 1410:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1411:             ele = document.forms.'.$form.'.elements[i];
 1412:             if (ele.name == "'.$type.'") {
 1413:             document.forms.'.$form.'.elements[i].checked=false;
 1414:                                        }
 1415:         }
 1416:     }
 1417: 
 1418: '."\n");
 1419:     return $chkallscript;
 1420: }
 1421: 
 1422: sub check_buttons {
 1423:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1424:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1425:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1426:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1427:     return $buttons;
 1428: }
 1429: 
 1430: #     Displays the submissions for one student or a group of students
 1431: sub processGroup {
 1432:     my ($request,$symb) = @_;
 1433:     my $ctr        = 0;
 1434:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1435:     my $total      = scalar(@stuchecked)-1;
 1436: 
 1437:     foreach my $student (@stuchecked) {
 1438: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1439: 	$env{'form.student'}        = $uname;
 1440: 	$env{'form.userdom'}        = $udom;
 1441: 	$env{'form.fullname'}       = $fullname;
 1442: 	&submission($request,$ctr,$total,$symb);
 1443: 	$ctr++;
 1444:     }
 1445:     return '';
 1446: }
 1447: 
 1448: #------------------------------------------------------------------------------------
 1449: #
 1450: #-------------------------- Next few routines handles grading by student, essentially
 1451: #                           handles essay response type problem/part
 1452: #
 1453: #--- Javascript to handle the submission page functionality ---
 1454: sub sub_page_js {
 1455:     my $request = shift;
 1456:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1457:     &js_escape(\$alertmsg);
 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1459:     function updateRadio(formname,id,weight) {
 1460: 	var gradeBox = formname["GD_BOX"+id];
 1461: 	var radioButton = formname["RADVAL"+id];
 1462: 	var oldpts = formname["oldpts"+id].value;
 1463: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1464: 	gradeBox.value = pts;
 1465: 	var resetbox = false;
 1466: 	if (isNaN(pts) || pts < 0) {
 1467: 	    alert("$alertmsg"+pts);
 1468: 	    for (var i=0; i<radioButton.length; i++) {
 1469: 		if (radioButton[i].checked) {
 1470: 		    gradeBox.value = i;
 1471: 		    resetbox = true;
 1472: 		}
 1473: 	    }
 1474: 	    if (!resetbox) {
 1475: 		formtextbox.value = "";
 1476: 	    }
 1477: 	    return;
 1478: 	}
 1479: 
 1480: 	if (pts > weight) {
 1481: 	    var resp = confirm("You entered a value ("+pts+
 1482: 			       ") greater than the weight for the part. Accept?");
 1483: 	    if (resp == false) {
 1484: 		gradeBox.value = oldpts;
 1485: 		return;
 1486: 	    }
 1487: 	}
 1488: 
 1489: 	for (var i=0; i<radioButton.length; i++) {
 1490: 	    radioButton[i].checked=false;
 1491: 	    if (pts == i && pts != "") {
 1492: 		radioButton[i].checked=true;
 1493: 	    }
 1494: 	}
 1495: 	updateSelect(formname,id);
 1496: 	formname["stores"+id].value = "0";
 1497:     }
 1498: 
 1499:     function writeBox(formname,id,pts) {
 1500: 	var gradeBox = formname["GD_BOX"+id];
 1501: 	if (checkSolved(formname,id) == 'update') {
 1502: 	    gradeBox.value = pts;
 1503: 	} else {
 1504: 	    var oldpts = formname["oldpts"+id].value;
 1505: 	    gradeBox.value = oldpts;
 1506: 	    var radioButton = formname["RADVAL"+id];
 1507: 	    for (var i=0; i<radioButton.length; i++) {
 1508: 		radioButton[i].checked=false;
 1509: 		if (i == oldpts) {
 1510: 		    radioButton[i].checked=true;
 1511: 		}
 1512: 	    }
 1513: 	}
 1514: 	formname["stores"+id].value = "0";
 1515: 	updateSelect(formname,id);
 1516: 	return;
 1517:     }
 1518: 
 1519:     function clearRadBox(formname,id) {
 1520: 	if (checkSolved(formname,id) == 'noupdate') {
 1521: 	    updateSelect(formname,id);
 1522: 	    return;
 1523: 	}
 1524: 	gradeSelect = formname["GD_SEL"+id];
 1525: 	for (var i=0; i<gradeSelect.length; i++) {
 1526: 	    if (gradeSelect[i].selected) {
 1527: 		var selectx=i;
 1528: 	    }
 1529: 	}
 1530: 	var stores = formname["stores"+id];
 1531: 	if (selectx == stores.value) { return };
 1532: 	var gradeBox = formname["GD_BOX"+id];
 1533: 	gradeBox.value = "";
 1534: 	var radioButton = formname["RADVAL"+id];
 1535: 	for (var i=0; i<radioButton.length; i++) {
 1536: 	    radioButton[i].checked=false;
 1537: 	}
 1538: 	stores.value = selectx;
 1539:     }
 1540: 
 1541:     function checkSolved(formname,id) {
 1542: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1543: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1544: 	    if (!reply) {return "noupdate";}
 1545: 	    formname.overRideScore.value = 'yes';
 1546: 	}
 1547: 	return "update";
 1548:     }
 1549: 
 1550:     function updateSelect(formname,id) {
 1551: 	formname["GD_SEL"+id][0].selected = true;
 1552: 	return;
 1553:     }
 1554: 
 1555: //=========== Check that a point is assigned for all the parts  ============
 1556:     function checksubmit(formname,val,total,parttot) {
 1557: 	formname.gradeOpt.value = val;
 1558: 	if (val == "Save & Next") {
 1559: 	    for (i=0;i<=total;i++) {
 1560: 		for (j=0;j<parttot;j++) {
 1561: 		    var partid = formname["partid"+i+"_"+j].value;
 1562: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1563: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1564: 			if (points == "") {
 1565: 			    var name = formname["name"+i].value;
 1566: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1567: 			    var resp = confirm("You did not assign a score for "+studentID+
 1568: 					       ", part "+partid+". Continue?");
 1569: 			    if (resp == false) {
 1570: 				formname["GD_BOX"+i+"_"+partid].focus();
 1571: 				return false;
 1572: 			    }
 1573: 			}
 1574: 		    }
 1575: 		}
 1576: 	    }
 1577: 	}
 1578: 	formname.submit();
 1579:     }
 1580: 
 1581: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1582:     function checkSubmitPage(formname,total) {
 1583: 	noscore = new Array(100);
 1584: 	var ptr = 0;
 1585: 	for (i=1;i<total;i++) {
 1586: 	    var partid = formname["q_"+i].value;
 1587: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1588: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1589: 		var status = formname["solved"+i+"_"+partid].value;
 1590: 		if (points == "" && status != "correct_by_student") {
 1591: 		    noscore[ptr] = i;
 1592: 		    ptr++;
 1593: 		}
 1594: 	    }
 1595: 	}
 1596: 	if (ptr != 0) {
 1597: 	    var sense = ptr == 1 ? ": " : "s: ";
 1598: 	    var prolist = "";
 1599: 	    if (ptr == 1) {
 1600: 		prolist = noscore[0];
 1601: 	    } else {
 1602: 		var i = 0;
 1603: 		while (i < ptr-1) {
 1604: 		    prolist += noscore[i]+", ";
 1605: 		    i++;
 1606: 		}
 1607: 		prolist += "and "+noscore[i];
 1608: 	    }
 1609: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1610: 	    if (resp == false) {
 1611: 		return false;
 1612: 	    }
 1613: 	}
 1614: 
 1615: 	formname.submit();
 1616:     }
 1617: SUBJAVASCRIPT
 1618: }
 1619: 
 1620: #--- javascript for grading message center
 1621: sub sub_grademessage_js {
 1622:     my $request = shift;
 1623:     my $iconpath = $request->dir_config('lonIconsURL');
 1624:     &commonJSfunctions($request);
 1625: 
 1626:     my $inner_js_msg_central= (<<INNERJS);
 1627: <script type="text/javascript">
 1628:     function checkInput() {
 1629:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1630:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1631:       var usrctr = document.msgcenter.usrctr.value;
 1632:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1633:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1634: 
 1635:       var msgchk = "";
 1636:       if (document.msgcenter.subchk.checked) {
 1637:          msgchk = "msgsub,";
 1638:       }
 1639:       var includemsg = 0;
 1640:       for (var i=1; i<=nmsg; i++) {
 1641:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1642:           var frmmsg = document.msgcenter["msg"+i];
 1643:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1644:           var showflg = opener.document.SCORE["shownOnce"+i];
 1645:           showflg.value = "1";
 1646:           var chkbox = document.msgcenter["msgn"+i];
 1647:           if (chkbox.checked) {
 1648:              msgchk += "savemsg"+i+",";
 1649:              includemsg = 1;
 1650:           }
 1651:       }
 1652:       if (document.msgcenter.newmsgchk.checked) {
 1653:          msgchk += "newmsg"+usrctr;
 1654:          includemsg = 1;
 1655:       }
 1656:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1657:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1658:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1659:       includemsg.value = msgchk;
 1660: 
 1661:       self.close()
 1662: 
 1663:     }
 1664: </script>
 1665: INNERJS
 1666: 
 1667:     my $start_page_msg_central =
 1668:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1669: 				       {'js_ready'  => 1,
 1670: 					'only_body' => 1,
 1671: 					'bgcolor'   =>'#FFFFFF',});
 1672:     my $end_page_msg_central =
 1673: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1674: 
 1675:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1676:     $docopen=~s/^document\.//;
 1677: 
 1678:     my %html_js_lt = &Apache::lonlocal::texthash(
 1679:                 comp => 'Compose Message for: ',
 1680:                 incl => 'Include',
 1681:                 type => 'Type',
 1682:                 subj => 'Subject',
 1683:                 mesa => 'Message',
 1684:                 new  => 'New',
 1685:                 save => 'Save',
 1686:                 canc => 'Cancel',
 1687:              );
 1688:     &html_escape(\%html_js_lt);
 1689:     &js_escape(\%html_js_lt);
 1690:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1691: 
 1692: //===================== Script to view submitted by ==================
 1693:   function viewSubmitter(submitter) {
 1694:     document.SCORE.refresh.value = "on";
 1695:     document.SCORE.NCT.value = "1";
 1696:     document.SCORE.unamedom0.value = submitter;
 1697:     document.SCORE.submit();
 1698:     return;
 1699:   }
 1700: 
 1701: //====================== Script for composing message ==============
 1702:    // preload images
 1703:    img1 = new Image();
 1704:    img1.src = "$iconpath/mailbkgrd.gif";
 1705:    img2 = new Image();
 1706:    img2.src = "$iconpath/mailto.gif";
 1707: 
 1708:   function msgCenter(msgform,usrctr,fullname) {
 1709:     var Nmsg  = msgform.savemsgN.value;
 1710:     savedMsgHeader(Nmsg,usrctr,fullname);
 1711:     var subject = msgform.msgsub.value;
 1712:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1713:     re = /msgsub/;
 1714:     var shwsel = "";
 1715:     if (re.test(msgchk)) { shwsel = "checked" }
 1716:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1717:     displaySubject(checkEntities(subject),shwsel);
 1718:     for (var i=1; i<=Nmsg; i++) {
 1719: 	var testmsg = "savemsg"+i+",";
 1720: 	re = new RegExp(testmsg,"g");
 1721: 	shwsel = "";
 1722: 	if (re.test(msgchk)) { shwsel = "checked" }
 1723: 	var message = document.SCORE["savemsg"+i].value;
 1724: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1725: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1726: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1727:     }
 1728:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1729:     shwsel = "";
 1730:     re = /newmsg/;
 1731:     if (re.test(msgchk)) { shwsel = "checked" }
 1732:     newMsg(newmsg,shwsel);
 1733:     msgTail(); 
 1734:     return;
 1735:   }
 1736: 
 1737:   function checkEntities(strx) {
 1738:     if (strx.length == 0) return strx;
 1739:     var orgStr = ["&", "<", ">", '"']; 
 1740:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1741:     var counter = 0;
 1742:     while (counter < 4) {
 1743: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1744: 	counter++;
 1745:     }
 1746:     return strx;
 1747:   }
 1748: 
 1749:   function strReplace(strx, orgStr, newStr) {
 1750:     return strx.split(orgStr).join(newStr);
 1751:   }
 1752: 
 1753:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1754:     var height = 70*Nmsg+250;
 1755:     if (height > 600) {
 1756: 	height = 600;
 1757:     }
 1758:     var xpos = (screen.width-600)/2;
 1759:     xpos = (xpos < 0) ? '0' : xpos;
 1760:     var ypos = (screen.height-height)/2-30;
 1761:     ypos = (ypos < 0) ? '0' : ypos;
 1762: 
 1763:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1764:     pWin.focus();
 1765:     pDoc = pWin.document;
 1766:     pDoc.$docopen;
 1767:     pDoc.write('$start_page_msg_central');
 1768: 
 1769:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1770:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1771:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1772: 
 1773:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1774:     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>");
 1775: }
 1776:     function displaySubject(msg,shwsel) {
 1777:     pDoc = pWin.document;
 1778:     pDoc.write("<tr>");
 1779:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1780:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1781:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1782: }
 1783: 
 1784:   function displaySavedMsg(ctr,msg,shwsel) {
 1785:     pDoc = pWin.document;
 1786:     pDoc.write("<tr>");
 1787:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1788:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1789:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1790: }
 1791: 
 1792:   function newMsg(newmsg,shwsel) {
 1793:     pDoc = pWin.document;
 1794:     pDoc.write("<tr>");
 1795:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1796:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1797:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1798: }
 1799: 
 1800:   function msgTail() {
 1801:     pDoc = pWin.document;
 1802:     //pDoc.write("<\\/table>");
 1803:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1804:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1805:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1806:     pDoc.write("<\\/form>");
 1807:     pDoc.write('$end_page_msg_central');
 1808:     pDoc.close();
 1809: }
 1810: 
 1811: SUBJAVASCRIPT
 1812: }
 1813: 
 1814: #--- javascript for essay type problem --
 1815: sub sub_page_kw_js {
 1816:     my $request = shift;
 1817: 
 1818:     unless ($env{'form.compmsg'}) {
 1819:         &commonJSfunctions($request);
 1820:     }
 1821: 
 1822:     my $inner_js_highlight_central= (<<INNERJS);
 1823: <script type="text/javascript">
 1824:     function updateChoice(flag) {
 1825:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1826:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1827:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1828:       opener.document.SCORE.refresh.value = "on";
 1829:       if (opener.document.SCORE.keywords.value!=""){
 1830:          opener.document.SCORE.submit();
 1831:       }
 1832:       self.close()
 1833:     }
 1834: </script>
 1835: INNERJS
 1836: 
 1837:     my $start_page_highlight_central =
 1838:         &Apache::loncommon::start_page('Highlight Central',
 1839:                                        $inner_js_highlight_central,
 1840:                                        {'js_ready'  => 1,
 1841:                                         'only_body' => 1,
 1842:                                         'bgcolor'   =>'#FFFFFF',});
 1843:     my $end_page_highlight_central =
 1844:         &Apache::loncommon::end_page({'js_ready' => 1});
 1845: 
 1846:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1847:     $docopen=~s/^document\.//;
 1848: 
 1849:     my %js_lt = &Apache::lonlocal::texthash(
 1850:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1851:                 plse => 'Please select a word or group of words from document and then click this link.',
 1852:                 adds => 'Add selection to keyword list? Edit if desired.',
 1853:                 col1 => 'red',
 1854:                 col2 => 'green',
 1855:                 col3 => 'blue',
 1856:                 siz1 => 'normal',
 1857:                 siz2 => '+1',
 1858:                 siz3 => '+2',
 1859:                 sty1 => 'normal',
 1860:                 sty2 => 'italic',
 1861:                 sty3 => 'bold',
 1862:              );
 1863:     my %html_js_lt = &Apache::lonlocal::texthash(
 1864:                 save => 'Save',
 1865:                 canc => 'Cancel',
 1866:                 kehi => 'Keyword Highlight Options',
 1867:                 txtc => 'Text Color',
 1868:                 font => 'Font Size',
 1869:                 fnst => 'Font Style',
 1870:              );
 1871:     &js_escape(\%js_lt);
 1872:     &html_escape(\%html_js_lt);
 1873:     &js_escape(\%html_js_lt);
 1874:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1875: 
 1876: //===================== Show list of keywords ====================
 1877:   function keywords(formname) {
 1878:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1879:     if (nret==null) return;
 1880:     formname.keywords.value = nret;
 1881: 
 1882:     if (formname.keywords.value != "") {
 1883:         formname.refresh.value = "on";
 1884:         formname.submit();
 1885:     }
 1886:     return;
 1887:   }
 1888: 
 1889: //===================== Script to add keyword(s) ==================
 1890:   function getSel() {
 1891:     if (document.getSelection) txt = document.getSelection();
 1892:     else if (document.selection) txt = document.selection.createRange().text;
 1893:     else return;
 1894:     if (typeof(txt) != 'string') {
 1895:         txt = String(txt);
 1896:     }
 1897:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1898:     if (cleantxt=="") {
 1899:         alert("$js_lt{'plse'}");
 1900:         return;
 1901:     }
 1902:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1903:     if (nret==null) return;
 1904:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1905:     if (document.SCORE.keywords.value != "") {
 1906:         document.SCORE.refresh.value = "on";
 1907:         document.SCORE.submit();
 1908:     }
 1909:     return;
 1910:   }
 1911: 
 1912: //====================== Script for keyword highlight options ==============
 1913:   function kwhighlight() {
 1914:     var kwclr    = document.SCORE.kwclr.value;
 1915:     var kwsize   = document.SCORE.kwsize.value;
 1916:     var kwstyle  = document.SCORE.kwstyle.value;
 1917:     var redsel = "";
 1918:     var grnsel = "";
 1919:     var blusel = "";
 1920:     var txtcol1 = "$js_lt{'col1'}";
 1921:     var txtcol2 = "$js_lt{'col2'}";
 1922:     var txtcol3 = "$js_lt{'col3'}";
 1923:     var txtsiz1 = "$js_lt{'siz1'}";
 1924:     var txtsiz2 = "$js_lt{'siz2'}";
 1925:     var txtsiz3 = "$js_lt{'siz3'}";
 1926:     var txtsty1 = "$js_lt{'sty1'}";
 1927:     var txtsty2 = "$js_lt{'sty2'}";
 1928:     var txtsty3 = "$js_lt{'sty3'}";
 1929:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1930:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1931:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1932:     var sznsel = "";
 1933:     var sz1sel = "";
 1934:     var sz2sel = "";
 1935:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1936:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1937:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1938:     var synsel = "";
 1939:     var syisel = "";
 1940:     var sybsel = "";
 1941:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1942:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1943:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1944:     highlightCentral();
 1945:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1946:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1947:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1948:     highlightend();
 1949:     return;
 1950:   }
 1951: 
 1952:   function highlightCentral() {
 1953: //    if (window.hwdWin) window.hwdWin.close();
 1954:     var xpos = (screen.width-400)/2;
 1955:     xpos = (xpos < 0) ? '0' : xpos;
 1956:     var ypos = (screen.height-330)/2-30;
 1957:     ypos = (ypos < 0) ? '0' : ypos;
 1958: 
 1959:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1960:     hwdWin.focus();
 1961:     var hDoc = hwdWin.document;
 1962:     hDoc.$docopen;
 1963:     hDoc.write('$start_page_highlight_central');
 1964:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1965:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1966: 
 1967:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1968:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1969:   }
 1970: 
 1971:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1972:     var hDoc = hwdWin.document;
 1973:     hDoc.write("<tr>");
 1974:     hDoc.write("<td align=\\"left\\">");
 1975:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1976:     hDoc.write("<td align=\\"left\\">");
 1977:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1978:     hDoc.write("<td align=\\"left\\">");
 1979:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1980:     hDoc.write("<\\/tr>");
 1981:   }
 1982: 
 1983:   function highlightend() { 
 1984:     var hDoc = hwdWin.document;
 1985:     hDoc.write("<\\/table><br \\/>");
 1986:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1987:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1988:     hDoc.write("<\\/form>");
 1989:     hDoc.write('$end_page_highlight_central');
 1990:     hDoc.close();
 1991:   }
 1992: 
 1993: SUBJAVASCRIPT
 1994: }
 1995: 
 1996: sub get_increment {
 1997:     my $increment = $env{'form.increment'};
 1998:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1999:         $increment != .1) {
 2000:         $increment = 1;
 2001:     }
 2002:     return $increment;
 2003: }
 2004: 
 2005: sub gradeBox_start {
 2006:     return (
 2007:         &Apache::loncommon::start_data_table()
 2008:        .&Apache::loncommon::start_data_table_header_row()
 2009:        .'<th>'.&mt('Part').'</th>'
 2010:        .'<th>'.&mt('Points').'</th>'
 2011:        .'<th>&nbsp;</th>'
 2012:        .'<th>'.&mt('Assign Grade').'</th>'
 2013:        .'<th>'.&mt('Weight').'</th>'
 2014:        .'<th>'.&mt('Grade Status').'</th>'
 2015:        .&Apache::loncommon::end_data_table_header_row()
 2016:     );
 2017: }
 2018: 
 2019: sub gradeBox_end {
 2020:     return (
 2021:         &Apache::loncommon::end_data_table()
 2022:     );
 2023: }
 2024: #--- displays the grading box, used in essay type problem and grading by page/sequence
 2025: sub gradeBox {
 2026:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 2027:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2028: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2029:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2030:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2031:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2032:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2033:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2034: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2035:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2036:     my $display_part= &get_display_part($partid,$symb);
 2037:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2038: 				       [$partid]);
 2039:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2040:     if ($last_resets{$partid}) {
 2041:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2042:     }
 2043:     my $result=&Apache::loncommon::start_data_table_row();
 2044:     my $ctr = 0;
 2045:     my $thisweight = 0;
 2046:     my $increment = &get_increment();
 2047: 
 2048:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2049:     while ($thisweight<=$wgt) {
 2050: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2051:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2052: 	    $thisweight.')" value="'.$thisweight.'" '.
 2053: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2054: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2055:         $thisweight += $increment;
 2056: 	$ctr++;
 2057:     }
 2058:     $radio.='</tr></table>';
 2059: 
 2060:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2061: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2062: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2063: 	$wgt.')" /></td>'."\n";
 2064:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2065: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2066: 	' </td>'."\n";
 2067:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2068: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2069:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2070: 	$line.='<option></option>'.
 2071: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2072:     } else {
 2073: 	$line.='<option selected="selected"></option>'.
 2074: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2075:     }
 2076:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2077: 
 2078: 
 2079:     $result .= 
 2080: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2081:     $result.=&Apache::loncommon::end_data_table_row();
 2082:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2083:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2084: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2085: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2086: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2087:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2088:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2089:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2090:         $aggtries.'" />'."\n";
 2091:     my $res_error;
 2092:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2093:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2094:     if ($res_error) {
 2095:         return &navmap_errormsg();
 2096:     }
 2097:     return $result;
 2098: }
 2099: 
 2100: sub handback_box {
 2101:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2102:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2103:     return unless ($numessay);
 2104:     my (@respids);
 2105:     my @part_response_id = &flatten_responseType($responseType);
 2106:     foreach my $part_response_id (@part_response_id) {
 2107:     	my ($part,$resp) = @{ $part_response_id };
 2108:         if ($part eq $partid) {
 2109:             push(@respids,$resp);
 2110:         }
 2111:     }
 2112:     my $result;
 2113:     foreach my $respid (@respids) {
 2114: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2115: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2116: 	next if (!@$files);
 2117: 	my $file_counter = 0;
 2118: 	foreach my $file (@$files) {
 2119: 	    if ($file =~ /\/portfolio\//) {
 2120:                 $file_counter++;
 2121:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2122:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2123:     	        $file_disp = "$name.$ext";
 2124:     	        $file = $file_path.$file_disp;
 2125:     	        $result.=&mt('Return commented version of [_1] to student.',
 2126:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2127:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2128:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2129: 	    }
 2130: 	}
 2131:         if ($file_counter) {
 2132:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2133:                        '<span class="LC_info">'.
 2134:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2135:         }
 2136:     }
 2137:     return $result;    
 2138: }
 2139: 
 2140: sub show_problem {
 2141:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2142:     my $rendered;
 2143:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2144:     &Apache::lonxml::remember_problem_counter();
 2145:     if ($mode eq 'both' or $mode eq 'text') {
 2146: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2147: 						       $env{'request.course.id'},
 2148: 						       undef,\%form);
 2149:     }
 2150:     if ($removeform) {
 2151: 	$rendered=~s|<form(.*?)>||g;
 2152: 	$rendered=~s|</form>||g;
 2153: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2154:     }
 2155:     my $companswer;
 2156:     if ($mode eq 'both' or $mode eq 'answer') {
 2157: 	&Apache::lonxml::restore_problem_counter();
 2158: 	$companswer=
 2159: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2160: 						    $env{'request.course.id'},
 2161: 						    %form);
 2162:     }
 2163:     if ($removeform) {
 2164: 	$companswer=~s|<form(.*?)>||g;
 2165: 	$companswer=~s|</form>||g;
 2166: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2167:     }
 2168:     my $renderheading = &mt('View of the problem');
 2169:     my $answerheading = &mt('Correct answer');
 2170:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2171:         my $stu_fullname = $env{'form.fullname'};
 2172:         if ($stu_fullname eq '') {
 2173:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2174:         }
 2175:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2176:         if ($forwhom ne '') {
 2177:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2178:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2179:         }
 2180:     }
 2181:     $rendered=
 2182:         '<div class="LC_Box">'
 2183:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2184:        .$rendered
 2185:        .'</div>';
 2186:     $companswer=
 2187:         '<div class="LC_Box">'
 2188:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2189:        .$companswer
 2190:        .'</div>';
 2191:     my $result;
 2192:     if ($mode eq 'both') {
 2193:         $result=$rendered.$companswer;
 2194:     } elsif ($mode eq 'text') {
 2195:         $result=$rendered;
 2196:     } elsif ($mode eq 'answer') {
 2197:         $result=$companswer;
 2198:     }
 2199:     return $result;
 2200: }
 2201: 
 2202: sub files_exist {
 2203:     my ($r, $symb) = @_;
 2204:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2205:     foreach my $student (@students) {
 2206:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2207:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2208: 					      $udom,$uname);
 2209:         my ($string,$timestamp)= &get_last_submission(\%record);
 2210:         foreach my $submission (@$string) {
 2211:             my ($partid,$respid) =
 2212: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2213:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2214: 					   \%record);
 2215:             return 1 if (@$files);
 2216:         }
 2217:     }
 2218:     return 0;
 2219: }
 2220: 
 2221: sub download_all_link {
 2222:     my ($r,$symb) = @_;
 2223:     unless (&files_exist($r, $symb)) {
 2224:         $r->print(&mt('There are currently no submitted documents.'));
 2225:         return;
 2226:     }
 2227:     my $all_students = 
 2228: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2229: 
 2230:     my $parts =
 2231: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2232: 
 2233:     my $identifier = &Apache::loncommon::get_cgi_id();
 2234:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2235:                              'cgi.'.$identifier.'.symb' => $symb,
 2236:                              'cgi.'.$identifier.'.parts' => $parts,});
 2237:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2238: 	      &mt('Download All Submitted Documents').'</a>');
 2239:     return;
 2240: }
 2241: 
 2242: sub submit_download_link {
 2243:     my ($request,$symb) = @_;
 2244:     if (!$symb) { return ''; }
 2245:     my $res_error;
 2246:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2247:         &response_type($symb,\$res_error);
 2248:     if ($res_error) {
 2249:         $request->print(&mt('An error occurred retrieving response types'));
 2250:         return;
 2251:     }
 2252:     unless ($numessay) {
 2253:         $request->print(&mt('No essayresponse items found'));
 2254:         return;
 2255:     }
 2256:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2257:     if (@chosenparts) {
 2258:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2259:                                           undef,undef,1));
 2260:     }
 2261:     if ($numessay) {
 2262:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2263:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2264:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2265:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2266:         if (ref($fullname) eq 'HASH') {
 2267:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2268:             if (@students) {
 2269:                 @{$env{'form.stuinfo'}} = @students;
 2270:                 if ($numdropbox) {
 2271:                     &download_all_link($request,$symb);
 2272:                 } else {
 2273:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2274:                 }
 2275: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2276: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2277:             } else {
 2278:                 $request->print(&mt('No students match the criteria you selected'));
 2279:             }
 2280:         } else {
 2281:             $request->print(&mt('Could not retrieve student information'));
 2282:         }
 2283:     } else {
 2284:         $request->print(&mt('No essayresponse items found'));
 2285:     }
 2286:     return;
 2287: }
 2288: 
 2289: sub build_section_inputs {
 2290:     my $section_inputs;
 2291:     if ($env{'form.section'} eq '') {
 2292:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2293:     } else {
 2294:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2295:         foreach my $section (@sections) {
 2296:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2297:         }
 2298:     }
 2299:     return $section_inputs;
 2300: }
 2301: 
 2302: # --------------------------- show submissions of a student, option to grade 
 2303: sub submission {
 2304:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2305:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2306:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2307:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2308:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2309: 
 2310:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2311:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2312:     my $is_tool = ($symb =~ /ext\.tool$/);
 2313:     my ($essayurl,%coursedesc_by_cid);
 2314: 
 2315:     if (!&canview($usec)) {
 2316:         $request->print(
 2317:             '<span class="LC_warning">'.
 2318:             &mt('Unable to view requested student.').
 2319:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2320:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2321:             '</span>');
 2322: 	return;
 2323:     }
 2324: 
 2325:     my $res_error;
 2326:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2327:         &response_type($symb,\$res_error);
 2328:     if ($res_error) {
 2329:         $request->print(&navmap_errormsg());
 2330:         return;
 2331:     }
 2332: 
 2333:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2334:     unless ($is_tool) { 
 2335:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2336:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2337:     }
 2338:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2339:         $env{'form.compmsg'} = 1;
 2340:     }
 2341:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2342:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2343: 	'" src="'.$request->dir_config('lonIconsURL').
 2344: 	'/check.gif" height="16" border="0" />';
 2345: 
 2346:     # header info
 2347:     if ($counter == 0) {
 2348:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2349:         if (@chosenparts) {
 2350:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2351:         } elsif ($divforres) {
 2352:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2353:         } else {
 2354:             $request->print('<br clear="all" />');
 2355:         }
 2356: 	&sub_page_js($request);
 2357:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2358: 	&sub_page_kw_js($request) if ($numessay);
 2359: 
 2360: 	# option to display problem, only once else it cause problems 
 2361:         # with the form later since the problem has a form.
 2362: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2363: 	    my $mode;
 2364: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2365: 		$mode='both';
 2366: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2367: 		$mode='text';
 2368: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2369: 		$mode='answer';
 2370: 	    }
 2371: 	    &Apache::lonxml::clear_problem_counter();
 2372: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2373: 	}
 2374: 
 2375: 	my %keyhash = ();
 2376: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2377: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2378: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2379: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2380: 	}
 2381: 	# kwclr is the only variable that is guaranteed not to be blank
 2382: 	# if this subroutine has been called once.
 2383: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2384: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2385: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2386: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2387: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2388: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2389: 	}
 2390: 	if ($env{'form.compmsg'}) {
 2391: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2392: 		$keyhash{$symb.'_subject'} : $probtitle;
 2393: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2394: 	}
 2395: 
 2396: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2397: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2398: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2399: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2400: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2401: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2402: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2403: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2404: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2405: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2406: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2407: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2408: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2409: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2410: 			&build_section_inputs().
 2411: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2412: 			'<input type="hidden" name="NCT"'.
 2413: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2414: 	if ($env{'form.compmsg'}) {
 2415: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2416: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2417: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2418: 	}
 2419: 	if ($numessay) {
 2420: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2421: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2422: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2423: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2424: 	}
 2425: 
 2426: 	my ($cts,$prnmsg) = (1,'');
 2427: 	while ($cts <= $env{'form.savemsgN'}) {
 2428: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2429: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2430: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2431: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2432: 		'" />'."\n".
 2433: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2434: 	    $cts++;
 2435: 	}
 2436: 	$request->print($prnmsg);
 2437: 
 2438: 	if ($numessay) {
 2439: 
 2440:             my %lt = &Apache::lonlocal::texthash(
 2441:                           keyh => 'Keyword Highlighting for Essays',
 2442:                           keyw => 'Keyword Options',
 2443:                           list => 'List',
 2444:                           past => 'Paste Selection to List',
 2445:                           high => 'Highlight Attribute',
 2446:                      );
 2447: #
 2448: # Print out the keyword options line
 2449: #
 2450: 	    $request->print(
 2451:                 '<div class="LC_columnSection">'
 2452:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2453:                .&Apache::lonhtmlcommon::funclist_from_array(
 2454:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2455:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2456:  class="page">'.$lt{'past'}.'</a>',
 2457:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2458:                     {legend => $lt{'keyw'}})
 2459:                .'</fieldset></div>'
 2460:             );
 2461: 
 2462: #
 2463: # Load the other essays for similarity check
 2464: #
 2465:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2466:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2467:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2468:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2469:                 if ($cdom ne '' && $cnum ne '') {
 2470:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2471:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2472:                         my $apath = $1.'_'.$id;
 2473:                         $apath=~s/\W/\_/gs;
 2474:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2475:                     }
 2476:                 }
 2477:             } else {
 2478: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2479: 	        $apath=&escape($apath);
 2480: 	        $apath=~s/\W/\_/gs;
 2481:                 &init_old_essays($symb,$apath,$adom,$aname);
 2482:             }
 2483:         }
 2484:     }
 2485: 
 2486: # This is where output for one specific student would start
 2487:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2488:     $request->print(
 2489:         "\n\n"
 2490:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2491:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2492:        ."\n"
 2493:     );
 2494: 
 2495:     # Show additional functions if allowed
 2496:     if ($perm{'vgr'}) {
 2497:         $request->print(
 2498:             &Apache::loncommon::track_student_link(
 2499:                 'View recent activity',
 2500:                 $uname,$udom,'check')
 2501:            .' '
 2502:         );
 2503:     }
 2504:     if ($perm{'opa'}) {
 2505:         $request->print(
 2506:             &Apache::loncommon::pprmlink(
 2507:                 &mt('Set/Change parameters'),
 2508:                 $uname,$udom,$symb,'check'));
 2509:     }
 2510: 
 2511:     # Show Problem
 2512:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2513: 	my $mode;
 2514: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2515: 	    $mode='both';
 2516: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2517: 	    $mode='text';
 2518: 	} elsif ($env{'form.vAns'} eq 'all') {
 2519: 	    $mode='answer';
 2520: 	}
 2521: 	&Apache::lonxml::clear_problem_counter();
 2522: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2523:     }
 2524: 
 2525:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2526: 
 2527:     # Display student info
 2528:     $request->print(($counter == 0 ? '' : '<br />'));
 2529: 
 2530:     my $boxtitle = &mt('Submissions');
 2531:     if ($is_tool) {
 2532:         $boxtitle = &mt('Transactions')
 2533:     }
 2534:     my $result='<div class="LC_Box">'
 2535:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2536:     $result.='<input type="hidden" name="name'.$counter.
 2537:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2538:     if (($numresp > $numessay) && !$is_tool) {
 2539:         $result.='<p class="LC_info">'
 2540:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2541:                 ."</p>\n";
 2542:     }
 2543: 
 2544:     # If any part of the problem is an essayresponse, then check for collaborators
 2545:     my $fullname;
 2546:     my $col_fullnames = [];
 2547:     if ($numessay) {
 2548: 	(my $sub_result,$fullname,$col_fullnames)=
 2549: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2550: 				 $counter);
 2551: 	$result.=$sub_result;
 2552:     }
 2553:     $request->print($result."\n");
 2554: 
 2555:     # print student answer/submission
 2556:     # Options are (1) Last submission only
 2557:     #             (2) Last submission (with detailed information for that submission)
 2558:     #             (3) All transactions (by date)
 2559:     #             (4) The whole record (with detailed information for all transactions)
 2560: 
 2561:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2562: 
 2563:     my $lastsubonly;
 2564: 
 2565:     if ($$timestamp eq '') {
 2566:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2567:     } elsif ($is_tool) {
 2568:         $lastsubonly =
 2569:             '<div class="LC_grade_submissions_body">'
 2570:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2571:     } else {
 2572:         $lastsubonly =
 2573:             '<div class="LC_grade_submissions_body">'
 2574:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2575: 
 2576: 	my %seenparts;
 2577: 	my @part_response_id = &flatten_responseType($responseType);
 2578: 	foreach my $part (@part_response_id) {
 2579: 	    my ($partid,$respid) = @{ $part };
 2580: 	    my $display_part=&get_display_part($partid,$symb);
 2581: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2582: 		if (exists($seenparts{$partid})) { next; }
 2583: 		$seenparts{$partid}=1;
 2584:                 $request->print(
 2585:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2586:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2587:                                '<a href="javascript:viewSubmitter(\''.
 2588:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2589:                                '\');" target="_self">'.
 2590:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2591:                     '<br />');
 2592: 		next;
 2593: 	    }
 2594: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2595: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2596:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2597:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2598:                     ' <span class="LC_internal_info">'.
 2599:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2600:                     '</span>&nbsp; &nbsp;'.
 2601: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2602: 		next;
 2603: 	    }
 2604: 	    foreach my $submission (@$string) {
 2605: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2606: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2607: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2608: 		# Similarity check
 2609:                 my $similar='';
 2610:                 my ($type,$trial,$rndseed);
 2611:                 if ($hide eq 'rand') {
 2612:                     $type = 'randomizetry';
 2613:                     $trial = $record{"resource.$partid.tries"};
 2614:                     $rndseed = $record{"resource.$partid.rndseed"};
 2615:                 }
 2616: 	        if ($env{'form.checkPlag'}) {
 2617: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2618: 		    &most_similar($uname,$udom,$symb,$subval);
 2619: 		    if ($osim) {
 2620: 			$osim=int($osim*100.0);
 2621:                         if ($hide eq 'anon') {
 2622:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2623:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2624:                         } else {
 2625: 			    $similar='<hr />';
 2626:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2627:                                 $similar .= '<h3><span class="LC_warning">'.
 2628:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2629:                                                 $osim,
 2630:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2631:                                             '</span></h3>';
 2632:                             } else {
 2633:                                 my %old_course_desc;
 2634:                                 if ($ocrsid ne '') {
 2635:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2636:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2637:                                     } else {
 2638:                                         my $args;
 2639:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2640:                                             $args = {'one_time' => 1};
 2641:                                         }
 2642:                                         %old_course_desc =
 2643:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2644:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2645:                                     }
 2646:                                     $similar .=
 2647:                                         '<h3><span class="LC_warning">'.
 2648:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2649:                                             $osim,
 2650:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2651:                                             $old_course_desc{'description'},
 2652:                                             $old_course_desc{'num'},
 2653:                                             $old_course_desc{'domain'}).
 2654:                                         '</span></h3>';
 2655:                                 } else {
 2656:                                     $similar .=
 2657:                                         '<h3><span class="LC_warning">'.
 2658:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2659:                                             $osim,
 2660:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2661:                                         '</span></h3>';
 2662:                                 }
 2663:                             }
 2664:                             $similar .= '<blockquote><i>'.
 2665:                                         &keywords_highlight($oessay).
 2666:                                         '</i></blockquote><hr />';
 2667:                         }
 2668: 	            }
 2669: 		}
 2670: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2671:                                      undef,$type,$trial,$rndseed);
 2672:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2673:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2674:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2675: 		    my $display_part=&get_display_part($partid,$symb);
 2676:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2677:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2678:                         ' <span class="LC_internal_info">'.
 2679:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2680:                         '</span>&nbsp; &nbsp;';
 2681: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2682: 		    if (@$files) {
 2683:                         if ($hide eq 'anon') {
 2684:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2685:                         } else {
 2686:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2687:                                         .'<br /><span class="LC_warning">';
 2688:                             if(@$files == 1) {
 2689:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2690:                             } else {
 2691:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2692:                             }
 2693:                             $lastsubonly .= '</span>';
 2694:                             foreach my $file (@$files) {
 2695:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2696:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2697:                             }
 2698:                         }
 2699: 			$lastsubonly.='<br />';
 2700:                     }
 2701:                     if ($hide eq 'anon') {
 2702:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2703:                     } else {
 2704:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2705:                         if ($draft) {
 2706:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2707:                         }
 2708:                         $subval =
 2709: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2710: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2711:                         if ($responsetype eq 'essay') {
 2712:                             $subval =~ s{\n}{<br />}g;
 2713:                         }
 2714:                         $lastsubonly.=$subval."\n";
 2715:                     }
 2716:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2717: 		    $lastsubonly.='</div>';
 2718: 		}
 2719:             }
 2720: 	}
 2721: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2722:     }
 2723:     $request->print($lastsubonly);
 2724:     if ($env{'form.lastSub'} eq 'datesub') {
 2725:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2726: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2727:     }
 2728:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2729:         my $identifier = (&canmodify($usec)? $counter : '');
 2730:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2731: 								 $env{'request.course.id'},
 2732: 								 $last,'.submission',
 2733: 								 'Apache::grades::keywords_highlight',
 2734:                                                                  $usec,$identifier));
 2735:     }
 2736:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2737: 	.$udom.'" />'."\n");
 2738:     # return if view submission with no grading option
 2739:     if (!&canmodify($usec)) {
 2740: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2741: 	return;
 2742:     } else {
 2743: 	$request->print('</div>'."\n");
 2744:     }
 2745: 
 2746:     # grading message center
 2747: 
 2748:     if ($env{'form.compmsg'}) {
 2749:         my $result='<div class="LC_Box">'.
 2750:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2751:                    '<div class="LC_grade_message_center_body">';
 2752:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2753:         my $msgfor = $givenn.' '.$lastname;
 2754:         if (scalar(@$col_fullnames) > 0) {
 2755:             my $lastone = pop(@$col_fullnames);
 2756:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2757:         }
 2758:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2759:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2760:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2761:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2762:                  ',\''.$msgfor.'\');" target="_self">'.
 2763:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2764:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2765:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2766:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2767:                  '<br />&nbsp;('.
 2768:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2769:                  '</div></div>';
 2770:         $request->print($result);
 2771:     }
 2772: 
 2773:     my %seen = ();
 2774:     my @partlist;
 2775:     my @gradePartRespid;
 2776:     my @part_response_id;
 2777:     if ($is_tool) {
 2778:         @part_response_id = ([0,'']);
 2779:     } else {
 2780:         @part_response_id = &flatten_responseType($responseType);
 2781:     }
 2782:     $request->print(
 2783:         '<div class="LC_Box">'
 2784:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2785:     );
 2786:     $request->print(&gradeBox_start());
 2787:     foreach my $part_response_id (@part_response_id) {
 2788:     	my ($partid,$respid) = @{ $part_response_id };
 2789: 	my $part_resp = join('_',@{ $part_response_id });
 2790: 	next if ($seen{$partid} > 0);
 2791: 	$seen{$partid}++;
 2792: 	push(@partlist,$partid);
 2793: 	push(@gradePartRespid,$partid.'.'.$respid);
 2794: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2795:     }
 2796:     $request->print(&gradeBox_end()); # </div>
 2797:     $request->print('</div>');
 2798: 
 2799:     $request->print('<div class="LC_grade_info_links">');
 2800:     $request->print('</div>');
 2801: 
 2802:     $result='<input type="hidden" name="partlist'.$counter.
 2803: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2804:     $result.='<input type="hidden" name="gradePartRespid'.
 2805: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2806:     my $ctr = 0;
 2807:     while ($ctr < scalar(@partlist)) {
 2808: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2809: 	    $partlist[$ctr].'" />'."\n";
 2810: 	$ctr++;
 2811:     }
 2812:     $request->print($result.''."\n");
 2813: 
 2814: # Done with printing info for one student
 2815: 
 2816:     $request->print('</div>');#LC_grade_show_user
 2817: 
 2818: 
 2819:     # print end of form
 2820:     if ($counter == $total) {
 2821:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2822: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2823: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2824: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2825: 	my $ntstu ='<select name="NTSTU">'.
 2826: 	    '<option>1</option><option>2</option>'.
 2827: 	    '<option>3</option><option>5</option>'.
 2828: 	    '<option>7</option><option>10</option></select>'."\n";
 2829: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2830: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2831:         $endform.=&mt('[_1]student(s)',$ntstu);
 2832: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2833: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2834: 	    '<input type="button" value="'.&mt('Next').'" '.
 2835: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2836:         $endform.='<span class="LC_warning">'.
 2837:                   &mt('(Next and Previous (student) do not save the scores.)').
 2838:                   '</span>'."\n" ;
 2839:         $endform.="<input type='hidden' value='".&get_increment().
 2840:             "' name='increment' />";
 2841: 	$endform.='</td></tr></table></form>';
 2842: 	$request->print($endform);
 2843:     }
 2844:     return '';
 2845: }
 2846: 
 2847: sub check_collaborators {
 2848:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2849:     my ($result,@col_fullnames);
 2850:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2851:     foreach my $part (keys(%$handgrade)) {
 2852: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2853: 					'.maxcollaborators',
 2854: 					$symb,$udom,$uname);
 2855: 	next if ($ncol <= 0);
 2856: 	$part =~ s/\_/\./g;
 2857: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2858: 	my (@good_collaborators, @bad_collaborators);
 2859: 	foreach my $possible_collaborator
 2860: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2861: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2862: 	    next if ($possible_collaborator eq '');
 2863: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2864: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2865: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2866: 	    # Doing this grep allows 'fuzzy' specification
 2867: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2868: 			       keys(%$classlist));
 2869: 	    if (! scalar(@matches)) {
 2870: 		push(@bad_collaborators, $possible_collaborator);
 2871: 	    } else {
 2872: 		push(@good_collaborators, @matches);
 2873: 	    }
 2874: 	}
 2875: 	if (scalar(@good_collaborators) != 0) {
 2876: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2877: 	    foreach my $name (@good_collaborators) {
 2878: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2879: 		push(@col_fullnames, $givenn.' '.$lastname);
 2880: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2881: 	    }
 2882: 	    $result.='</ol><br />'."\n";
 2883: 	    my ($part)=split(/\./,$part);
 2884: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2885: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2886: 		"\n";
 2887: 	}
 2888: 	if (scalar(@bad_collaborators) > 0) {
 2889: 	    $result.='<div class="LC_warning">';
 2890: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2891: 	    $result .= '</div>';
 2892: 	}         
 2893: 	if (scalar(@bad_collaborators > $ncol)) {
 2894: 	    $result .= '<div class="LC_warning">';
 2895: 	    $result .= &mt('This student has submitted too many '.
 2896: 		'collaborators.  Maximum is [_1].',$ncol);
 2897: 	    $result .= '</div>';
 2898: 	}
 2899:     }
 2900:     return ($result,$fullname,\@col_fullnames);
 2901: }
 2902: 
 2903: #--- Retrieve the last submission for all the parts
 2904: sub get_last_submission {
 2905:     my ($returnhash,$is_tool)=@_;
 2906:     my (@string,$timestamp,%lasthidden);
 2907:     if ($$returnhash{'version'}) {
 2908: 	my %lasthash=();
 2909: 	my ($version);
 2910: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2911: 	    foreach my $key (sort(split(/\:/,
 2912: 					$$returnhash{$version.':keys'}))) {
 2913: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2914: 		$timestamp = 
 2915: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2916: 	    }
 2917: 	}
 2918:         my (%typeparts,%randombytry);
 2919:         my $showsurv = 
 2920:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2921:         foreach my $key (sort(keys(%lasthash))) {
 2922:             if ($key =~ /\.type$/) {
 2923:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2924:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2925:                     ($lasthash{$key} eq 'randomizetry')) {
 2926:                     my ($ign,@parts) = split(/\./,$key);
 2927:                     pop(@parts);
 2928:                     my $id = join('.',@parts);
 2929:                     if ($lasthash{$key} eq 'randomizetry') {
 2930:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2931:                     } else {
 2932:                         unless ($showsurv) {
 2933:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2934:                         }
 2935:                     }
 2936:                     delete($lasthash{$key});
 2937:                 }
 2938:             }
 2939:         }
 2940:         my @hidden = keys(%typeparts);
 2941:         my @randomize = keys(%randombytry);
 2942: 	foreach my $key (keys(%lasthash)) {
 2943: 	    next if ($key !~ /\.submission$/);
 2944:             my $hide;
 2945:             if (@hidden) {
 2946:                 foreach my $id (@hidden) {
 2947:                     if ($key =~ /^\Q$id\E/) {
 2948:                         $hide = 'anon';
 2949:                         last;
 2950:                     }
 2951:                 }
 2952:             }
 2953:             unless ($hide) {
 2954:                 if (@randomize) {
 2955:                     foreach my $id (@randomize) {
 2956:                         if ($key =~ /^\Q$id\E/) {
 2957:                             $hide = 'rand';
 2958:                             last;
 2959:                         }
 2960:                     }
 2961:                 }
 2962:             }
 2963: 	    my ($partid,$foo) = split(/submission$/,$key);
 2964: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2965:             push(@string, join(':', $key, $hide, $draft, (
 2966:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2967:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2968: 	}
 2969:     }
 2970:     if (!@string) {
 2971:         my $msg;
 2972:         if ($is_tool) {
 2973:             $msg = &mt('No grade passed back.');
 2974:         } else {
 2975:             $msg = &mt('Nothing submitted - no attempts.');
 2976:         }
 2977: 	$string[0] =
 2978: 	    '<span class="LC_warning">'.$msg.'</span>';
 2979:     }
 2980:     return (\@string,\$timestamp);
 2981: }
 2982: 
 2983: #--- High light keywords, with style choosen by user.
 2984: sub keywords_highlight {
 2985:     my $string    = shift;
 2986:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2987:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2988:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2989:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2990:     foreach my $keyword (@keylist) {
 2991: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2992:     }
 2993:     return $string;
 2994: }
 2995: 
 2996: # For Tasks provide a mechanism to display previous version for one specific student
 2997: 
 2998: sub show_previous_task_version {
 2999:     my ($request,$symb) = @_;
 3000:     if ($symb eq '') {
 3001:         $request->print(
 3002:             '<span class="LC_error">'.
 3003:             &mt('Unable to handle ambiguous references.').
 3004:             '</span>');
 3005:         return '';
 3006:     }
 3007:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 3008:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 3009:     if (!&canview($usec)) {
 3010:         $request->print(
 3011:             '<span class="LC_warning">'.
 3012:             &mt('Unable to view previous version for requested student.').
 3013:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 3014:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3015:             '</span>');
 3016:         return;
 3017:     }
 3018:     my $mode = 'both';
 3019:     my $isTask = ($symb =~/\.task$/);
 3020:     if ($isTask) {
 3021:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3022:             if ($env{'form.fullname'} eq '') {
 3023:                 $env{'form.fullname'} =
 3024:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3025:             }
 3026:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3027:             $request->print("\n\n".
 3028:                             '<div class="LC_grade_show_user">'.
 3029:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3030:                             '</h2>'."\n");
 3031:             &Apache::lonxml::clear_problem_counter();
 3032:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3033:                             {'previousversion' => $env{'form.previousversion'} }));
 3034:             $request->print("\n</div>");
 3035:         }
 3036:     }
 3037:     return;
 3038: }
 3039: 
 3040: sub choose_task_version_form {
 3041:     my ($symb,$uname,$udom,$nomenu) = @_;
 3042:     my $isTask = ($symb =~/\.task$/);
 3043:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3044:     if ($isTask) {
 3045:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3046:                                               $udom,$uname);
 3047:         if (($record{'resource.0.version'} eq '') ||
 3048:             ($record{'resource.0.version'} < 2)) {
 3049:             return ($record{'resource.0.version'},
 3050:                     $record{'resource.0.version'},$result,$js);
 3051:         } else {
 3052:             $current = $record{'resource.0.version'};
 3053:         }
 3054:         if ($env{'form.previousversion'}) {
 3055:             $displayed = $env{'form.previousversion'};
 3056:             $rowtitle = &mt('Choose another version:')
 3057:         } else {
 3058:             $displayed = $current;
 3059:             $rowtitle = &mt('Show earlier version:');
 3060:         }
 3061:         $result = '<div class="LC_left_float">';
 3062:         my $list;
 3063:         my $numversions = 0;
 3064:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3065:             if ($i == $current) {
 3066:                 if (!$env{'form.previousversion'} || $nomenu) {
 3067:                     next;
 3068:                 } else {
 3069:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3070:                     $numversions ++;
 3071:                 }
 3072:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3073:                 unless ($i == $env{'form.previousversion'}) {
 3074:                     $numversions ++;
 3075:                 }
 3076:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3077:             }
 3078:         }
 3079:         if ($numversions) {
 3080:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3081:             $result .=
 3082:                 '<form name="getprev" method="post" action=""'.
 3083:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3084:                 &Apache::loncommon::start_data_table().
 3085:                 &Apache::loncommon::start_data_table_row().
 3086:                 '<th align="left">'.$rowtitle.'</th>'.
 3087:                 '<td><select name="version">'.
 3088:                 '<option>'.&mt('Select').'</option>'.
 3089:                 $list.
 3090:                 '</select></td>'.
 3091:                 &Apache::loncommon::end_data_table_row();
 3092:             unless ($nomenu) {
 3093:                 $result .= &Apache::loncommon::start_data_table_row().
 3094:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3095:                 '<td><span class="LC_nobreak">'.
 3096:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3097:                 &mt('Yes').'</label>'.
 3098:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3099:                 '</span></td>'.
 3100:                 &Apache::loncommon::end_data_table_row();
 3101:             }
 3102:             $result .=
 3103:                 &Apache::loncommon::start_data_table_row().
 3104:                 '<th align="left">&nbsp;</th>'.
 3105:                 '<td>'.
 3106:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3107:                 '</td>'.
 3108:                 &Apache::loncommon::end_data_table_row().
 3109:                 &Apache::loncommon::end_data_table().
 3110:                 '</form>';
 3111:             $js = &previous_display_javascript($nomenu,$current);
 3112:         } elsif ($displayed && $nomenu) {
 3113:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3114:         } else {
 3115:             $result .= &mt('No previous versions to show for this student');
 3116:         }
 3117:         $result .= '</div>';
 3118:     }
 3119:     return ($current,$displayed,$result,$js);
 3120: }
 3121: 
 3122: sub previous_display_javascript {
 3123:     my ($nomenu,$current) = @_;
 3124:     my $js = <<"JSONE";
 3125: <script type="text/javascript">
 3126: // <![CDATA[
 3127: function previousVersion(uname,udom,symb) {
 3128:     var current = '$current';
 3129:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3130:     var prevstr = new RegExp("^\\\\d+\$");
 3131:     if (!prevstr.test(version)) {
 3132:         return false;
 3133:     }
 3134:     var url = '';
 3135:     if (version == current) {
 3136:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3137:     } else {
 3138:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3139:     }
 3140: JSONE
 3141:     if ($nomenu) {
 3142:         $js .= <<"JSTWO";
 3143:     document.location.href = url;
 3144: JSTWO
 3145:     } else {
 3146:         $js .= <<"JSTHREE";
 3147:     var newwin = 0;
 3148:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3149:         if (document.getprev.prevwin[i].checked == true) {
 3150:             newwin = document.getprev.prevwin[i].value;
 3151:         }
 3152:     }
 3153:     if (newwin == 1) {
 3154:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3155:         url = url+'&inhibitmenu=yes';
 3156:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3157:             previousWin = window.open(url,'',options,1);
 3158:         } else {
 3159:             previousWin.location.href = url;
 3160:         }
 3161:         previousWin.focus();
 3162:         return false;
 3163:     } else {
 3164:         document.location.href = url;
 3165:         return false;
 3166:     }
 3167: JSTHREE
 3168:     }
 3169:     $js .= <<"ENDJS";
 3170:     return false;
 3171: }
 3172: // ]]>
 3173: </script>
 3174: ENDJS
 3175: 
 3176: }
 3177: 
 3178: #--- Called from submission routine
 3179: sub processHandGrade {
 3180:     my ($request,$symb) = @_;
 3181:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3182:     my $button = $env{'form.gradeOpt'};
 3183:     my $ngrade = $env{'form.NCT'};
 3184:     my $ntstu  = $env{'form.NTSTU'};
 3185:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3186:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3187:     my ($res_error,%queueable);
 3188:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3189:     if ($res_error) {
 3190:         $request->print(&navmap_errormsg());
 3191:         return;
 3192:     } else {
 3193:         foreach my $part (@{$partlist}) {
 3194:             if (ref($responseType->{$part}) eq 'HASH') {
 3195:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3196:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3197:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3198:                         $queueable{$part} = 1;
 3199:                         last;
 3200:                     }
 3201:                 }
 3202:             }
 3203:         }
 3204:     }
 3205: 
 3206:     if ($button eq 'Save & Next') {
 3207: 	my $ctr = 0;
 3208: 	while ($ctr < $ngrade) {
 3209: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3210: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3211:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3212: 	    if ($errorflag eq 'no_score') {
 3213: 		$ctr++;
 3214: 		next;
 3215: 	    }
 3216: 	    if ($errorflag eq 'not_allowed') {
 3217: 		$request->print(
 3218:                     '<span class="LC_error">'
 3219:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3220:                    .'</span>');
 3221: 		$ctr++;
 3222: 		next;
 3223: 	    }
 3224:             if ($numhidden) {
 3225:                 $request->print(
 3226:                     '<span class="LC_info">'
 3227:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3228:                    .'</span><br />');
 3229:             }
 3230: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3231: 	    my ($subject,$message,$msgstatus) = ('','','');
 3232: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3233:             my ($feedurl,$showsymb) =
 3234: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3235: 	    my $messagetail;
 3236: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3237: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3238: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3239: 		$subject.=' ['.$restitle.']';
 3240: 		my (@msgnum) = split(/,/,$includemsg);
 3241: 		foreach (@msgnum) {
 3242: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3243: 		}
 3244: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3245: 		if ($env{'form.withgrades'.$ctr}) {
 3246: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3247: 		    $messagetail = " for <a href=\"".
 3248: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3249: 		}
 3250: 		$msgstatus = 
 3251:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3252: 						     $message.$messagetail,
 3253:                                                      undef,$feedurl,undef,
 3254:                                                      undef,undef,$showsymb,
 3255:                                                      $restitle);
 3256: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3257: 				$msgstatus.'<br />');
 3258: 	    }
 3259: 	    if ($env{'form.collaborator'.$ctr}) {
 3260: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3261: 		foreach my $collabstr (@collabstrs) {
 3262: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3263: 		    foreach my $collaborator (@collaborators) {
 3264: 			my ($errorflag,$pts,$wgt) = 
 3265: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3266: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3267: 			if ($errorflag eq 'not_allowed') {
 3268: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3269: 			    next;
 3270: 			} elsif ($message ne '') {
 3271: 			    my ($baseurl,$showsymb) = 
 3272: 				&get_feedurl_and_symb($symb,$collaborator,
 3273: 						      $udom);
 3274: 			    if ($env{'form.withgrades'.$ctr}) {
 3275: 				$messagetail = " for <a href=\"".
 3276:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3277: 			    }
 3278: 			    $msgstatus = 
 3279: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3280: 			}
 3281: 		    }
 3282: 		}
 3283: 	    }
 3284: 	    $ctr++;
 3285: 	}
 3286:     }
 3287: 
 3288:     my %keyhash = ();
 3289:     if ($numessay) {
 3290: 	# Keywords sorted in alphabatical order
 3291: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3292: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3293: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3294: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3295: 	$env{'form.keywords'} = join(' ',@keywords);
 3296: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3297: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3298: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3299: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3300: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3301:     }
 3302: 
 3303:     if ($env{'form.compmsg'}) {
 3304: 	# message center - Order of message gets changed. Blank line is eliminated.
 3305: 	# New messages are saved in env for the next student.
 3306: 	# All messages are saved in nohist_handgrade.db
 3307: 	my ($ctr,$idx) = (1,1);
 3308: 	while ($ctr <= $env{'form.savemsgN'}) {
 3309: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3310: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3311: 		$idx++;
 3312: 	    }
 3313: 	    $ctr++;
 3314: 	}
 3315: 	$ctr = 0;
 3316: 	while ($ctr < $ngrade) {
 3317: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3318: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3319: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3320: 	        $idx++;
 3321: 	    }
 3322: 	    $ctr++;
 3323: 	}
 3324: 	$env{'form.savemsgN'} = --$idx;
 3325: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3326:     }
 3327:     if (($numessay) || ($env{'form.compmsg'})) {
 3328:         my $putresult = &Apache::lonnet::put
 3329:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3330:     }
 3331: 
 3332:     # Called by Save & Refresh from Highlight Attribute Window
 3333:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3334:     if ($env{'form.refresh'} eq 'on') {
 3335: 	my ($ctr,$total) = (0,0);
 3336: 	while ($ctr < $ngrade) {
 3337: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3338: 	    $ctr++;
 3339: 	}
 3340: 	$env{'form.NTSTU'}=$ngrade;
 3341: 	$ctr = 0;
 3342: 	while ($ctr < $total) {
 3343: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3344: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3345: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3346: 	    &submission($request,$ctr,$total-1,$symb);
 3347: 	    $ctr++;
 3348: 	}
 3349: 	return '';
 3350:     }
 3351: 
 3352:     # Get the next/previous one or group of students
 3353:     my $firststu = $env{'form.unamedom0'};
 3354:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3355:     my $ctr = 2;
 3356:     while ($laststu eq '') {
 3357: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3358: 	$ctr++;
 3359: 	$laststu = $firststu if ($ctr > $ngrade);
 3360:     }
 3361: 
 3362:     my (@parsedlist,@nextlist);
 3363:     my ($nextflg) = 0;
 3364:     foreach my $item (sort 
 3365: 	     {
 3366: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3367: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3368: 		 }
 3369: 		 return $a cmp $b;
 3370: 	     } (keys(%$fullname))) {
 3371: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3372: 	    push(@parsedlist,$item);
 3373: 	}
 3374: 	$nextflg = 1 if ($item eq $laststu);
 3375: 	if ($button eq 'Previous') {
 3376: 	    last if ($item eq $firststu);
 3377: 	    push(@parsedlist,$item);
 3378: 	}
 3379:     }
 3380:     $ctr = 0;
 3381:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3382:     foreach my $student (@parsedlist) {
 3383: 	my $submitonly=$env{'form.submitonly'};
 3384: 	my ($uname,$udom) = split(/:/,$student);
 3385: 	
 3386: 	if ($submitonly eq 'queued') {
 3387: 	    my %queue_status = 
 3388: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3389: 							$udom,$uname);
 3390: 	    next if (!defined($queue_status{'gradingqueue'}));
 3391: 	}
 3392: 
 3393: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3394: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3395: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3396: 	    my $submitted = 0;
 3397: 	    my $ungraded = 0;
 3398: 	    my $incorrect = 0;
 3399: 	    foreach my $item (keys(%status)) {
 3400: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3401: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3402: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3403: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3404: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3405: 		    $submitted = 0;
 3406: 		}
 3407: 	    }
 3408: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3409: 				     $submitonly eq 'incorrect' ||
 3410: 				     $submitonly eq 'graded'));
 3411: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3412: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3413: 	}
 3414: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3415: 	last if ($ctr == $ntstu);
 3416: 	$ctr++;
 3417:     }
 3418: 
 3419:     $ctr = 0;
 3420:     my $total = scalar(@nextlist)-1;
 3421: 
 3422:     foreach (sort(@nextlist)) {
 3423: 	my ($uname,$udom,$submitter) = split(/:/);
 3424: 	$env{'form.student'}  = $uname;
 3425: 	$env{'form.userdom'}  = $udom;
 3426: 	$env{'form.fullname'} = $$fullname{$_};
 3427: 	&submission($request,$ctr,$total,$symb);
 3428: 	$ctr++;
 3429:     }
 3430:     if ($total < 0) {
 3431: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3432: 	$request->print($the_end);
 3433:     }
 3434:     return '';
 3435: }
 3436: 
 3437: #---- Save the score and award for each student, if changed
 3438: sub saveHandGrade {
 3439:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3440:     my @version_parts;
 3441:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3442: 					   $env{'request.course.id'});
 3443:     if (!&canmodify($usec)) { return('not_allowed'); }
 3444:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3445:     my @parts_graded;
 3446:     my %newrecord  = ();
 3447:     my ($pts,$wgt,$totchg) = ('','',0);
 3448:     my %aggregate = ();
 3449:     my $aggregateflag = 0;
 3450:     if ($env{'form.HIDE'.$newflg}) {
 3451:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3452:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3453:         $totchg += $numchgs;
 3454:     }
 3455:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3456:     foreach my $new_part (@parts) {
 3457: 	#collaborator ($submi may vary for different parts
 3458: 	if ($submitter && $new_part ne $part) { next; }
 3459: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3460: 	if ($dropMenu eq 'excused') {
 3461: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3462: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3463: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3464: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3465: 		}
 3466: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3467: 	    }
 3468: 	} elsif ($dropMenu eq 'reset status'
 3469: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3470: 	    foreach my $key (keys(%record)) {
 3471: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3472: 	    }
 3473: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3474: 		"$env{'user.name'}:$env{'user.domain'}";
 3475:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3476: 
 3477:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3478: 					       [$new_part]);
 3479:             my $aggtries =$totaltries;
 3480:             if ($last_resets{$new_part}) {
 3481:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3482: 					   $new_part);
 3483:             }
 3484: 
 3485:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3486:             if ($aggtries > 0) {
 3487:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3488:                 $aggregateflag = 1;
 3489:             }
 3490: 	} elsif ($dropMenu eq '') {
 3491: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3492: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3493: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3494: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3495: 		next;
 3496: 	    }
 3497: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3498: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3499: 	    my $partial= $pts/$wgt;
 3500: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3501: 		#do not update score for part if not changed.
 3502:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3503: 		next;
 3504: 	    } else {
 3505: 	        push(@parts_graded,$new_part);
 3506: 	    }
 3507: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3508: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3509: 	    }
 3510: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3511: 	    if ($partial == 0) {
 3512: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3513: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3514: 		}
 3515: 	    } else {
 3516: 		if ($record{$reckey} ne 'correct_by_override') {
 3517: 		    $newrecord{$reckey} = 'correct_by_override';
 3518: 		}
 3519: 	    }	    
 3520: 	    if ($submitter && 
 3521: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3522: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3523: 	    }
 3524: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3525: 		"$env{'user.name'}:$env{'user.domain'}";
 3526: 	}
 3527: 	# unless problem has been graded, set flag to version the submitted files
 3528: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3529: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3530: 	        $dropMenu eq 'reset status')
 3531: 	   {
 3532: 	    push(@version_parts,$new_part);
 3533: 	}
 3534:     }
 3535:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3536:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3537: 
 3538:     if (%newrecord) {
 3539:         if (@version_parts) {
 3540:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3541:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3542: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3543: 	    foreach my $new_part (@version_parts) {
 3544: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3545: 				$new_part,\%newrecord);
 3546: 	    }
 3547:         }
 3548: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3549: 				$env{'request.course.id'},$domain,$stuname);
 3550: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3551: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3552:     }
 3553:     if ($aggregateflag) {
 3554:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3555: 			      $cdom,$cnum);
 3556:     }
 3557:     return ('',$pts,$wgt,$totchg);
 3558: }
 3559: 
 3560: sub makehidden {
 3561:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3562:     return unless (ref($record) eq 'HASH');
 3563:     my %modified;
 3564:     my $numchanged = 0;
 3565:     if (exists($record->{$version.':keys'})) {
 3566:         my $partsregexp = $parts;
 3567:         $partsregexp =~ s/,/|/g;
 3568:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3569:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3570:                  my $item = $1;
 3571:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3572:                      $modified{$key} = $record->{$version.':'.$key};
 3573:                  }
 3574:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3575:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3576:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3577:                 $modified{$key} = $record->{$version.':'.$key};
 3578:             }
 3579:         }
 3580:         if (keys(%modified)) {
 3581:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3582:                                           $domain,$stuname,$tolog) eq 'ok') {
 3583:                 $numchanged ++;
 3584:             }
 3585:         }
 3586:     }
 3587:     return $numchanged;
 3588: }
 3589: 
 3590: sub check_and_remove_from_queue {
 3591:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3592:     my @ungraded_parts;
 3593:     foreach my $part (@{$parts}) {
 3594: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3595: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3596: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3597: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3598: 		) {
 3599:             if ($queueable->{$part}) {
 3600: 	        push(@ungraded_parts, $part);
 3601:             }
 3602: 	}
 3603:     }
 3604:     if ( !@ungraded_parts ) {
 3605: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3606: 					       $cnum,$domain,$stuname);
 3607:     }
 3608: }
 3609: 
 3610: sub handback_files {
 3611:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3612:     my $portfolio_root = '/userfiles/portfolio';
 3613:     my $res_error;
 3614:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3615:     if ($res_error) {
 3616:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3617:         return;
 3618:     }
 3619:     my @handedback;
 3620:     my $file_msg;
 3621:     my @part_response_id = &flatten_responseType($responseType);
 3622:     foreach my $part_response_id (@part_response_id) {
 3623:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3624: 	my $part_resp = join('_',@{ $part_response_id });
 3625:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3626:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3627:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3628:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3629:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3630:                     my ($directory,$answer_file) = 
 3631:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3632:                     my ($answer_name,$answer_ver,$answer_ext) =
 3633: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3634: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3635:                     my $getpropath = 1;
 3636:                     my ($dir_list,$listerror) =
 3637:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3638:                                                  $domain,$stuname,$getpropath);
 3639: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3640:                     # fix filename
 3641:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3642:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3643:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3644:             	                                $save_file_name);
 3645:                     if ($result !~ m|^/uploaded/|) {
 3646:                         $request->print('<br /><span class="LC_error">'.
 3647:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3648:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3649:                                         '</span>');
 3650:                     } else {
 3651:                         # mark the file as read only
 3652:                         push(@handedback,$save_file_name);
 3653: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3654: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3655: 			}
 3656:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3657: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3658:                     }
 3659:                     $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>'));
 3660:                 }
 3661:             }
 3662:         }
 3663:     }
 3664:     if (@handedback > 0) {
 3665:         $request->print('<br />');
 3666:         my @what = ($symb,$env{'request.course.id'},'handback');
 3667:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3668:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3669:         my ($subject,$message);
 3670:         if (scalar(@handedback) == 1) {
 3671:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3672:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3673:         } else {
 3674:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3675:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3676:         }
 3677:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3678:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3679:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3680:         my ($feedurl,$showsymb) =
 3681:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3682:         my $restitle = &Apache::lonnet::gettitle($symb);
 3683:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3684:         my $msgstatus =
 3685:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3686:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3687:                  $restitle);
 3688:         if ($msgstatus) {
 3689:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3690:         }
 3691:     }
 3692:     return;
 3693: }
 3694: 
 3695: sub get_feedurl_and_symb {
 3696:     my ($symb,$uname,$udom) = @_;
 3697:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3698:     $url = &Apache::lonnet::clutter($url);
 3699:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3700: 					$symb,$udom,$uname);
 3701:     if ($encrypturl =~ /^yes$/i) {
 3702: 	&Apache::lonenc::encrypted(\$url,1);
 3703: 	&Apache::lonenc::encrypted(\$symb,1);
 3704:     }
 3705:     return ($url,$symb);
 3706: }
 3707: 
 3708: sub get_submitted_files {
 3709:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3710:     my @files;
 3711:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3712:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3713:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3714:     	    push(@files,$file_url.$file);
 3715:         }
 3716:     }
 3717:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3718:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3719:     }
 3720:     return (\@files);
 3721: }
 3722: 
 3723: # ----------- Provides number of tries since last reset.
 3724: sub get_num_tries {
 3725:     my ($record,$last_reset,$part) = @_;
 3726:     my $timestamp = '';
 3727:     my $num_tries = 0;
 3728:     if ($$record{'version'}) {
 3729:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3730:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3731:                 $timestamp = $$record{$version.':timestamp'};
 3732:                 if ($timestamp > $last_reset) {
 3733:                     $num_tries ++;
 3734:                 } else {
 3735:                     last;
 3736:                 }
 3737:             }
 3738:         }
 3739:     }
 3740:     return $num_tries;
 3741: }
 3742: 
 3743: # ----------- Determine decrements required in aggregate totals 
 3744: sub decrement_aggs {
 3745:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3746:     my %decrement = (
 3747:                         attempts => 0,
 3748:                         users => 0,
 3749:                         correct => 0
 3750:                     );
 3751:     $decrement{'attempts'} = $aggtries;
 3752:     if ($solvedstatus =~ /^correct/) {
 3753:         $decrement{'correct'} = 1;
 3754:     }
 3755:     if ($aggtries == $totaltries) {
 3756:         $decrement{'users'} = 1;
 3757:     }
 3758:     foreach my $type (keys(%decrement)) {
 3759:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3760:     }
 3761:     return;
 3762: }
 3763: 
 3764: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3765: sub get_last_resets {
 3766:     my ($symb,$courseid,$partids) =@_;
 3767:     my %last_resets;
 3768:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3769:     my $cname = $env{'course.'.$courseid.'.num'};
 3770:     my @keys;
 3771:     foreach my $part (@{$partids}) {
 3772: 	push(@keys,"$symb\0$part\0resettime");
 3773:     }
 3774:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3775: 				     $cdom,$cname);
 3776:     foreach my $part (@{$partids}) {
 3777: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3778:     }
 3779:     return %last_resets;
 3780: }
 3781: 
 3782: # ----------- Handles creating versions for portfolio files as answers
 3783: sub version_portfiles {
 3784:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3785:     my $version_parts = join('|',@$v_flag);
 3786:     my @returned_keys;
 3787:     my $parts = join('|', @$parts_graded);
 3788:     foreach my $key (keys(%$record)) {
 3789:         my $new_portfiles;
 3790:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3791:             my @versioned_portfiles;
 3792:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3793:             if (@portfiles) {
 3794:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3795:                                                       \@versioned_portfiles);
 3796:             }
 3797:             $$record{$key} = join(',',@versioned_portfiles);
 3798:             push(@returned_keys,$key);
 3799:         }
 3800:     } 
 3801:     return (@returned_keys);   
 3802: }
 3803: 
 3804: #--------------------------------------------------------------------------------------
 3805: #
 3806: #-------------------------- Next few routines handles grading by section or whole class
 3807: #
 3808: #--- Javascript to handle grading by section or whole class
 3809: sub viewgrades_js {
 3810:     my ($request) = shift;
 3811: 
 3812:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3813:     &js_escape(\$alertmsg);
 3814:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3815:    function writePoint(partid,weight,point) {
 3816: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3817: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3818: 	if (point == "textval") {
 3819: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3820: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3821: 		alert("$alertmsg"+parseFloat(point));
 3822: 		var resetbox = false;
 3823: 		for (var i=0; i<radioButton.length; i++) {
 3824: 		    if (radioButton[i].checked) {
 3825: 			textbox.value = i;
 3826: 			resetbox = true;
 3827: 		    }
 3828: 		}
 3829: 		if (!resetbox) {
 3830: 		    textbox.value = "";
 3831: 		}
 3832: 		return;
 3833: 	    }
 3834: 	    if (parseFloat(point) > parseFloat(weight)) {
 3835: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3836: 				   ") greater than the weight for the part. Accept?");
 3837: 		if (resp == false) {
 3838: 		    textbox.value = "";
 3839: 		    return;
 3840: 		}
 3841: 	    }
 3842: 	    for (var i=0; i<radioButton.length; i++) {
 3843: 		radioButton[i].checked=false;
 3844: 		if (parseFloat(point) == i) {
 3845: 		    radioButton[i].checked=true;
 3846: 		}
 3847: 	    }
 3848: 
 3849: 	} else {
 3850: 	    textbox.value = parseFloat(point);
 3851: 	}
 3852: 	for (i=0;i<document.classgrade.total.value;i++) {
 3853: 	    var user = document.classgrade["ctr"+i].value;
 3854: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3855: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3856: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3857: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3858: 	    if (saveval != "correct") {
 3859: 		scorename.value = point;
 3860: 		if (selname[0].selected != true) {
 3861: 		    selname[0].selected = true;
 3862: 		}
 3863: 	    }
 3864: 	}
 3865: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3866:     }
 3867: 
 3868:     function writeRadText(partid,weight) {
 3869: 	var selval   = document.classgrade["SELVAL_"+partid];
 3870: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3871:         var override = document.classgrade["FORCE_"+partid].checked;
 3872: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3873: 	if (selval[1].selected || selval[2].selected) {
 3874: 	    for (var i=0; i<radioButton.length; i++) {
 3875: 		radioButton[i].checked=false;
 3876: 
 3877: 	    }
 3878: 	    textbox.value = "";
 3879: 
 3880: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3881: 		var user = document.classgrade["ctr"+i].value;
 3882: 		user = user.replace(new RegExp(':', 'g'),"_");
 3883: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3884: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3885: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3886: 		if ((saveval != "correct") || override) {
 3887: 		    scorename.value = "";
 3888: 		    if (selval[1].selected) {
 3889: 			selname[1].selected = true;
 3890: 		    } else {
 3891: 			selname[2].selected = true;
 3892: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3893: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3894: 		    }
 3895: 		}
 3896: 	    }
 3897: 	} else {
 3898: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3899: 		var user = document.classgrade["ctr"+i].value;
 3900: 		user = user.replace(new RegExp(':', 'g'),"_");
 3901: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3902: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3903: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3904: 		if ((saveval != "correct") || override) {
 3905: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3906: 		    selname[0].selected = true;
 3907: 		}
 3908: 	    }
 3909: 	}	    
 3910:     }
 3911: 
 3912:     function changeSelect(partid,user) {
 3913: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3914: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3915: 	var point  = textbox.value;
 3916: 	var weight = document.classgrade["weight_"+partid].value;
 3917: 
 3918: 	if (isNaN(point) || parseFloat(point) < 0) {
 3919: 	    alert("$alertmsg"+parseFloat(point));
 3920: 	    textbox.value = "";
 3921: 	    return;
 3922: 	}
 3923: 	if (parseFloat(point) > parseFloat(weight)) {
 3924: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3925: 			       ") greater than the weight of the part. Accept?");
 3926: 	    if (resp == false) {
 3927: 		textbox.value = "";
 3928: 		return;
 3929: 	    }
 3930: 	}
 3931: 	selval[0].selected = true;
 3932:     }
 3933: 
 3934:     function changeOneScore(partid,user) {
 3935: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3936: 	if (selval[1].selected || selval[2].selected) {
 3937: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3938: 	    if (selval[2].selected) {
 3939: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3940: 	    }
 3941:         }
 3942:     }
 3943: 
 3944:     function resetEntry(numpart) {
 3945: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3946: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3947: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3948: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3949: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3950: 	    for (var i=0; i<radioButton.length; i++) {
 3951: 		radioButton[i].checked=false;
 3952: 
 3953: 	    }
 3954: 	    textbox.value = "";
 3955: 	    selval[0].selected = true;
 3956: 
 3957: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3958: 		var user = document.classgrade["ctr"+i].value;
 3959: 		user = user.replace(new RegExp(':', 'g'),"_");
 3960: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3961: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3962: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3963: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3964: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3965: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3966: 		if (saveselval == "excused") {
 3967: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3968: 		} else {
 3969: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3970: 		}
 3971: 	    }
 3972: 	}
 3973:     }
 3974: 
 3975: VIEWJAVASCRIPT
 3976: }
 3977: 
 3978: #--- show scores for a section or whole class w/ option to change/update a score
 3979: sub viewgrades {
 3980:     my ($request,$symb) = @_;
 3981:     my ($is_tool,$toolsymb);
 3982:     if ($symb =~ /ext\.tool$/) {
 3983:         $is_tool = 1;
 3984:         $toolsymb = $symb;
 3985:     }
 3986:     &viewgrades_js($request);
 3987: 
 3988:     #need to make sure we have the correct data for later EXT calls, 
 3989:     #thus invalidate the cache
 3990:     &Apache::lonnet::devalidatecourseresdata(
 3991:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3992:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3993:     &Apache::lonnet::clear_EXT_cache_status();
 3994: 
 3995:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3996: 
 3997:     #view individual student submission form - called using Javascript viewOneStudent
 3998:     $result.=&jscriptNform($symb);
 3999: 
 4000:     #beginning of class grading form
 4001:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4002:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4003: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4004: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4005: 	&build_section_inputs().
 4006: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4007: 
 4008:     #retrieve selected groups
 4009:     my (@groups,$group_display);
 4010:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4011:     if (grep(/^all$/,@groups)) {
 4012:         @groups = ('all');
 4013:     } elsif (grep(/^none$/,@groups)) {
 4014:         @groups = ('none');
 4015:     } elsif (@groups > 0) {
 4016:         $group_display = join(', ',@groups);
 4017:     }
 4018: 
 4019:     my ($common_header,$specific_header,@sections,$section_display);
 4020:     if ($env{'request.course.sec'} ne '') {
 4021:         @sections = ($env{'request.course.sec'});
 4022:     } else {
 4023:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4024:     }
 4025: 
 4026: # Check if Save button should be usable
 4027:     my $disabled = ' disabled="disabled"';
 4028:     if ($perm{'mgr'}) {
 4029:         if (grep(/^all$/,@sections)) {
 4030:             undef($disabled);
 4031:         } else {
 4032:             foreach my $sec (@sections) {
 4033:                 if (&canmodify($sec)) {
 4034:                     undef($disabled);
 4035:                     last;
 4036:                 }
 4037:             }
 4038:         }
 4039:     }
 4040:     if (grep(/^all$/,@sections)) {
 4041:         @sections = ('all');
 4042:         if ($group_display) {
 4043:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4044:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4045:         } elsif (grep(/^none$/,@groups)) {
 4046:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4047:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4048:         } else {
 4049: 	    $common_header = &mt('Assign Common Grade to Class');
 4050:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4051:         }
 4052:     } elsif (grep(/^none$/,@sections)) {
 4053:         @sections = ('none');
 4054:         if ($group_display) {
 4055:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4056:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4057:         } elsif (grep(/^none$/,@groups)) {
 4058:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4059:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4060:         } else {
 4061:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4062: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4063:         }
 4064:     } else {
 4065:         $section_display = join (", ",@sections);
 4066:         if ($group_display) {
 4067:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4068:                                  $section_display,$group_display);
 4069:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4070:                                    $section_display,$group_display);
 4071:         } elsif (grep(/^none$/,@groups)) {
 4072:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4073:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4074:         } else {
 4075:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4076: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4077:         }
 4078:     }
 4079:     my %submit_types = &substatus_options();
 4080:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4081: 
 4082:     if ($env{'form.submitonly'} eq 'all') {
 4083:         $result.= '<h3>'.$common_header.'</h3>';
 4084:     } else {
 4085:         my $text;
 4086:         if ($is_tool) {
 4087:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4088:         } else {
 4089:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4090:         }
 4091:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4092:     }
 4093:     $result .= &Apache::loncommon::start_data_table();
 4094:     #radio buttons/text box for assigning points for a section or class.
 4095:     #handles different parts of a problem
 4096:     my $res_error;
 4097:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4098:     if ($res_error) {
 4099:         return &navmap_errormsg();
 4100:     }
 4101:     my %weight = ();
 4102:     my $ctsparts = 0;
 4103:     my %seen = ();
 4104:     my @part_response_id;
 4105:     if ($is_tool) {
 4106:         @part_response_id = ([0,'']);
 4107:     } else {
 4108:         @part_response_id = &flatten_responseType($responseType);
 4109:     }
 4110:     foreach my $part_response_id (@part_response_id) {
 4111:     	my ($partid,$respid) = @{ $part_response_id };
 4112: 	my $part_resp = join('_',@{ $part_response_id });
 4113: 	next if $seen{$partid};
 4114: 	$seen{$partid}++;
 4115: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4116: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4117: 
 4118: 	my $display_part=&get_display_part($partid,$symb);
 4119: 	my $radio.='<table border="0"><tr>';  
 4120: 	my $ctr = 0;
 4121: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4122: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4123: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4124: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4125: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4126: 	    $ctr++;
 4127: 	}
 4128: 	$radio.='</tr></table>';
 4129: 	my $line = '<input type="text" name="TEXTVAL_'.
 4130: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4131: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4132: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4133:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4134:             '<select name="SELVAL_'.$partid.'" '.
 4135:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4136:                 $weight{$partid}.')"> '.
 4137: 	    '<option selected="selected"> </option>'.
 4138: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4139: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4140: 	    '</select></td>'.
 4141:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4142: 	$line.='<input type="hidden" name="partid_'.
 4143: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4144: 	$line.='<input type="hidden" name="weight_'.
 4145: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4146: 
 4147: 	$result.=
 4148: 	    &Apache::loncommon::start_data_table_row()."\n".
 4149: 	    '<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>'.
 4150: 	    &Apache::loncommon::end_data_table_row()."\n";
 4151: 	$ctsparts++;
 4152:     }
 4153:     $result.=&Apache::loncommon::end_data_table()."\n".
 4154: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4155:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4156: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4157: 
 4158:     #table listing all the students in a section/class
 4159:     #header of table
 4160:     if ($env{'form.submitonly'} eq 'all') {
 4161:         $result.= '<h3>'.$specific_header.'</h3>';
 4162:     } else {
 4163:         my $text;
 4164:         if ($is_tool) {
 4165:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4166:         } else {
 4167:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4168:         }
 4169:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4170:     }
 4171:     $result.= &Apache::loncommon::start_data_table().
 4172: 	      &Apache::loncommon::start_data_table_header_row().
 4173: 	      '<th>'.&mt('No.').'</th>'.
 4174: 	      '<th>'.&nameUserString('header')."</th>\n";
 4175:     my $partserror;
 4176:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4177:     if ($partserror) {
 4178:         return &navmap_errormsg();
 4179:     }
 4180:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4181:     my @partids = ();
 4182:     foreach my $part (@parts) {
 4183: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4184:         my $narrowtext = &mt('Tries');
 4185: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4186: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4187: 	my ($partid) = &split_part_type($part);
 4188:         push(@partids,$partid);
 4189: #
 4190: # FIXME: Looks like $display looks at English text
 4191: #
 4192: 	my $display_part=&get_display_part($partid,$symb);
 4193: 	if ($display =~ /^Partial Credit Factor/) {
 4194: 	    $result.='<th>'.
 4195: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4196: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4197: 	    next;
 4198: 	    
 4199: 	} else {
 4200: 	    if ($display =~ /Problem Status/) {
 4201: 		my $grade_status_mt = &mt('Grade Status');
 4202: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4203: 	    }
 4204: 	    my $part_mt = &mt('Part:');
 4205: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4206: 	}
 4207: 
 4208: 	$result.='<th>'.$display.'</th>'."\n";
 4209:     }
 4210:     $result.=&Apache::loncommon::end_data_table_header_row();
 4211: 
 4212:     my %last_resets = 
 4213: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4214: 
 4215:     #get info for each student
 4216:     #list all the students - with points and grade status
 4217:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4218:     my $ctr = 0;
 4219:     foreach (sort 
 4220: 	     {
 4221: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4222: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4223: 		 }
 4224: 		 return $a cmp $b;
 4225: 	     } (keys(%$fullname))) {
 4226: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4227: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4228:     }
 4229:     $result.=&Apache::loncommon::end_data_table();
 4230:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4231:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4232: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4233:     if ($ctr == 0) {
 4234:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4235:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4236:                 '<span class="LC_warning">';
 4237:         if ($env{'form.submitonly'} eq 'all') {
 4238:             if (grep(/^all$/,@sections)) {
 4239:                 if (grep(/^all$/,@groups)) {
 4240:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4241:                                    $stu_status);
 4242:                 } elsif (grep(/^none$/,@groups)) {
 4243:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4244:                                    $stu_status); 
 4245:                 } else {
 4246:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4247:                                    $group_display,$stu_status);
 4248:                 }
 4249:             } elsif (grep(/^none$/,@sections)) {
 4250:                 if (grep(/^all$/,@groups)) {
 4251:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4252:                                    $stu_status);
 4253:                 } elsif (grep(/^none$/,@groups)) {
 4254:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4255:                                    $stu_status);
 4256:                 } else {
 4257:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4258:                                    $group_display,$stu_status);
 4259:                 }
 4260:             } else {
 4261:                 if (grep(/^all$/,@groups)) {
 4262:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4263:                                    $section_display,$stu_status);
 4264:                 } elsif (grep(/^none$/,@groups)) {
 4265:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4266:                                    $section_display,$stu_status);
 4267:                 } else {
 4268:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4269:                                    $section_display,$group_display,$stu_status);
 4270:                 }
 4271:             }
 4272:         } else {
 4273:             if (grep(/^all$/,@sections)) {
 4274:                 if (grep(/^all$/,@groups)) {
 4275:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4276:                                    $stu_status,$submission_status);
 4277:                 } elsif (grep(/^none$/,@groups)) {
 4278:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4279:                                    $stu_status,$submission_status);
 4280:                 } else {
 4281:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4282:                                    $group_display,$stu_status,$submission_status);
 4283:                 }
 4284:             } elsif (grep(/^none$/,@sections)) {
 4285:                 if (grep(/^all$/,@groups)) {
 4286:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4287:                                    $stu_status,$submission_status);
 4288:                 } elsif (grep(/^none$/,@groups)) {
 4289:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4290:                                    $stu_status,$submission_status);
 4291:                 } else {
 4292:                     $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.',
 4293:                                    $group_display,$stu_status,$submission_status);
 4294:                 }
 4295:             } else {
 4296:                 if (grep(/^all$/,@groups)) {
 4297: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4298: 	                           $section_display,$stu_status,$submission_status);
 4299:                 } elsif (grep(/^none$/,@groups)) {
 4300:                     $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.',
 4301:                                    $section_display,$stu_status,$submission_status);
 4302:                 } else {
 4303:                     $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.',
 4304:                                    $section_display,$group_display,$stu_status,$submission_status);
 4305:                 }
 4306:             }
 4307:         }
 4308: 	$result .= '</span><br />';
 4309:     }
 4310:     return $result;
 4311: }
 4312: 
 4313: #--- call by previous routine to display each student who satisfies submission filter. 
 4314: sub viewstudentgrade {
 4315:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4316:     my ($uname,$udom) = split(/:/,$student);
 4317:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4318:     my $submitonly = $env{'form.submitonly'};
 4319:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4320:         my %partstatus = ();
 4321:         if (ref($parts) eq 'ARRAY') {
 4322:             foreach my $apart (@{$parts}) {
 4323:                 my ($part,$type) = &split_part_type($apart);
 4324:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4325:                 $status = 'nothing' if ($status eq '');
 4326:                 $partstatus{$part}      = $status;
 4327:                 my $subkey = "resource.$part.submitted_by";
 4328:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4329:             }
 4330:             my $submitted = 0;
 4331:             my $graded = 0;
 4332:             my $incorrect = 0;
 4333:             foreach my $key (keys(%partstatus)) {
 4334:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4335:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4336:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4337: 
 4338:                 my $partid = (split(/\./,$key))[1];
 4339:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4340:                     $submitted = 0;
 4341:                 }
 4342:             }
 4343:             return if (!$submitted && ($submitonly eq 'yes' ||
 4344:                                        $submitonly eq 'incorrect' ||
 4345:                                        $submitonly eq 'graded'));
 4346:             return if (!$graded && ($submitonly eq 'graded'));
 4347:             return if (!$incorrect && $submitonly eq 'incorrect');
 4348:         }
 4349:     }
 4350:     if ($submitonly eq 'queued') {
 4351:         my ($cdom,$cnum) = split(/_/,$courseid);
 4352:         my %queue_status =
 4353:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4354:                                                     $udom,$uname);
 4355:         return if (!defined($queue_status{'gradingqueue'}));
 4356:     }
 4357:     $$ctr++;
 4358:     my %aggregates = ();
 4359:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4360: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4361: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4362: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4363: 	'\');" target="_self">'.$fullname.'</a> '.
 4364: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4365:     $student=~s/:/_/; # colon doen't work in javascript for names
 4366:     foreach my $apart (@$parts) {
 4367: 	my ($part,$type) = &split_part_type($apart);
 4368: 	my $score=$record{"resource.$part.$type"};
 4369:         $result.='<td align="center">';
 4370:         my ($aggtries,$totaltries);
 4371:         unless (exists($aggregates{$part})) {
 4372: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4373: 	    $aggtries = $totaltries;
 4374:             if ($$last_resets{$part}) {  
 4375:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4376: 					   $part);
 4377:             }
 4378:             $result.='<input type="hidden" name="'.
 4379:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4380:             $result.='<input type="hidden" name="'.
 4381:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4382:             $aggregates{$part} = 1;
 4383:         }
 4384: 	if ($type eq 'awarded') {
 4385: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4386: 	    $result.='<input type="hidden" name="'.
 4387: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4388: 	    $result.='<input type="text" name="'.
 4389: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4390:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4391: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4392: 	} elsif ($type eq 'solved') {
 4393: 	    my ($status,$foo)=split(/_/,$score,2);
 4394: 	    $status = 'nothing' if ($status eq '');
 4395: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4396: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4397: 	    $result.='&nbsp;<select name="'.
 4398: 		'GD_'.$student.'_'.$part.'_solved" '.
 4399:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4400: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4401: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4402: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4403: 	    $result.="</select>&nbsp;</td>\n";
 4404: 	} else {
 4405: 	    $result.='<input type="hidden" name="'.
 4406: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4407: 		    "\n";
 4408: 	    $result.='<input type="text" name="'.
 4409: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4410: 		'value="'.$score.'" size="4" /></td>'."\n";
 4411: 	}
 4412:     }
 4413:     $result.=&Apache::loncommon::end_data_table_row();
 4414:     return $result;
 4415: }
 4416: 
 4417: #--- change scores for all the students in a section/class
 4418: #    record does not get update if unchanged
 4419: sub editgrades {
 4420:     my ($request,$symb) = @_;
 4421:     my $toolsymb;
 4422:     if ($symb =~ /ext\.tool$/) {
 4423:         $toolsymb = $symb;
 4424:     }
 4425: 
 4426:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4427:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4428:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4429: 
 4430:     my $result= &Apache::loncommon::start_data_table().
 4431: 	&Apache::loncommon::start_data_table_header_row().
 4432: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4433: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4434:     my %scoreptr = (
 4435: 		    'correct'  =>'correct_by_override',
 4436: 		    'incorrect'=>'incorrect_by_override',
 4437: 		    'excused'  =>'excused',
 4438: 		    'ungraded' =>'ungraded_attempted',
 4439:                     'credited' =>'credit_attempted',
 4440: 		    'nothing'  => '',
 4441: 		    );
 4442:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4443: 
 4444:     my (@partid);
 4445:     my %weight = ();
 4446:     my %columns = ();
 4447:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4448: 
 4449:     my $partserror;
 4450:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4451:     if ($partserror) {
 4452:         return &navmap_errormsg();
 4453:     }
 4454:     my $header;
 4455:     while ($ctr < $env{'form.totalparts'}) {
 4456: 	my $partid = $env{'form.partid_'.$ctr};
 4457: 	push(@partid,$partid);
 4458: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4459: 	$ctr++;
 4460:     }
 4461:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4462:     my $totcolspan = 0;
 4463:     foreach my $partid (@partid) {
 4464: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4465: 	    '<th align="center">'.&mt('New Score').'</th>';
 4466: 	$columns{$partid}=2;
 4467: 	foreach my $stores (@parts) {
 4468: 	    my ($part,$type) = &split_part_type($stores);
 4469: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4470: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4471: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4472: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4473:             my $narrowtext = &mt('Tries');
 4474: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4475: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4476: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4477: 	    $columns{$partid}+=2;
 4478: 	}
 4479:         $totcolspan += $columns{$partid};
 4480:     }
 4481:     foreach my $partid (@partid) {
 4482: 	my $display_part=&get_display_part($partid,$symb);
 4483: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4484: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4485: 	    '</th>';
 4486: 
 4487:     }
 4488:     $result .= &Apache::loncommon::end_data_table_header_row().
 4489: 	&Apache::loncommon::start_data_table_header_row().
 4490: 	$header.
 4491: 	&Apache::loncommon::end_data_table_header_row();
 4492:     my @noupdate;
 4493:     my ($updateCtr,$noupdateCtr) = (1,1);
 4494:     my ($got_types,%queueable);
 4495:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4496: 	my $user = $env{'form.ctr'.$i};
 4497: 	my ($uname,$udom)=split(/:/,$user);
 4498: 	my %newrecord;
 4499: 	my $updateflag = 0;
 4500: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4501: 	my $canmodify = &canmodify($usec);
 4502: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4503: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4504: 	if (!$canmodify) {
 4505: 	    push(@noupdate,
 4506: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4507: 		 &mt('Not allowed to modify student')."</span></td>");
 4508: 	    next;
 4509: 	}
 4510:         my %aggregate = ();
 4511:         my $aggregateflag = 0;
 4512: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4513: 	foreach (@partid) {
 4514: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4515: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4516: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4517: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4518: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4519: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4520: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4521: 	    my $score;
 4522: 	    if ($partial eq '') {
 4523: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4524: 	    } elsif ($partial > 0) {
 4525: 		$score = 'correct_by_override';
 4526: 	    } elsif ($partial == 0) {
 4527: 		$score = 'incorrect_by_override';
 4528: 	    }
 4529: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4530: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4531: 
 4532: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4533: 		"$env{'user.name'}:$env{'user.domain'}";
 4534: 	    if ($dropMenu eq 'reset status' &&
 4535: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4536: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4537: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4538: 		$newrecord{'resource.'.$_.'.award'} = '';
 4539: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4540: 		$updateflag = 1;
 4541:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4542:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4543:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4544:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4545:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4546:                     $aggregateflag = 1;
 4547:                 }
 4548: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4549: 		$updateflag = 1;
 4550: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4551: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4552: 		$rec_update++;
 4553: 	    }
 4554: 
 4555: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4556: 		'<td align="center">'.$awarded.
 4557: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4558: 
 4559: 
 4560: 	    my $partid=$_;
 4561: 	    foreach my $stores (@parts) {
 4562: 		my ($part,$type) = &split_part_type($stores);
 4563: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4564: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4565: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4566: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4567: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4568: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4569: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4570: 		    $updateflag=1;
 4571: 		}
 4572: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4573: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4574: 	    }
 4575: 	}
 4576: 	$line.="\n";
 4577: 
 4578: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4579: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4580: 
 4581: 	if ($updateflag) {
 4582: 	    $count++;
 4583: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4584: 				    $udom,$uname);
 4585: 
 4586: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4587: 					      $cnum,$udom,$uname)) {
 4588: 		# need to figure out if should be in queue.
 4589: 		my %record =  
 4590: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4591: 					     $udom,$uname);
 4592: 		my $all_graded = 1;
 4593: 		my $none_graded = 1;
 4594:                 unless ($got_types) {
 4595:                     my $error;
 4596:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4597:                     unless ($error) {
 4598:                         foreach my $part (@parts) {
 4599:                             if (ref($resptype->{$part}) eq 'HASH') {
 4600:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4601:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4602:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4603:                                         $queueable{$part} = 1;
 4604:                                         last;
 4605:                                     }
 4606:                                 }
 4607:                             }
 4608:                         }
 4609:                     }
 4610:                     $got_types = 1;
 4611:                 }
 4612: 		foreach my $part (@parts) {
 4613:                     if ($queueable{$part}) {
 4614: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4615: 			    $all_graded = 0;
 4616: 		        } else {
 4617: 			    $none_graded = 0;
 4618: 		        }
 4619: 		    }
 4620:                 }
 4621: 		if ($all_graded || $none_graded) {
 4622: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4623: 							   $symb,$cdom,$cnum,
 4624: 							   $udom,$uname);
 4625: 		}
 4626: 	    }
 4627: 
 4628: 	    $result.=&Apache::loncommon::start_data_table_row().
 4629: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4630: 		&Apache::loncommon::end_data_table_row();
 4631: 	    $updateCtr++;
 4632: 	} else {
 4633: 	    push(@noupdate,
 4634: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4635: 	    $noupdateCtr++;
 4636: 	}
 4637:         if ($aggregateflag) {
 4638:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4639: 				  $cdom,$cnum);
 4640:         }
 4641:     }
 4642:     if (@noupdate) {
 4643:         my $numcols=$totcolspan+2;
 4644: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4645: 	    '<td align="center" colspan="'.$numcols.'">'.
 4646: 	    &mt('No Changes Occurred For the Students Below').
 4647: 	    '</td>'.
 4648: 	    &Apache::loncommon::end_data_table_row();
 4649: 	foreach my $line (@noupdate) {
 4650: 	    $result.=
 4651: 		&Apache::loncommon::start_data_table_row().
 4652: 		$line.
 4653: 		&Apache::loncommon::end_data_table_row();
 4654: 	}
 4655:     }
 4656:     $result .= &Apache::loncommon::end_data_table();
 4657:     my $msg = '<p><b>'.
 4658: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4659: 	    $rec_update,$count).'</b><br />'.
 4660: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4661: 	'</b></p>';
 4662:     return $title.$msg.$result;
 4663: }
 4664: 
 4665: sub split_part_type {
 4666:     my ($partstr) = @_;
 4667:     my ($temp,@allparts)=split(/_/,$partstr);
 4668:     my $type=pop(@allparts);
 4669:     my $part=join('_',@allparts);
 4670:     return ($part,$type);
 4671: }
 4672: 
 4673: #------------- end of section for handling grading by section/class ---------
 4674: #
 4675: #----------------------------------------------------------------------------
 4676: 
 4677: 
 4678: #----------------------------------------------------------------------------
 4679: #
 4680: #-------------------------- Next few routines handles grading by csv upload
 4681: #
 4682: #--- Javascript to handle csv upload
 4683: sub csvupload_javascript_reverse_associate {
 4684:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4685:     my $error2=&mt('You need to specify at least one grading field');
 4686:   &js_escape(\$error1);
 4687:   &js_escape(\$error2);
 4688:   return(<<ENDPICK);
 4689:   function verify(vf) {
 4690:     var foundsomething=0;
 4691:     var founduname=0;
 4692:     var foundID=0;
 4693:     var foundclicker=0;
 4694:     for (i=0;i<=vf.nfields.value;i++) {
 4695:       tw=eval('vf.f'+i+'.selectedIndex');
 4696:       if (i==0 && tw!=0) { foundID=1; }
 4697:       if (i==1 && tw!=0) { founduname=1; }
 4698:       if (i==2 && tw!=0) { foundclicker=1; }
 4699:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4700:     }
 4701:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4702: 	alert('$error1');
 4703: 	return;
 4704:     }
 4705:     if (foundsomething==0) {
 4706: 	alert('$error2');
 4707: 	return;
 4708:     }
 4709:     vf.submit();
 4710:   }
 4711:   function flip(vf,tf) {
 4712:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4713:     var i;
 4714:     for (i=0;i<=vf.nfields.value;i++) {
 4715:       //can not pick the same destination field for both name and domain
 4716:       if (((i ==0)||(i ==1)) && 
 4717:           ((tf==0)||(tf==1)) && 
 4718:           (i!=tf) &&
 4719:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4720:         eval('vf.f'+i+'.selectedIndex=0;')
 4721:       }
 4722:     }
 4723:   }
 4724: ENDPICK
 4725: }
 4726: 
 4727: sub csvupload_javascript_forward_associate {
 4728:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4729:     my $error2=&mt('You need to specify at least one grading field');
 4730:   &js_escape(\$error1);
 4731:   &js_escape(\$error2);
 4732:   return(<<ENDPICK);
 4733:   function verify(vf) {
 4734:     var foundsomething=0;
 4735:     var founduname=0;
 4736:     var foundID=0;
 4737:     var foundclicker=0;
 4738:     for (i=0;i<=vf.nfields.value;i++) {
 4739:       tw=eval('vf.f'+i+'.selectedIndex');
 4740:       if (tw==1) { foundID=1; }
 4741:       if (tw==2) { founduname=1; }
 4742:       if (tw==3) { foundclicker=1; }
 4743:       if (tw>4) { foundsomething=1; }
 4744:     }
 4745:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4746: 	alert('$error1');
 4747: 	return;
 4748:     }
 4749:     if (foundsomething==0) {
 4750: 	alert('$error2');
 4751: 	return;
 4752:     }
 4753:     vf.submit();
 4754:   }
 4755:   function flip(vf,tf) {
 4756:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4757:     var i;
 4758:     //can not pick the same destination field twice
 4759:     for (i=0;i<=vf.nfields.value;i++) {
 4760:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4761:         eval('vf.f'+i+'.selectedIndex=0;')
 4762:       }
 4763:     }
 4764:   }
 4765: ENDPICK
 4766: }
 4767: 
 4768: sub csvuploadmap_header {
 4769:     my ($request,$symb,$datatoken,$distotal)= @_;
 4770:     my $javascript;
 4771:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4772: 	$javascript=&csvupload_javascript_reverse_associate();
 4773:     } else {
 4774: 	$javascript=&csvupload_javascript_forward_associate();
 4775:     }
 4776: 
 4777:     $symb = &Apache::lonenc::check_encrypt($symb);
 4778:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4779:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4780:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4781:     my $reverse=&mt("Reverse Association");
 4782:     $request->print(<<ENDPICK);
 4783: <br />
 4784: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4785: <input type="hidden" name="associate"  value="" />
 4786: <input type="hidden" name="phase"      value="three" />
 4787: <input type="hidden" name="datatoken"  value="$datatoken" />
 4788: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4789: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4790: <input type="hidden" name="upfile_associate" 
 4791:                                        value="$env{'form.upfile_associate'}" />
 4792: <input type="hidden" name="symb"       value="$symb" />
 4793: <input type="hidden" name="command"    value="csvuploadoptions" />
 4794: <hr />
 4795: ENDPICK
 4796:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4797:     return '';
 4798: 
 4799: }
 4800: 
 4801: sub csvupload_fields {
 4802:     my ($symb,$errorref) = @_;
 4803:     my $toolsymb;
 4804:     if ($symb =~ /ext\.tool$/) {
 4805:         $toolsymb = $symb;
 4806:     }
 4807:     my (@parts) = &getpartlist($symb,$errorref);
 4808:     if (ref($errorref)) {
 4809:         if ($$errorref) {
 4810:             return;
 4811:         }
 4812:     }
 4813: 
 4814:     my @fields=(['ID','Student/Employee ID'],
 4815: 		['username','Student Username'],
 4816: 		['clicker','Clicker ID'],
 4817: 		['domain','Student Domain']);
 4818:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4819:     foreach my $part (sort(@parts)) {
 4820: 	my @datum;
 4821: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4822: 	my $name=$part;
 4823: 	if (!$display) { $display = $name; }
 4824: 	@datum=($name,$display);
 4825: 	if ($name=~/^stores_(.*)_awarded/) {
 4826: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4827: 	}
 4828: 	push(@fields,\@datum);
 4829:     }
 4830:     return (@fields);
 4831: }
 4832: 
 4833: sub csvuploadmap_footer {
 4834:     my ($request,$i,$keyfields) =@_;
 4835:     my $buttontext = &mt('Assign Grades');
 4836:     $request->print(<<ENDPICK);
 4837: </table>
 4838: <input type="hidden" name="nfields" value="$i" />
 4839: <input type="hidden" name="keyfields" value="$keyfields" />
 4840: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4841: </form>
 4842: ENDPICK
 4843: }
 4844: 
 4845: sub checkforfile_js {
 4846:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4847:     &js_escape(\$alertmsg);
 4848:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4849:     function checkUpload(formname) {
 4850: 	if (formname.upfile.value == "") {
 4851: 	    alert("$alertmsg");
 4852: 	    return false;
 4853: 	}
 4854: 	formname.submit();
 4855:     }
 4856: CSVFORMJS
 4857:     return $result;
 4858: }
 4859: 
 4860: sub upcsvScores_form {
 4861:     my ($request,$symb) = @_;
 4862:     if (!$symb) {return '';}
 4863:     my $result=&checkforfile_js();
 4864:     $result.=&Apache::loncommon::start_data_table().
 4865:              &Apache::loncommon::start_data_table_header_row().
 4866:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4867:              &Apache::loncommon::end_data_table_header_row().
 4868:              &Apache::loncommon::start_data_table_row().'<td>';
 4869:     my $upload=&mt("Upload Scores");
 4870:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4871:     my $ignore=&mt('Ignore First Line');
 4872:     $symb = &Apache::lonenc::check_encrypt($symb);
 4873:     $result.=<<ENDUPFORM;
 4874: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4875: <input type="hidden" name="symb" value="$symb" />
 4876: <input type="hidden" name="command" value="csvuploadmap" />
 4877: $upfile_select
 4878: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4879: </form>
 4880: ENDUPFORM
 4881:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4882:                            &mt("How do I create a CSV file from a spreadsheet")).
 4883:              '</td>'.
 4884:             &Apache::loncommon::end_data_table_row().
 4885:             &Apache::loncommon::end_data_table();
 4886:     return $result;
 4887: }
 4888: 
 4889: 
 4890: sub csvuploadmap {
 4891:     my ($request,$symb) = @_;
 4892:     if (!$symb) {return '';}
 4893: 
 4894:     my $datatoken;
 4895:     if (!$env{'form.datatoken'}) {
 4896: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4897:     } else {
 4898: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4899:         if ($datatoken ne '') {
 4900: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4901:         }
 4902:     }
 4903:     my @records=&Apache::loncommon::upfile_record_sep();
 4904:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4905:     my ($i,$keyfields);
 4906:     if (@records) {
 4907:         my $fieldserror;
 4908: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4909:         if ($fieldserror) {
 4910:             $request->print(&navmap_errormsg());
 4911:             return;
 4912:         }
 4913: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4914: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4915: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4916: 							  \@fields);
 4917: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4918: 	    chop($keyfields);
 4919: 	} else {
 4920: 	    unshift(@fields,['none','']);
 4921: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4922: 							    \@fields);
 4923:             foreach my $rec (@records) {
 4924:                 my %temp = &Apache::loncommon::record_sep($rec);
 4925:                 if (%temp) {
 4926:                     $keyfields=join(',',sort(keys(%temp)));
 4927:                     last;
 4928:                 }
 4929:             }
 4930: 	}
 4931:     }
 4932:     &csvuploadmap_footer($request,$i,$keyfields);
 4933: 
 4934:     return '';
 4935: }
 4936: 
 4937: sub csvuploadoptions {
 4938:     my ($request,$symb)= @_;
 4939:     my $overwrite=&mt('Overwrite any existing score');
 4940:     $request->print(<<ENDPICK);
 4941: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4942: <input type="hidden" name="command"    value="csvuploadassign" />
 4943: <p>
 4944: <label>
 4945:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4946:    $overwrite
 4947: </label>
 4948: </p>
 4949: ENDPICK
 4950:     my %fields=&get_fields();
 4951:     if (!defined($fields{'domain'})) {
 4952: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4953: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4954:     }
 4955:     foreach my $key (sort(keys(%env))) {
 4956: 	if ($key !~ /^form\.(.*)$/) { next; }
 4957: 	my $cleankey=$1;
 4958: 	if ($cleankey eq 'command') { next; }
 4959: 	$request->print('<input type="hidden" name="'.$cleankey.
 4960: 			'"  value="'.$env{$key}.'" />'."\n");
 4961:     }
 4962:     # FIXME do a check for any duplicated user ids...
 4963:     # FIXME do a check for any invalid user ids?...
 4964:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4965: <hr /></form>'."\n");
 4966:     return '';
 4967: }
 4968: 
 4969: sub get_fields {
 4970:     my %fields;
 4971:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4972:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4973: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4974: 	    if ($env{'form.f'.$i} ne 'none') {
 4975: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4976: 	    }
 4977: 	} else {
 4978: 	    if ($env{'form.f'.$i} ne 'none') {
 4979: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4980: 	    }
 4981: 	}
 4982:     }
 4983:     return %fields;
 4984: }
 4985: 
 4986: sub csvuploadassign {
 4987:     my ($request,$symb) = @_;
 4988:     if (!$symb) {return '';}
 4989:     my $error_msg = '';
 4990:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4991:     if ($datatoken ne '') { 
 4992:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4993:     }
 4994:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4995:     my %fields=&get_fields();
 4996:     my $courseid=$env{'request.course.id'};
 4997:     my ($classlist) = &getclasslist('all',0);
 4998:     my @notallowed;
 4999:     my @skipped;
 5000:     my @warnings;
 5001:     my $countdone=0;
 5002:     foreach my $grade (@gradedata) {
 5003: 	my %entries=&Apache::loncommon::record_sep($grade);
 5004: 	my $domain;
 5005: 	if ($entries{$fields{'domain'}}) {
 5006: 	    $domain=$entries{$fields{'domain'}};
 5007: 	} else {
 5008: 	    $domain=$env{'form.default_domain'};
 5009: 	}
 5010: 	$domain=~s/\s//g;
 5011: 	my $username=$entries{$fields{'username'}};
 5012: 	$username=~s/\s//g;
 5013: 	if (!$username) {
 5014: 	    my $id=$entries{$fields{'ID'}};
 5015: 	    $id=~s/\s//g;
 5016:             if ($id ne '') {
 5017: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 5018: 	        $username=$ids{$id};
 5019:             } else {
 5020:                 if ($entries{$fields{'clicker'}}) {
 5021:                     my $clicker = $entries{$fields{'clicker'}};
 5022:                     $clicker=~s/\s//g;
 5023:                     if ($clicker ne '') {
 5024:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 5025:                         if ($clickers{$clicker} ne '') {  
 5026:                             my $match = 0;
 5027:                             my @inclass;
 5028:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 5029:                                 if (exists($$classlist{"$poss:$domain"})) {
 5030:                                     $username = $poss;
 5031:                                     push(@inclass,$poss);
 5032:                                     $match ++;
 5033:                                     
 5034:                                 }
 5035:                             }
 5036:                             if ($match > 1) {
 5037:                                 undef($username); 
 5038:                                 $request->print('<p class="LC_warning">'.
 5039:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 5040:                                                 $clicker,join(', ',@inclass)).'</p>');
 5041:                             }
 5042:                         }
 5043:                     }
 5044:                 }
 5045:             }
 5046: 	}
 5047: 	if (!exists($$classlist{"$username:$domain"})) {
 5048: 	    my $id=$entries{$fields{'ID'}};
 5049: 	    $id=~s/\s//g;
 5050:             my $clicker = $entries{$fields{'clicker'}};
 5051:             $clicker=~s/\s//g;
 5052:             if ($clicker) {
 5053:                 push(@skipped,"$clicker:$domain");
 5054: 	    } elsif ($id) {
 5055: 		push(@skipped,"$id:$domain");
 5056: 	    } else {
 5057: 		push(@skipped,"$username:$domain");
 5058: 	    }
 5059: 	    next;
 5060: 	}
 5061: 	my $usec=$classlist->{"$username:$domain"}[5];
 5062: 	if (!&canmodify($usec)) {
 5063: 	    push(@notallowed,"$username:$domain");
 5064: 	    next;
 5065: 	}
 5066: 	my %points;
 5067: 	my %grades;
 5068: 	foreach my $dest (keys(%fields)) {
 5069: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5070: 		$dest eq 'domain') { next; }
 5071: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5072: 	    if ($dest=~/stores_(.*)_points/) {
 5073: 		my $part=$1;
 5074: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5075: 					      $symb,$domain,$username);
 5076:                 if ($wgt) {
 5077:                     $entries{$fields{$dest}}=~s/\s//g;
 5078:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5079:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5080:                                           : 'correct_by_override';
 5081:                     if ($pcr>1) {
 5082:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5083:                     }
 5084:                     $grades{"resource.$part.awarded"}=$pcr;
 5085:                     $grades{"resource.$part.solved"}=$award;
 5086:                     $points{$part}=1;
 5087:                 } else {
 5088:                     $error_msg = "<br />" .
 5089:                         &mt("Some point values were assigned"
 5090:                             ." for problems with a weight "
 5091:                             ."of zero. These values were "
 5092:                             ."ignored.");
 5093:                 }
 5094: 	    } else {
 5095: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5096: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5097: 		my $store_key=$dest;
 5098: 		$store_key=~s/^stores/resource/;
 5099: 		$store_key=~s/_/\./g;
 5100: 		$grades{$store_key}=$entries{$fields{$dest}};
 5101: 	    }
 5102: 	}
 5103: 	if (! %grades) {
 5104:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5105:         } else {
 5106: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5107: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5108: 					   $env{'request.course.id'},
 5109: 					   $domain,$username);
 5110: 	   if ($result eq 'ok') {
 5111: # Successfully stored
 5112: 	      $request->print('.');
 5113: # Remove from grading queue
 5114:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5115:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5116:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5117:                                              $domain,$username);
 5118:               $countdone++;
 5119:            } else {
 5120: 	      $request->print("<p><span class=\"LC_error\">".
 5121:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5122:                                   "$username:$domain",$result)."</span></p>");
 5123: 	   }
 5124: 	   $request->rflush();
 5125:         }
 5126:     }
 5127:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5128:     if (@warnings) {
 5129:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5130:         $request->print(join(', ',@warnings));
 5131:     }
 5132:     if (@skipped) {
 5133: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5134:         $request->print(join(', ',@skipped));
 5135:     }
 5136:     if (@notallowed) {
 5137: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5138: 	$request->print(join(', ',@notallowed));
 5139:     }
 5140:     $request->print("<br />\n");
 5141:     return $error_msg;
 5142: }
 5143: #------------- end of section for handling csv file upload ---------
 5144: #
 5145: #-------------------------------------------------------------------
 5146: #
 5147: #-------------- Next few routines handle grading by page/sequence
 5148: #
 5149: #--- Select a page/sequence and a student to grade
 5150: sub pickStudentPage {
 5151:     my ($request,$symb) = @_;
 5152: 
 5153:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5154:     &js_escape(\$alertmsg);
 5155:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5156: 
 5157: function checkPickOne(formname) {
 5158:     if (radioSelection(formname.student) == null) {
 5159: 	alert("$alertmsg");
 5160: 	return;
 5161:     }
 5162:     ptr = pullDownSelection(formname.selectpage);
 5163:     formname.page.value = formname["page"+ptr].value;
 5164:     formname.title.value = formname["title"+ptr].value;
 5165:     formname.submit();
 5166: }
 5167: 
 5168: LISTJAVASCRIPT
 5169:     &commonJSfunctions($request);
 5170: 
 5171:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5172:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5173:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5174:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5175: 
 5176:     my $result='<h3><span class="LC_info">&nbsp;'.
 5177: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5178: 
 5179:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5180:     my $map_error;
 5181:     my ($titles,$symbx) = &getSymbMap($map_error);
 5182:     if ($map_error) {
 5183:         $request->print(&navmap_errormsg());
 5184:         return; 
 5185:     }
 5186:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5187: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5188: #    my $type=($curpage =~ /\.(page|sequence)/);
 5189: 
 5190:     # Collection of hidden fields
 5191:     my $ctr=0;
 5192:     foreach (@$titles) {
 5193:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5194:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5195:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5196:         $ctr++;
 5197:     }
 5198:     $result.='<input type="hidden" name="page" />'."\n".
 5199:         '<input type="hidden" name="title" />'."\n";
 5200: 
 5201:     $result.=&build_section_inputs();
 5202:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5203:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5204: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5205: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5206: 
 5207:     # Show grading options
 5208:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5209:     my $select = '<select name="selectpage">'."\n";
 5210:     $ctr=0;
 5211:     foreach (@$titles) {
 5212: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5213: 	$select.='<option value="'.$ctr.'"'.
 5214: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5215: 	    '>'.$showtitle.'</option>'."\n";
 5216: 	$ctr++;
 5217:     }
 5218:     $select.= '</select>';
 5219: 
 5220:     $result.=
 5221:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5222:        .$select
 5223:        .&Apache::lonhtmlcommon::row_closure();
 5224: 
 5225:     $result.=
 5226:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5227:        .'<label><input type="radio" name="vProb" value="no"'
 5228:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5229:        .'<label><input type="radio" name="vProb" value="yes" />'
 5230:            .&mt('yes').'</label>'."\n"
 5231:        .&Apache::lonhtmlcommon::row_closure();
 5232: 
 5233:     $result.=
 5234:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5235:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5236:            .&mt('none').' </label>'."\n"
 5237:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5238:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5239:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5240:            .&mt('all submissions with details').' </label>'
 5241:        .&Apache::lonhtmlcommon::row_closure();
 5242:     
 5243:     $result.=
 5244:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5245:        .'<input type="text" name="CODE" value="" />'
 5246:        .&Apache::lonhtmlcommon::row_closure(1)
 5247:        .&Apache::lonhtmlcommon::end_pick_box();
 5248: 
 5249:     # Show list of students to select for grading
 5250:     $result.='<br /><input type="button" '.
 5251:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5252: 
 5253:     $request->print($result);
 5254: 
 5255:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5256: 	&Apache::loncommon::start_data_table().
 5257: 	&Apache::loncommon::start_data_table_header_row().
 5258: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5259: 	'<th>'.&nameUserString('header').'</th>'.
 5260: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5261: 	'<th>'.&nameUserString('header').'</th>'.
 5262: 	&Apache::loncommon::end_data_table_header_row();
 5263:  
 5264:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5265:     my $ptr = 1;
 5266:     foreach my $student (sort 
 5267: 			 {
 5268: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5269: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5270: 			     }
 5271: 			     return $a cmp $b;
 5272: 			 } (keys(%$fullname))) {
 5273: 	my ($uname,$udom) = split(/:/,$student);
 5274: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5275:                                   : '</td>');
 5276: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5277: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5278: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5279: 	$studentTable.=
 5280: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5281:                          : '');
 5282: 	$ptr++;
 5283:     }
 5284:     if ($ptr%2 == 0) {
 5285: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5286: 	    &Apache::loncommon::end_data_table_row();
 5287:     }
 5288:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5289:     $studentTable.='<input type="button" '.
 5290:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5291: 
 5292:     $request->print($studentTable);
 5293: 
 5294:     return '';
 5295: }
 5296: 
 5297: sub getSymbMap {
 5298:     my ($map_error) = @_;
 5299:     my $navmap = Apache::lonnavmaps::navmap->new();
 5300:     unless (ref($navmap)) {
 5301:         if (ref($map_error)) {
 5302:             $$map_error = 'navmap';
 5303:         }
 5304:         return;
 5305:     }
 5306:     my %symbx = ();
 5307:     my @titles = ();
 5308:     my $minder = 0;
 5309: 
 5310:     # Gather every sequence that has problems.
 5311:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5312: 					       1,0,1);
 5313:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5314: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5315: 	    my $title = $minder.'.'.
 5316: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5317: 	    push(@titles, $title); # minder in case two titles are identical
 5318: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5319: 	    $minder++;
 5320: 	}
 5321:     }
 5322:     return \@titles,\%symbx;
 5323: }
 5324: 
 5325: #
 5326: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5327: sub displayPage {
 5328:     my ($request,$symb) = @_;
 5329:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5330:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5331:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5332:     my $pageTitle = $env{'form.page'};
 5333:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5334:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5335:     my $usec=$classlist->{$env{'form.student'}}[5];
 5336: 
 5337:     #need to make sure we have the correct data for later EXT calls, 
 5338:     #thus invalidate the cache
 5339:     &Apache::lonnet::devalidatecourseresdata(
 5340:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5341:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5342:     &Apache::lonnet::clear_EXT_cache_status();
 5343: 
 5344:     if (!&canview($usec)) {
 5345:         $request->print(
 5346:             '<span class="LC_warning">'.
 5347:             &mt('Unable to view requested student. ([_1])',
 5348:                     $env{'form.student'}).
 5349:             '</span>');
 5350:         return;
 5351:     }
 5352:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5353:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5354: 	'</h3>'."\n";
 5355:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5356:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5357: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5358:     } else {
 5359: 	delete($env{'form.CODE'});
 5360:     }
 5361:     &sub_page_js($request);
 5362:     $request->print($result);
 5363: 
 5364:     my $navmap = Apache::lonnavmaps::navmap->new();
 5365:     unless (ref($navmap)) {
 5366:         $request->print(&navmap_errormsg());
 5367:         return;
 5368:     }
 5369:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5370:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5371:     if (!$map) {
 5372: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5373: 	return; 
 5374:     }
 5375:     my $iterator = $navmap->getIterator($map->map_start(),
 5376: 					$map->map_finish());
 5377: 
 5378:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5379: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5380: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5381: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5382: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5383: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5384: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5385: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5386: 
 5387:     if (defined($env{'form.CODE'})) {
 5388: 	$studentTable.=
 5389: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5390:     }
 5391:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5392: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5393: 
 5394:     $studentTable.='&nbsp;<span class="LC_info">'.
 5395:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5396:         '</span>'."\n".
 5397: 	&Apache::loncommon::start_data_table().
 5398: 	&Apache::loncommon::start_data_table_header_row().
 5399: 	'<th>'.&mt('Prob.').'</th>'.
 5400: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5401: 	&Apache::loncommon::end_data_table_header_row();
 5402: 
 5403:     &Apache::lonxml::clear_problem_counter();
 5404:     my ($depth,$question,$prob) = (1,1,1);
 5405:     $iterator->next(); # skip the first BEGIN_MAP
 5406:     my $curRes = $iterator->next(); # for "current resource"
 5407:     while ($depth > 0) {
 5408:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5409:         if($curRes == $iterator->END_MAP) { $depth--; }
 5410: 
 5411:         if (ref($curRes) && $curRes->is_gradable()) {
 5412: 	    my $parts = $curRes->parts();
 5413:             my $title = $curRes->compTitle();
 5414: 	    my $symbx = $curRes->symb();
 5415:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5416: 	    $studentTable.=
 5417: 		&Apache::loncommon::start_data_table_row().
 5418: 		'<td align="center" valign="top" >'.$prob.
 5419: 		(scalar(@{$parts}) == 1 ? '' 
 5420: 		                        : '<br />('.&mt('[_1]parts',
 5421: 							scalar(@{$parts}).'&nbsp;').')'
 5422: 		 ).
 5423: 		 '</td>';
 5424: 	    $studentTable.='<td valign="top">';
 5425: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5426:             if ($is_tool) {
 5427:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5428:             } else {
 5429: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5430: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5431: 					         undef,'both',\%form);
 5432: 	        } else {
 5433: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5434: 		    $companswer =~ s|<form(.*?)>||g;
 5435: 		    $companswer =~ s|</form>||g;
 5436: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5437: #		        $companswer =~ s/$1/ /ms;
 5438: #		        $request->print('match='.$1."<br />\n");
 5439: #		    }
 5440: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5441: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5442: 		}
 5443: 	    }
 5444: 
 5445: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5446: 
 5447: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5448: 		if ($record{'version'} eq '') {
 5449:                     my $msg = &mt('No recorded submission for this problem.');
 5450:                     if ($is_tool) {
 5451:                         $msg = &mt('No recorded transactions for this external tool');
 5452:                     }
 5453: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5454: 		} else {
 5455: 		    my %responseType = ();
 5456: 		    foreach my $partid (@{$parts}) {
 5457: 			my @responseIds =$curRes->responseIds($partid);
 5458: 			my @responseType =$curRes->responseType($partid);
 5459: 			my %responseIds;
 5460: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5461: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5462: 			}
 5463: 			$responseType{$partid} = \%responseIds;
 5464: 		    }
 5465: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5466: 		}
 5467: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5468: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5469:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5470: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5471: 									$env{'request.course.id'},
 5472: 									'','.submission',undef,
 5473:                                                                         $usec,$identifier);
 5474:  
 5475: 	    }
 5476: 	    if (&canmodify($usec)) {
 5477:             $studentTable.=&gradeBox_start();
 5478: 		foreach my $partid (@{$parts}) {
 5479: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5480: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5481: 		    $question++;
 5482: 		}
 5483:             $studentTable.=&gradeBox_end();
 5484: 		$prob++;
 5485: 	    }
 5486: 	    $studentTable.='</td></tr>';
 5487: 
 5488: 	}
 5489:         $curRes = $iterator->next();
 5490:     }
 5491:     my $disabled;
 5492:     unless (&canmodify($usec)) {
 5493:         $disabled = ' disabled="disabled"';
 5494:     }
 5495: 
 5496:     $studentTable.=
 5497:         '</table>'."\n".
 5498:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5499:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5500:         '</form>'."\n";
 5501:     $request->print($studentTable);
 5502: 
 5503:     return '';
 5504: }
 5505: 
 5506: sub displaySubByDates {
 5507:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5508:     my $isCODE=0;
 5509:     my $isTask = ($symb =~/\.task$/);
 5510:     my $is_tool = ($symb =~/\.tool$/);
 5511:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5512:     my $studentTable=&Apache::loncommon::start_data_table().
 5513: 	&Apache::loncommon::start_data_table_header_row().
 5514: 	'<th>'.&mt('Date/Time').'</th>'.
 5515: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5516:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5517: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5518: 	'<th>'.&mt('Status').'</th>'.
 5519: 	&Apache::loncommon::end_data_table_header_row();
 5520:     my ($version);
 5521:     my %mark;
 5522:     my %orders;
 5523:     $mark{'correct_by_student'} = $checkIcon;
 5524:     if (!exists($$record{'1:timestamp'})) {
 5525:         if ($is_tool) {
 5526:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5527:         } else {
 5528:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5529:         }
 5530:     }
 5531: 
 5532:     my $interaction;
 5533:     my $no_increment = 1;
 5534:     my (%lastrndseed,%lasttype);
 5535:     for ($version=1;$version<=$$record{'version'};$version++) {
 5536: 	my $timestamp = 
 5537: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5538: 	if (exists($$record{$version.':resource.0.version'})) {
 5539: 	    $interaction = $$record{$version.':resource.0.version'};
 5540: 	}
 5541:         if ($isTask && $env{'form.previousversion'}) {
 5542:             next unless ($interaction == $env{'form.previousversion'});
 5543:         }
 5544: 	my $where = ($isTask ? "$version:resource.$interaction"
 5545: 		             : "$version:resource");
 5546: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5547: 	    '<td>'.$timestamp.'</td>';
 5548: 	if ($isCODE) {
 5549: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5550: 	}
 5551:         if ($isTask) {
 5552:             $studentTable.='<td>'.$interaction.'</td>';
 5553:         }
 5554: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5555: 	my @displaySub = ();
 5556: 	foreach my $partid (@{$parts}) {
 5557:             my ($hidden,$type);
 5558:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5559:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5560:                 $hidden = 1;
 5561:             }
 5562:             my @matchKey;
 5563:             if ($isTask) {
 5564:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5565:             } elsif ($is_tool) {
 5566:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5567:             } else {
 5568:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5569:             }
 5570: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5571: 	    my $display_part=&get_display_part($partid,$symb);
 5572: 	    foreach my $matchKey (@matchKey) {
 5573: 		if (exists($$record{$version.':'.$matchKey}) &&
 5574: 		    $$record{$version.':'.$matchKey} ne '') {
 5575:                     if ($is_tool) {
 5576:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5577:                     } else {
 5578: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5579: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5580:                         $displaySub[0].='<span class="LC_nobreak">';
 5581:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5582:                                        .' <span class="LC_internal_info">'
 5583:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5584:                                        .'</span>'
 5585:                                        .' <b>';
 5586:                         if ($hidden) {
 5587:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5588:                         } else {
 5589:                             my ($trial,$rndseed,$newvariation);
 5590:                             if ($type eq 'randomizetry') {
 5591:                                 $trial = $$record{"$where.$partid.tries"};
 5592:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5593:                             }
 5594: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5595: 			        $displaySub[0].=&mt('Trial not counted');
 5596: 		            } else {
 5597: 			        $displaySub[0].=&mt('Trial: [_1]',
 5598: 					        $$record{"$where.$partid.tries"});
 5599:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5600:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5601:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5602:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5603:                                     }
 5604:                                 }
 5605:                                 $lastrndseed{$partid} = $rndseed;
 5606:                                 $lasttype{$partid} = $type;
 5607: 		            }
 5608: 		            my $responseType=($isTask ? 'Task'
 5609:                                               : $responseType->{$partid}->{$responseId});
 5610: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5611: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5612: 			        $orders{$partid}->{$responseId}=
 5613: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5614:                                                $no_increment,$type,$trial,$rndseed);
 5615: 		            }
 5616: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5617: 		            $displaySub[0].='&nbsp; '.
 5618: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5619:                         }
 5620:                     }
 5621: 		}
 5622: 	    }
 5623: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5624: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5625: 				    $$record{"$where.$partid.checkedin"},
 5626: 				    $$record{"$where.$partid.checkedin.slot"}).
 5627: 					'<br />';
 5628: 	    }
 5629: 	    if (exists $$record{"$where.$partid.award"}) {
 5630: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5631: 		    lc($$record{"$where.$partid.award"}).' '.
 5632: 		    $mark{$$record{"$where.$partid.solved"}}.
 5633: 		    '<br />';
 5634: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5635: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5636: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5637: 		}
 5638: 	    }
 5639: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5640: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5641: 		unless ($is_tool) {
 5642: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5643: 		}
 5644: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5645: 		$displaySub[2].=
 5646: 		    $$record{"$version:resource.$partid.regrader"};
 5647:                 unless ($is_tool) {
 5648: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5649:                 }
 5650: 	    }
 5651: 	}
 5652: 	# needed because old essay regrader has not parts info
 5653: 	if (exists $$record{"$version:resource.regrader"}) {
 5654: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5655: 	}
 5656: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5657: 	if ($displaySub[2]) {
 5658: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5659: 	}
 5660: 	$studentTable.='&nbsp;</td>'.
 5661: 	    &Apache::loncommon::end_data_table_row();
 5662:     }
 5663:     $studentTable.=&Apache::loncommon::end_data_table();
 5664:     return $studentTable;
 5665: }
 5666: 
 5667: sub updateGradeByPage {
 5668:     my ($request,$symb) = @_;
 5669: 
 5670:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5671:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5672:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5673:     my $pageTitle = $env{'form.page'};
 5674:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5675:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5676:     my $usec=$classlist->{$env{'form.student'}}[5];
 5677:     if (!&canmodify($usec)) {
 5678: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5679: 	return;
 5680:     }
 5681:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5682:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5683: 	'</h3>'."\n";
 5684: 
 5685:     $request->print($result);
 5686: 
 5687: 
 5688:     my $navmap = Apache::lonnavmaps::navmap->new();
 5689:     unless (ref($navmap)) {
 5690:         $request->print(&navmap_errormsg());
 5691:         return;
 5692:     }
 5693:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5694:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5695:     if (!$map) {
 5696: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5697: 	return; 
 5698:     }
 5699:     my $iterator = $navmap->getIterator($map->map_start(),
 5700: 					$map->map_finish());
 5701: 
 5702:     my $studentTable=
 5703: 	&Apache::loncommon::start_data_table().
 5704: 	&Apache::loncommon::start_data_table_header_row().
 5705: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5706: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5707: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5708: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5709: 	&Apache::loncommon::end_data_table_header_row();
 5710: 
 5711:     $iterator->next(); # skip the first BEGIN_MAP
 5712:     my $curRes = $iterator->next(); # for "current resource"
 5713:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5714:     while ($depth > 0) {
 5715:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5716:         if($curRes == $iterator->END_MAP) { $depth--; }
 5717: 
 5718:         if (ref($curRes) && $curRes->is_problem()) {
 5719: 	    my $parts = $curRes->parts();
 5720:             my $title = $curRes->compTitle();
 5721: 	    my $symbx = $curRes->symb();
 5722: 	    $studentTable.=
 5723: 		&Apache::loncommon::start_data_table_row().
 5724: 		'<td align="center" valign="top" >'.$prob.
 5725: 		(scalar(@{$parts}) == 1 ? '' 
 5726:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5727: 		.')').'</td>';
 5728: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5729: 
 5730: 	    my %newrecord=();
 5731: 	    my @displayPts=();
 5732:             my %aggregate = ();
 5733:             my $aggregateflag = 0;
 5734:             my %queueable;
 5735:             if ($env{'form.HIDE'.$prob}) {
 5736:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5737:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5738:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5739:                 $hideflag += $numchgs;
 5740:             }
 5741: 	    foreach my $partid (@{$parts}) {
 5742: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5743: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5744:                 my @types = $curRes->responseType($partid);
 5745:                 if (grep(/^essay$/,@types)) {
 5746:                     $queueable{$partid} = 1;
 5747:                 } else {
 5748:                     my @ids = $curRes->responseIds($partid);
 5749:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5750:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
 5751:                                                           '.handgrade',$symb);
 5752:                         if (lc($hndgrd) eq 'yes') {
 5753:                             $queueable{$partid} = 1;
 5754:                             last;
 5755:                         }
 5756:                     }
 5757:                 }
 5758: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5759: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5760: 		my $partial = $newpts/$wgt;
 5761: 		my $score;
 5762: 		if ($partial > 0) {
 5763: 		    $score = 'correct_by_override';
 5764: 		} elsif ($newpts ne '') { #empty is taken as 0
 5765: 		    $score = 'incorrect_by_override';
 5766: 		}
 5767: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5768: 		if ($dropMenu eq 'excused') {
 5769: 		    $partial = '';
 5770: 		    $score = 'excused';
 5771: 		} elsif ($dropMenu eq 'reset status'
 5772: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5773: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5774: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5775: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5776: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5777: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5778: 		    $changeflag++;
 5779: 		    $newpts = '';
 5780:                     
 5781:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5782:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5783:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5784:                     if ($aggtries > 0) {
 5785:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5786:                         $aggregateflag = 1;
 5787:                     }
 5788: 		}
 5789: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5790: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5791: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5792: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5793: 		    '&nbsp;<br />';
 5794: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5795: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5796: 		    '&nbsp;<br />';
 5797: 		$question++;
 5798: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5799: 
 5800: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5801: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5802: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5803: 		    if (scalar(keys(%newrecord)) > 0);
 5804: 
 5805: 		$changeflag++;
 5806: 	    }
 5807: 	    if (scalar(keys(%newrecord)) > 0) {
 5808: 		my %record = 
 5809: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5810: 					     $udom,$uname);
 5811: 
 5812: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5813: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5814: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5815: 		    $newrecord{'resource.CODE'} = '';
 5816: 		}
 5817: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5818: 					$udom,$uname);
 5819: 		%record = &Apache::lonnet::restore($symbx,
 5820: 						   $env{'request.course.id'},
 5821: 						   $udom,$uname);
 5822: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5823: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5824: 	    }
 5825: 	    
 5826:             if ($aggregateflag) {
 5827:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5828:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5829:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5830:             }
 5831: 
 5832: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5833: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5834: 		&Apache::loncommon::end_data_table_row();
 5835: 
 5836: 	    $prob++;
 5837: 	}
 5838:         $curRes = $iterator->next();
 5839:     }
 5840: 
 5841:     $studentTable.=&Apache::loncommon::end_data_table();
 5842:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5843: 		  &mt('The scores were changed for [quant,_1,problem].',
 5844: 		  $changeflag).'<br />');
 5845:     my $hidemsg=($hideflag == 0 ? '' :
 5846:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5847:                      $hideflag).'<br />');
 5848:     $request->print($hidemsg.$grademsg.$studentTable);
 5849: 
 5850:     return '';
 5851: }
 5852: 
 5853: #-------- end of section for handling grading by page/sequence ---------
 5854: #
 5855: #-------------------------------------------------------------------
 5856: 
 5857: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5858: #
 5859: #------ start of section for handling grading by page/sequence ---------
 5860: 
 5861: =pod
 5862: 
 5863: =head1 Bubble sheet grading routines
 5864: 
 5865:   For this documentation:
 5866: 
 5867:    'scanline' refers to the full line of characters
 5868:    from the file that we are parsing that represents one entire sheet
 5869: 
 5870:    'bubble line' refers to the data
 5871:    representing the line of bubbles that are on the physical bubblesheet
 5872: 
 5873: 
 5874: The overall process is that a scanned in bubblesheet data is uploaded
 5875: into a course. When a user wants to grade, they select a
 5876: sequence/folder of resources, a file of bubblesheet info, and pick
 5877: one of the predefined configurations for what each scanline looks
 5878: like.
 5879: 
 5880: Next each scanline is checked for any errors of either 'missing
 5881: bubbles' (it's an error because it may have been mis-scanned
 5882: because too light bubbling), 'double bubble' (each bubble line should
 5883: have no more than one letter picked), invalid or duplicated CODE,
 5884: invalid student/employee ID
 5885: 
 5886: If the CODE option is used that determines the randomization of the
 5887: homework problems, either way the student/employee ID is looked up into a
 5888: username:domain.
 5889: 
 5890: During the validation phase the instructor can choose to skip scanlines. 
 5891: 
 5892: After the validation phase, there are now 3 bubblesheet files
 5893: 
 5894:   scantron_original_filename (unmodified original file)
 5895:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5896:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5897: 
 5898: Also there is a separate hash nohist_scantrondata that contains extra
 5899: correction information that isn't representable in the bubblesheet
 5900: file (see &scantron_getfile() for more information)
 5901: 
 5902: After all scanlines are either valid, marked as valid or skipped, then
 5903: foreach line foreach problem in the picked sequence, an ssi request is
 5904: made that simulates a user submitting their selected letter(s) against
 5905: the homework problem.
 5906: 
 5907: =over 4
 5908: 
 5909: 
 5910: 
 5911: =item defaultFormData
 5912: 
 5913:   Returns html hidden inputs used to hold context/default values.
 5914: 
 5915:  Arguments:
 5916:   $symb - $symb of the current resource 
 5917: 
 5918: =cut
 5919: 
 5920: sub defaultFormData {
 5921:     my ($symb)=@_;
 5922:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5923: }
 5924: 
 5925: 
 5926: =pod 
 5927: 
 5928: =item getSequenceDropDown
 5929: 
 5930:    Return html dropdown of possible sequences to grade
 5931:  
 5932:  Arguments:
 5933:    $symb - $symb of the current resource
 5934:    $map_error - ref to scalar which will container error if
 5935:                 $navmap object is unavailable in &getSymbMap().
 5936: 
 5937: =cut
 5938: 
 5939: sub getSequenceDropDown {
 5940:     my ($symb,$map_error)=@_;
 5941:     my $result='<select name="selectpage">'."\n";
 5942:     my ($titles,$symbx) = &getSymbMap($map_error);
 5943:     if (ref($map_error)) {
 5944:         return if ($$map_error);
 5945:     }
 5946:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5947:     my $ctr=0;
 5948:     foreach (@$titles) {
 5949: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5950: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5951: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5952: 	    '>'.$showtitle.'</option>'."\n";
 5953: 	$ctr++;
 5954:     }
 5955:     $result.= '</select>';
 5956:     return $result;
 5957: }
 5958: 
 5959: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5960:                                    # key is zero-based index - 0, 1, 2 ...
 5961: 
 5962: my %first_bubble_line;             # First bubble line no. for each bubble.
 5963: 
 5964: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5965:                                    # matchresponse or rankresponse, where 
 5966:                                    # an individual response can have multiple 
 5967:                                    # lines
 5968: 
 5969: my %responsetype_per_response;     # responsetype for each response
 5970: 
 5971: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5972:                                    # numbered response. Needed when randomorder
 5973:                                    # or randompick are in use. Key is ID, value 
 5974:                                    # is response number.
 5975: 
 5976: # Save and restore the bubble lines array to the form env.
 5977: 
 5978: 
 5979: sub save_bubble_lines {
 5980:     foreach my $line (keys(%bubble_lines_per_response)) {
 5981: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5982: 	$env{"form.scantron.first_bubble_line.$line"} =
 5983: 	    $first_bubble_line{$line};
 5984:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5985:             $subdivided_bubble_lines{$line};
 5986:         $env{"form.scantron.responsetype.$line"} =
 5987:             $responsetype_per_response{$line};
 5988:     }
 5989:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5990:         my $line = $masterseq_id_responsenum{$resid};
 5991:         $env{"form.scantron.residpart.$line"} = $resid;
 5992:     }
 5993: }
 5994: 
 5995: 
 5996: sub restore_bubble_lines {
 5997:     my $line = 0;
 5998:     %bubble_lines_per_response = ();
 5999:     %masterseq_id_responsenum = ();
 6000:     while ($env{"form.scantron.bubblelines.$line"}) {
 6001: 	my $value = $env{"form.scantron.bubblelines.$line"};
 6002: 	$bubble_lines_per_response{$line} = $value;
 6003: 	$first_bubble_line{$line}  =
 6004: 	    $env{"form.scantron.first_bubble_line.$line"};
 6005:         $subdivided_bubble_lines{$line} =
 6006:             $env{"form.scantron.sub_bubblelines.$line"};
 6007:         $responsetype_per_response{$line} =
 6008:             $env{"form.scantron.responsetype.$line"};
 6009:         my $id = $env{"form.scantron.residpart.$line"};
 6010:         $masterseq_id_responsenum{$id} = $line;
 6011: 	$line++;
 6012:     }
 6013: }
 6014: 
 6015: =pod 
 6016: 
 6017: =item scantron_filenames
 6018: 
 6019:    Returns a list of the scantron files in the current course 
 6020: 
 6021: =cut
 6022: 
 6023: sub scantron_filenames {
 6024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6025:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6026:     my $getpropath = 1;
 6027:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6028:                                                         $cname,$getpropath);
 6029:     my @possiblenames;
 6030:     if (ref($dirlist) eq 'ARRAY') {
 6031:         foreach my $filename (sort(@{$dirlist})) {
 6032: 	    ($filename)=split(/&/,$filename);
 6033: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6034: 	    $filename=~s/^scantron_orig_//;
 6035: 	    push(@possiblenames,$filename);
 6036:         }
 6037:     }
 6038:     return @possiblenames;
 6039: }
 6040: 
 6041: =pod 
 6042: 
 6043: =item scantron_uploads
 6044: 
 6045:    Returns  html drop-down list of scantron files in current course.
 6046: 
 6047:  Arguments:
 6048:    $file2grade - filename to set as selected in the dropdown
 6049: 
 6050: =cut
 6051: 
 6052: sub scantron_uploads {
 6053:     my ($file2grade) = @_;
 6054:     my $result=	'<select name="scantron_selectfile">';
 6055:     $result.="<option></option>";
 6056:     foreach my $filename (sort(&scantron_filenames())) {
 6057: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6058:     }
 6059:     $result.="</select>";
 6060:     return $result;
 6061: }
 6062: 
 6063: =pod 
 6064: 
 6065: =item scantron_scantab
 6066: 
 6067:   Returns html drop down of the scantron formats in the scantronformat.tab
 6068:   file.
 6069: 
 6070: =cut
 6071: 
 6072: sub scantron_scantab {
 6073:     my $result='<select name="scantron_format">'."\n";
 6074:     $result.='<option></option>'."\n";
 6075:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6076:     if (@lines > 0) {
 6077:         foreach my $line (@lines) {
 6078:             next if (($line =~ /^\#/) || ($line eq ''));
 6079: 	    my ($name,$descrip)=split(/:/,$line);
 6080: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6081:         }
 6082:     }
 6083:     $result.='</select>'."\n";
 6084:     return $result;
 6085: }
 6086: 
 6087: =pod 
 6088: 
 6089: =item scantron_CODElist
 6090: 
 6091:   Returns html drop down of the saved CODE lists from current course,
 6092:   generated from earlier printings.
 6093: 
 6094: =cut
 6095: 
 6096: sub scantron_CODElist {
 6097:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6098:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6099:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6100:     my $namechoice='<option></option>';
 6101:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6102: 	if ($name =~ /^error: 2 /) { next; }
 6103: 	if ($name =~ /^type\0/) { next; }
 6104: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6105:     }
 6106:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6107:     return $namechoice;
 6108: }
 6109: 
 6110: =pod 
 6111: 
 6112: =item scantron_CODEunique
 6113: 
 6114:   Returns the html for "Each CODE to be used once" radio.
 6115: 
 6116: =cut
 6117: 
 6118: sub scantron_CODEunique {
 6119:     my $result='<span class="LC_nobreak">
 6120:                  <label><input type="radio" name="scantron_CODEunique"
 6121:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6122:                 </span>
 6123:                 <span class="LC_nobreak">
 6124:                  <label><input type="radio" name="scantron_CODEunique"
 6125:                         value="no" />'.&mt('No').' </label>
 6126:                 </span>';
 6127:     return $result;
 6128: }
 6129: 
 6130: =pod 
 6131: 
 6132: =item scantron_selectphase
 6133: 
 6134:   Generates the initial screen to start the bubblesheet process.
 6135:   Allows for - starting a grading run.
 6136:              - downloading existing scan data (original, corrected
 6137:                                                 or skipped info)
 6138: 
 6139:              - uploading new scan data
 6140: 
 6141:  Arguments:
 6142:   $r          - The Apache request object
 6143:   $file2grade - name of the file that contain the scanned data to score
 6144: 
 6145: =cut
 6146: 
 6147: sub scantron_selectphase {
 6148:     my ($r,$file2grade,$symb) = @_;
 6149:     if (!$symb) {return '';}
 6150:     my $map_error;
 6151:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6152:     if ($map_error) {
 6153:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6154:         return;
 6155:     }
 6156:     my $default_form_data=&defaultFormData($symb);
 6157:     my $file_selector=&scantron_uploads($file2grade);
 6158:     my $format_selector=&scantron_scantab();
 6159:     my $CODE_selector=&scantron_CODElist();
 6160:     my $CODE_unique=&scantron_CODEunique();
 6161:     my $result;
 6162: 
 6163:     $ssi_error = 0;
 6164: 
 6165:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6166: 
 6167: 	# Chunk of form to prompt for a scantron file upload.
 6168: 
 6169:         $r->print('
 6170:     <br />');
 6171:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6172:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6173:     my $csec= $env{'request.course.sec'};
 6174:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6175:     &js_escape(\$alertmsg);
 6176:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6177:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6178:     function checkUpload(formname) {
 6179: 	if (formname.upfile.value == "") {
 6180: 	    alert("'.$alertmsg.'");
 6181: 	    return false;
 6182: 	}
 6183: 	formname.submit();
 6184:     }'."\n".$formatjs));
 6185:     $r->print('
 6186:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6187:                 '.$default_form_data.'
 6188:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6189:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6190:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6191:                 <input name="command" value="scantronupload_save" type="hidden" />
 6192:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6193:               '.&Apache::loncommon::start_data_table_header_row().'
 6194:                 <th>
 6195:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6196:                 </th>
 6197:               '.&Apache::loncommon::end_data_table_header_row().'
 6198:               '.&Apache::loncommon::start_data_table_row().'
 6199:             <td>
 6200:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6201:     if ($formatoptions) {
 6202:         $r->print('</td>
 6203:                  '.&Apache::loncommon::end_data_table_row().'
 6204:                  '.&Apache::loncommon::start_data_table_row().'
 6205:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6206:                  </td>
 6207:                  '.&Apache::loncommon::end_data_table_row().'
 6208:                  '.&Apache::loncommon::start_data_table_row().'
 6209:                  <td>'
 6210:         );
 6211:     } else {
 6212:         $r->print(' <br />');
 6213:     }
 6214:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6215:               </td>
 6216:              '.&Apache::loncommon::end_data_table_row().'
 6217:              '.&Apache::loncommon::end_data_table().'
 6218:              </form>'
 6219:     );
 6220: 
 6221:     }
 6222: 
 6223:     # Chunk of form to prompt for a file to grade and how:
 6224: 
 6225:     $result.= '
 6226:     <br />
 6227:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6228:     <input type="hidden" name="command" value="scantron_warning" />
 6229:     '.$default_form_data.'
 6230:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6231:        '.&Apache::loncommon::start_data_table_header_row().'
 6232:             <th colspan="2">
 6233:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6234:             </th>
 6235:        '.&Apache::loncommon::end_data_table_header_row().'
 6236:        '.&Apache::loncommon::start_data_table_row().'
 6237:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6238:        '.&Apache::loncommon::end_data_table_row().'
 6239:        '.&Apache::loncommon::start_data_table_row().'
 6240:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6241:        '.&Apache::loncommon::end_data_table_row().'
 6242:        '.&Apache::loncommon::start_data_table_row().'
 6243:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6244:        '.&Apache::loncommon::end_data_table_row().'
 6245:        '.&Apache::loncommon::start_data_table_row().'
 6246:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6247:        '.&Apache::loncommon::end_data_table_row().'
 6248:        '.&Apache::loncommon::start_data_table_row().'
 6249:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6250:        '.&Apache::loncommon::end_data_table_row().'
 6251:        '.&Apache::loncommon::start_data_table_row().'
 6252: 	    <td> '.&mt('Options:').' </td>
 6253:             <td>
 6254: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6255:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6256:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6257: 	    </td>
 6258:        '.&Apache::loncommon::end_data_table_row().'
 6259:        '.&Apache::loncommon::start_data_table_row().'
 6260:             <td colspan="2">
 6261:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6262:             </td>
 6263:        '.&Apache::loncommon::end_data_table_row().'
 6264:     '.&Apache::loncommon::end_data_table().'
 6265:     </form>
 6266: ';
 6267:    
 6268:     $r->print($result);
 6269: 
 6270:     # Chunk of the form that prompts to view a scoring office file,
 6271:     # corrected file, skipped records in a file.
 6272: 
 6273:     $r->print('
 6274:    <br />
 6275:    <form action="/adm/grades" name="scantron_download">
 6276:      '.$default_form_data.'
 6277:      <input type="hidden" name="command" value="scantron_download" />
 6278:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6279:        '.&Apache::loncommon::start_data_table_header_row().'
 6280:               <th>
 6281:                 &nbsp;'.&mt('Download a scoring office file').'
 6282:               </th>
 6283:        '.&Apache::loncommon::end_data_table_header_row().'
 6284:        '.&Apache::loncommon::start_data_table_row().'
 6285:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6286:                 <br />
 6287:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6288:        '.&Apache::loncommon::end_data_table_row().'
 6289:      '.&Apache::loncommon::end_data_table().'
 6290:    </form>
 6291:    <br />
 6292: ');
 6293: 
 6294:     &Apache::lonpickcode::code_list($r,2);
 6295: 
 6296:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6297:              $default_form_data."\n".
 6298:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6299:              &Apache::loncommon::start_data_table_header_row()."\n".
 6300:              '<th colspan="2">
 6301:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6302:              '</th>'."\n".
 6303:               &Apache::loncommon::end_data_table_header_row()."\n".
 6304:               &Apache::loncommon::start_data_table_row()."\n".
 6305:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6306:               '<td> '.$sequence_selector.' </td>'.
 6307:               &Apache::loncommon::end_data_table_row()."\n".
 6308:               &Apache::loncommon::start_data_table_row()."\n".
 6309:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6310:               '<td> '.$file_selector.' </td>'."\n".
 6311:               &Apache::loncommon::end_data_table_row()."\n".
 6312:               &Apache::loncommon::start_data_table_row()."\n".
 6313:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6314:               '<td> '.$format_selector.' </td>'."\n".
 6315:               &Apache::loncommon::end_data_table_row()."\n".
 6316:               &Apache::loncommon::start_data_table_row()."\n".
 6317:               '<td> '.&mt('Options').' </td>'."\n".
 6318:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6319:               &Apache::loncommon::end_data_table_row()."\n".
 6320:               &Apache::loncommon::start_data_table_row()."\n".
 6321:               '<td colspan="2">'."\n".
 6322:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6323:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6324:               '</td>'."\n".
 6325:               &Apache::loncommon::end_data_table_row()."\n".
 6326:               &Apache::loncommon::end_data_table()."\n".
 6327:               '</form><br />');
 6328:     return;
 6329: }
 6330: 
 6331: =pod 
 6332: 
 6333: =item username_to_idmap
 6334: 
 6335:     creates a hash keyed by student/employee ID with values of the corresponding
 6336:     student username:domain. If a single ID occurs for more than one student,
 6337:     the status of the student is checked, and if Active, the value in the hash
 6338:     will be set to the Active student.
 6339: 
 6340:   Arguments:
 6341: 
 6342:     $classlist - reference to the class list hash. This is a hash
 6343:                  keyed by student name:domain  whose elements are references
 6344:                  to arrays containing various chunks of information
 6345:                  about the student. (See loncoursedata for more info).
 6346: 
 6347:   Returns
 6348:     %idmap - the constructed hash
 6349: 
 6350: =cut
 6351: 
 6352: sub username_to_idmap {
 6353:     my ($classlist)= @_;
 6354:     my %idmap;
 6355:     foreach my $student (keys(%$classlist)) {
 6356:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6357:         unless ($id eq '') {
 6358:             if (!exists($idmap{$id})) {
 6359:                 $idmap{$id} = $student;
 6360:             } else {
 6361:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6362:                 if ($status eq 'Active') {
 6363:                     $idmap{$id} = $student;
 6364:                 }
 6365:             }
 6366:         }
 6367:     }
 6368:     return %idmap;
 6369: }
 6370: 
 6371: =pod
 6372: 
 6373: =item scantron_fixup_scanline
 6374: 
 6375:    Process a requested correction to a scanline.
 6376: 
 6377:   Arguments:
 6378:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6379:     $scan_data         - hash of correction information 
 6380:                           (see &scantron_getfile())
 6381:     $line              - existing scanline
 6382:     $whichline         - line number of the passed in scanline
 6383:     $field             - type of change to process 
 6384:                          (either 
 6385:                           'ID'     -> correct the student/employee ID
 6386:                           'CODE'   -> correct the CODE
 6387:                           'answer' -> fixup the submitted answers)
 6388:     
 6389:    $args               - hash of additional info,
 6390:                           - 'ID' 
 6391:                                'newid' -> studentID to use in replacement
 6392:                                           of existing one
 6393:                           - 'CODE' 
 6394:                                'CODE_ignore_dup' - set to true if duplicates
 6395:                                                    should be ignored.
 6396: 	                       'CODE' - is new code or 'use_unfound'
 6397:                                         if the existing unfound code should
 6398:                                         be used as is
 6399:                           - 'answer'
 6400:                                'response' - new answer or 'none' if blank
 6401:                                'question' - the bubble line to change
 6402:                                'questionnum' - the question identifier,
 6403:                                                may include subquestion. 
 6404: 
 6405:   Returns:
 6406:     $line - the modified scanline
 6407: 
 6408:   Side effects: 
 6409:     $scan_data - may be updated
 6410: 
 6411: =cut
 6412: 
 6413: 
 6414: sub scantron_fixup_scanline {
 6415:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6416:     if ($field eq 'ID') {
 6417: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6418: 	    return ($line,1,'New value too large');
 6419: 	}
 6420: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6421: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6422: 				     $args->{'newid'});
 6423: 	}
 6424: 	substr($line,$$scantron_config{'IDstart'}-1,
 6425: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6426: 	if ($args->{'newid'}=~/^\s*$/) {
 6427: 	    &scan_data($scan_data,"$whichline.user",
 6428: 		       $args->{'username'}.':'.$args->{'domain'});
 6429: 	}
 6430:     } elsif ($field eq 'CODE') {
 6431: 	if ($args->{'CODE_ignore_dup'}) {
 6432: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6433: 	}
 6434: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6435: 	if ($args->{'CODE'} ne 'use_unfound') {
 6436: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6437: 		return ($line,1,'New CODE value too large');
 6438: 	    }
 6439: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6440: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6441: 	    }
 6442: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6443: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6444: 	}
 6445:     } elsif ($field eq 'answer') {
 6446: 	my $length=$scantron_config->{'Qlength'};
 6447: 	my $off=$scantron_config->{'Qoff'};
 6448: 	my $on=$scantron_config->{'Qon'};
 6449: 	my $answer=${off}x$length;
 6450: 	if ($args->{'response'} eq 'none') {
 6451: 	    &scan_data($scan_data,
 6452: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6453: 	} else {
 6454: 	    if ($on eq 'letter') {
 6455: 		my @alphabet=('A'..'Z');
 6456: 		$answer=$alphabet[$args->{'response'}];
 6457: 	    } elsif ($on eq 'number') {
 6458: 		$answer=$args->{'response'}+1;
 6459: 		if ($answer == 10) { $answer = '0'; }
 6460: 	    } else {
 6461: 		substr($answer,$args->{'response'},1)=$on;
 6462: 	    }
 6463: 	    &scan_data($scan_data,
 6464: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6465: 	}
 6466: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6467: 	substr($line,$where-1,$length)=$answer;
 6468:     }
 6469:     return $line;
 6470: }
 6471: 
 6472: =pod
 6473: 
 6474: =item scan_data
 6475: 
 6476:     Edit or look up  an item in the scan_data hash.
 6477: 
 6478:   Arguments:
 6479:     $scan_data  - The hash (see scantron_getfile)
 6480:     $key        - shorthand of the key to edit (actual key is
 6481:                   scantronfilename_key).
 6482:     $data        - New value of the hash entry.
 6483:     $delete      - If true, the entry is removed from the hash.
 6484: 
 6485:   Returns:
 6486:     The new value of the hash table field (undefined if deleted).
 6487: 
 6488: =cut
 6489: 
 6490: 
 6491: sub scan_data {
 6492:     my ($scan_data,$key,$value,$delete)=@_;
 6493:     my $filename=$env{'form.scantron_selectfile'};
 6494:     if (defined($value)) {
 6495: 	$scan_data->{$filename.'_'.$key} = $value;
 6496:     }
 6497:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6498:     return $scan_data->{$filename.'_'.$key};
 6499: }
 6500: 
 6501: # ----- These first few routines are general use routines.----
 6502: 
 6503: # Return the number of occurences of a pattern in a string.
 6504: 
 6505: sub occurence_count {
 6506:     my ($string, $pattern) = @_;
 6507: 
 6508:     my @matches = ($string =~ /$pattern/g);
 6509: 
 6510:     return scalar(@matches);
 6511: }
 6512: 
 6513: 
 6514: # Take a string known to have digits and convert all the
 6515: # digits into letters in the range J,A..I.
 6516: 
 6517: sub digits_to_letters {
 6518:     my ($input) = @_;
 6519: 
 6520:     my @alphabet = ('J', 'A'..'I');
 6521: 
 6522:     my @input    = split(//, $input);
 6523:     my $output ='';
 6524:     for (my $i = 0; $i < scalar(@input); $i++) {
 6525: 	if ($input[$i] =~ /\d/) {
 6526: 	    $output .= $alphabet[$input[$i]];
 6527: 	} else {
 6528: 	    $output .= $input[$i];
 6529: 	}
 6530:     }
 6531:     return $output;
 6532: }
 6533: 
 6534: =pod 
 6535: 
 6536: =item scantron_parse_scanline
 6537: 
 6538:   Decodes a scanline from the selected bubblesheet file
 6539: 
 6540:  Arguments:
 6541:     line             - The text of the bubblesheet file line to process
 6542:     whichline        - Line number
 6543:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6544:     scan_data        - Hash of extra information about the scanline
 6545:                        (see scantron_getfile for more information)
 6546:     just_header      - True if should not process question answers but only
 6547:                        the stuff to the left of the answers.
 6548:     randomorder      - True if randomorder in use
 6549:     randompick       - True if randompick in use
 6550:     sequence         - Exam folder URL
 6551:     master_seq       - Ref to array containing symbs in exam folder
 6552:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6553:                        (corresponding values are resource objects)
 6554:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6555:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6556:                        are refs to an array of resource objects, ordered
 6557:                        according to order used for CODE, when randomorder
 6558:                        and or randompick are in use.
 6559:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6560:                        for current line to question number used for same question
 6561:                         in "Master Sequence" (as seen by Course Coordinator).
 6562:     startline        - Ref to hash where key is question number (0 is first)
 6563:                        and value is number of first bubble line for current 
 6564:                        student or code-based randompick and/or randomorder.
 6565:     totalref         - Ref of scalar used to score total number of bubble
 6566:                        lines needed for responses in a scan line (used when
 6567:                        randompick in use. 
 6568:     
 6569:  Returns:
 6570:    Hash containing the result of parsing the scanline
 6571: 
 6572:    Keys are all proceeded by the string 'scantron.'
 6573: 
 6574:        CODE    - the CODE in use for this scanline
 6575:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6576:                  by the operator
 6577:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6578:                             CODEs were selected, but the usage has been
 6579:                             forced by the operator
 6580:        ID  - student/employee ID
 6581:        PaperID - if used, the ID number printed on the sheet when the 
 6582:                  paper was scanned
 6583:        FirstName - first name from the sheet
 6584:        LastName  - last name from the sheet
 6585: 
 6586:      if just_header was not true these key may also exist
 6587: 
 6588:        missingerror - a list of bubble ranges that are considered to be answers
 6589:                       to a single question that don't have any bubbles filled in.
 6590:                       Of the form questionnumber:firstbubblenumber:count.
 6591:        doubleerror  - a list of bubble ranges that are considered to be answers
 6592:                       to a single question that have more than one bubble filled in.
 6593:                       Of the form questionnumber::firstbubblenumber:count
 6594:    
 6595:                 In the above, count is the number of bubble responses in the
 6596:                 input line needed to represent the possible answers to the question.
 6597:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6598:                 per line would have count = 2.
 6599: 
 6600:        maxquest     - the number of the last bubble line that was parsed
 6601: 
 6602:        (<number> starts at 1)
 6603:        <number>.answer - zero or more letters representing the selected
 6604:                          letters from the scanline for the bubble line 
 6605:                          <number>.
 6606:                          if blank there was either no bubble or there where
 6607:                          multiple bubbles, (consult the keys missingerror and
 6608:                          doubleerror if this is an error condition)
 6609: 
 6610: =cut
 6611: 
 6612: sub scantron_parse_scanline {
 6613:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6614:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6615:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6616: 
 6617:     my %record;
 6618:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6619:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6620: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6621: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6622: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6623: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6624: 	    $record{'scantron.CODE'}=substr($data,
 6625: 					    $$scantron_config{'CODEstart'}-1,
 6626: 					    $$scantron_config{'CODElength'});
 6627: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6628: 		$record{'scantron.useCODE'}=1;
 6629: 	    }
 6630: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6631: 		$record{'scantron.CODE_ignore_dup'}=1;
 6632: 	    }
 6633: 	} else {
 6634: 	    #FIXME interpret first N questions
 6635: 	}
 6636:     }
 6637:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6638: 				  $$scantron_config{'IDlength'});
 6639:     $record{'scantron.PaperID'}=
 6640: 	substr($data,$$scantron_config{'PaperID'}-1,
 6641: 	       $$scantron_config{'PaperIDlength'});
 6642:     $record{'scantron.FirstName'}=
 6643: 	substr($data,$$scantron_config{'FirstName'}-1,
 6644: 	       $$scantron_config{'FirstNamelength'});
 6645:     $record{'scantron.LastName'}=
 6646: 	substr($data,$$scantron_config{'LastName'}-1,
 6647: 	       $$scantron_config{'LastNamelength'});
 6648:     if ($just_header) { return \%record; }
 6649: 
 6650:     my @alphabet=('A'..'Z');
 6651:     my $questnum=0;
 6652:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6653: 
 6654:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6655:     if ($randompick || $randomorder) {
 6656:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6657:                                          $master_seq,$symb_to_resource,
 6658:                                          $partids_by_symb,$orderedforcode,
 6659:                                          $respnumlookup,$startline);
 6660:         if ($total) {
 6661:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6662:         }
 6663:         if (ref($totalref)) {
 6664:             $$totalref = $total;
 6665:         }
 6666:     }
 6667:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6668:     chomp($questions);		# Get rid of any trailing \n.
 6669:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6670:     while (length($questions)) {
 6671:         my $answers_needed;
 6672:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6673:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6674:         } else {
 6675: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6676:         }
 6677:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6678:                              || 1;
 6679:         $questnum++;
 6680:         my $quest_id = $questnum;
 6681:         my $currentquest = substr($questions,0,$answer_length);
 6682:         $questions       = substr($questions,$answer_length);
 6683:         if (length($currentquest) < $answer_length) { next; }
 6684: 
 6685:         my $subdivided;
 6686:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6687:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6688:         } else {
 6689:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6690:         }
 6691:         if ($subdivided =~ /,/) {
 6692:             my $subquestnum = 1;
 6693:             my $subquestions = $currentquest;
 6694:             my @subanswers_needed = split(/,/,$subdivided);
 6695:             foreach my $subans (@subanswers_needed) {
 6696:                 my $subans_length =
 6697:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6698:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6699:                 $subquestions   = substr($subquestions,$subans_length);
 6700:                 $quest_id = "$questnum.$subquestnum";
 6701:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6702:                     ($$scantron_config{'Qon'} eq 'number')) {
 6703:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6704:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6705:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6706:                         $randomorder,$randompick,$respnumlookup);
 6707:                 } else {
 6708:                     $ansnum = &scantron_validator_positional($ansnum,
 6709:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6710:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6711:                         $randomorder,$randompick,$respnumlookup);
 6712:                 }
 6713:                 $subquestnum ++;
 6714:             }
 6715:         } else {
 6716:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6717:                 ($$scantron_config{'Qon'} eq 'number')) {
 6718:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6719:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6720:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6721:                     $randomorder,$randompick,$respnumlookup);
 6722:             } else {
 6723:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6724:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6725:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6726:                     $randomorder,$randompick,$respnumlookup);
 6727:             }
 6728:         }
 6729:     }
 6730:     $record{'scantron.maxquest'}=$questnum;
 6731:     return \%record;
 6732: }
 6733: 
 6734: sub get_master_seq {
 6735:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6736:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6737:                    (ref($symb_to_resource) eq 'HASH'));
 6738:     my $resource_error;
 6739:     foreach my $resource (@{$resources}) {
 6740:         my $ressymb;
 6741:         if (ref($resource)) {
 6742:             $ressymb = $resource->symb();
 6743:             push(@{$master_seq},$ressymb);
 6744:             $symb_to_resource->{$ressymb} = $resource;
 6745:         } else {
 6746:             $resource_error = 1;
 6747:             last;
 6748:         }
 6749:     }
 6750:     return $resource_error;
 6751: }
 6752: 
 6753: sub get_respnum_lookups {
 6754:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6755:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6756:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6757:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6758:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6759:                    (ref($startline) eq 'HASH'));
 6760:     my ($user,$scancode);
 6761:     if ((exists($record->{'scantron.CODE'})) &&
 6762:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6763:         $scancode = $record->{'scantron.CODE'};
 6764:     } else {
 6765:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6766:     }
 6767:     my @mapresources =
 6768:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6769:                      $orderedforcode);
 6770:     my $total = 0;
 6771:     my $count = 0;
 6772:     foreach my $resource (@mapresources) {
 6773:         my $id = $resource->id();
 6774:         my $symb = $resource->symb();
 6775:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6776:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6777:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6778:                 if ($respnum ne '') {
 6779:                     $respnumlookup->{$count} = $respnum;
 6780:                     $startline->{$count} = $total;
 6781:                     $total += $bubble_lines_per_response{$respnum};
 6782:                     $count ++;
 6783:                 }
 6784:             }
 6785:         }
 6786:     }
 6787:     return $total;
 6788: }
 6789: 
 6790: sub scantron_validator_lettnum {
 6791:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6792:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6793:         $randompick,$respnumlookup) = @_;
 6794: 
 6795:     # Qon 'letter' implies for each slot in currquest we have:
 6796:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6797:     #    about anything else (esp. a value of Qoff) for missing
 6798:     #    bubbles.
 6799:     #
 6800:     # Qon 'number' implies each slot gives a digit that indexes the
 6801:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6802:     #    and * or ? for double bubbles on a single line.
 6803:     #
 6804: 
 6805:     my $matchon;
 6806:     if ($$scantron_config{'Qon'} eq 'letter') {
 6807:         $matchon = '[A-Z]';
 6808:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6809:         $matchon = '\d';
 6810:     }
 6811:     my $occurrences = 0;
 6812:     my $responsenum = $questnum-1;
 6813:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6814:        $responsenum = $respnumlookup->{$questnum-1} 
 6815:     }
 6816:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6817:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6818:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6819:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6820:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6821:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6822:         my @singlelines = split('',$currquest);
 6823:         foreach my $entry (@singlelines) {
 6824:             $occurrences = &occurence_count($entry,$matchon);
 6825:             if ($occurrences > 1) {
 6826:                 last;
 6827:             }
 6828:         }
 6829:     } else {
 6830:         $occurrences = &occurence_count($currquest,$matchon); 
 6831:     }
 6832:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6833:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6834:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6835:             my $bubble = substr($currquest,$ans,1);
 6836:             if ($bubble =~ /$matchon/ ) {
 6837:                 if ($$scantron_config{'Qon'} eq 'number') {
 6838:                     if ($bubble == 0) {
 6839:                         $bubble = 10; 
 6840:                     }
 6841:                     $record->{"scantron.$ansnum.answer"} = 
 6842:                         $alphabet->[$bubble-1];
 6843:                 } else {
 6844:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6845:                 }
 6846:             } else {
 6847:                 $record->{"scantron.$ansnum.answer"}='';
 6848:             }
 6849:             $ansnum++;
 6850:         }
 6851:     } elsif (!defined($currquest)
 6852:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6853:             || (&occurence_count($currquest,$matchon) == 0)) {
 6854:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6855:             $record->{"scantron.$ansnum.answer"}='';
 6856:             $ansnum++;
 6857:         }
 6858:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6859:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6860:         }
 6861:     } else {
 6862:         if ($$scantron_config{'Qon'} eq 'number') {
 6863:             $currquest = &digits_to_letters($currquest);            
 6864:         }
 6865:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6866:             my $bubble = substr($currquest,$ans,1);
 6867:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6868:             $ansnum++;
 6869:         }
 6870:     }
 6871:     return $ansnum;
 6872: }
 6873: 
 6874: sub scantron_validator_positional {
 6875:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6876:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6877:         $randomorder,$randompick,$respnumlookup) = @_;
 6878: 
 6879:     # Otherwise there's a positional notation;
 6880:     # each bubble line requires Qlength items, and there are filled in
 6881:     # bubbles for each case where there 'Qon' characters.
 6882:     #
 6883: 
 6884:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6885: 
 6886:     # If the split only gives us one element.. the full length of the
 6887:     # answer string, no bubbles are filled in:
 6888: 
 6889:     if ($answers_needed eq '') {
 6890:         return;
 6891:     }
 6892: 
 6893:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6894:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6895:             $record->{"scantron.$ansnum.answer"}='';
 6896:             $ansnum++;
 6897:         }
 6898:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6899:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6900:         }
 6901:     } elsif (scalar(@array) == 2) {
 6902:         my $location = length($array[0]);
 6903:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6904:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6905:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6906:             if ($ans eq $line_num) {
 6907:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6908:             } else {
 6909:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6910:             }
 6911:             $ansnum++;
 6912:          }
 6913:     } else {
 6914:         #  If there's more than one instance of a bubble character
 6915:         #  That's a double bubble; with positional notation we can
 6916:         #  record all the bubbles filled in as well as the
 6917:         #  fact this response consists of multiple bubbles.
 6918:         #
 6919:         my $responsenum = $questnum-1;
 6920:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6921:             $responsenum = $respnumlookup->{$questnum-1}
 6922:         }
 6923:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6924:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6925:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6926:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6927:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6928:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6929:             my $doubleerror = 0;
 6930:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6931:                    (!$doubleerror)) {
 6932:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6933:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6934:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6935:                if (length(@currarray) > 2) {
 6936:                    $doubleerror = 1;
 6937:                } 
 6938:             }
 6939:             if ($doubleerror) {
 6940:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6941:             }
 6942:         } else {
 6943:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6944:         }
 6945:         my $item = $ansnum;
 6946:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6947:             $record->{"scantron.$item.answer"} = '';
 6948:             $item ++;
 6949:         }
 6950: 
 6951:         my @ans=@array;
 6952:         my $i=0;
 6953:         my $increment = 0;
 6954:         while ($#ans) {
 6955:             $i+=length($ans[0]) + $increment;
 6956:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6957:             my $bubble = $i%$$scantron_config{'Qlength'};
 6958:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6959:             shift(@ans);
 6960:             $increment = 1;
 6961:         }
 6962:         $ansnum += $answers_needed;
 6963:     }
 6964:     return $ansnum;
 6965: }
 6966: 
 6967: =pod
 6968: 
 6969: =item scantron_add_delay
 6970: 
 6971:    Adds an error message that occurred during the grading phase to a
 6972:    queue of messages to be shown after grading pass is complete
 6973: 
 6974:  Arguments:
 6975:    $delayqueue  - arrary ref of hash ref of error messages
 6976:    $scanline    - the scanline that caused the error
 6977:    $errormesage - the error message
 6978:    $errorcode   - a numeric code for the error
 6979: 
 6980:  Side Effects:
 6981:    updates the $delayqueue to have a new hash ref of the error
 6982: 
 6983: =cut
 6984: 
 6985: sub scantron_add_delay {
 6986:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6987:     push(@$delayqueue,
 6988: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6989: 	  'ecode' => $errorcode }
 6990: 	 );
 6991: }
 6992: 
 6993: =pod
 6994: 
 6995: =item scantron_find_student
 6996: 
 6997:    Finds the username for the current scanline
 6998: 
 6999:   Arguments:
 7000:    $scantron_record - hash result from scantron_parse_scanline
 7001:    $scan_data       - hash of correction information 
 7002:                       (see &scantron_getfile() form more information)
 7003:    $idmap           - hash from &username_to_idmap()
 7004:    $line            - number of current scanline
 7005:  
 7006:   Returns:
 7007:    Either 'username:domain' or undef if unknown
 7008: 
 7009: =cut
 7010: 
 7011: sub scantron_find_student {
 7012:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 7013:     my $scanID=$$scantron_record{'scantron.ID'};
 7014:     if ($scanID =~ /^\s*$/) {
 7015:  	return &scan_data($scan_data,"$line.user");
 7016:     }
 7017:     foreach my $id (keys(%$idmap)) {
 7018:  	if (lc($id) eq lc($scanID)) {
 7019:  	    return $$idmap{$id};
 7020:  	}
 7021:     }
 7022:     return undef;
 7023: }
 7024: 
 7025: =pod
 7026: 
 7027: =item scantron_filter
 7028: 
 7029:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7030:    hidden resources was selected
 7031: 
 7032: =cut
 7033: 
 7034: sub scantron_filter {
 7035:     my ($curres)=@_;
 7036: 
 7037:     if (ref($curres) && $curres->is_problem()) {
 7038: 	# if the user has asked to not have either hidden
 7039: 	# or 'randomout' controlled resources to be graded
 7040: 	# don't include them
 7041: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7042: 	    && $curres->randomout) {
 7043: 	    return 0;
 7044: 	}
 7045: 	return 1;
 7046:     }
 7047:     return 0;
 7048: }
 7049: 
 7050: =pod
 7051: 
 7052: =item scantron_process_corrections
 7053: 
 7054:    Gets correction information out of submitted form data and corrects
 7055:    the scanline
 7056: 
 7057: =cut
 7058: 
 7059: sub scantron_process_corrections {
 7060:     my ($r) = @_;
 7061:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7062:     my ($scanlines,$scan_data)=&scantron_getfile();
 7063:     my $classlist=&Apache::loncoursedata::get_classlist();
 7064:     my $which=$env{'form.scantron_line'};
 7065:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7066:     my ($skip,$err,$errmsg);
 7067:     if ($env{'form.scantron_skip_record'}) {
 7068: 	$skip=1;
 7069:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7070: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7071: 	    $env{'form.scantron_domain'};
 7072: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7073: 	($line,$err,$errmsg)=
 7074: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7075: 				     'ID',{'newid'=>$newid,
 7076: 				    'username'=>$env{'form.scantron_username'},
 7077: 				    'domain'=>$env{'form.scantron_domain'}});
 7078:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7079: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7080: 	my $newCODE;
 7081: 	my %args;
 7082: 	if      ($resolution eq 'use_unfound') {
 7083: 	    $newCODE='use_unfound';
 7084: 	} elsif ($resolution eq 'use_found') {
 7085: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7086: 	} elsif ($resolution eq 'use_typed') {
 7087: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7088: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7089: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7090: 	}
 7091: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7092: 	    $args{'CODE_ignore_dup'}=1;
 7093: 	}
 7094: 	$args{'CODE'}=$newCODE;
 7095: 	($line,$err,$errmsg)=
 7096: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7097: 				     'CODE',\%args);
 7098:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7099: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7100: 	    ($line,$err,$errmsg)=
 7101: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7102: 					 $which,'answer',
 7103: 					 { 'question'=>$question,
 7104: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7105:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7106: 	    if ($err) { last; }
 7107: 	}
 7108:     }
 7109:     if ($err) {
 7110:         $r->print(
 7111:             '<p class="LC_error">'
 7112:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7113:                 $errmsg)
 7114:            .'</p>');
 7115:     } else {
 7116: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7117: 	&scantron_putfile($scanlines,$scan_data);
 7118:     }
 7119: }
 7120: 
 7121: =pod
 7122: 
 7123: =item reset_skipping_status
 7124: 
 7125:    Forgets the current set of remember skipped scanlines (and thus
 7126:    reverts back to considering all lines in the
 7127:    scantron_skipped_<filename> file)
 7128: 
 7129: =cut
 7130: 
 7131: sub reset_skipping_status {
 7132:     my ($scanlines,$scan_data)=&scantron_getfile();
 7133:     &scan_data($scan_data,'remember_skipping',undef,1);
 7134:     &scantron_putfile(undef,$scan_data);
 7135: }
 7136: 
 7137: =pod
 7138: 
 7139: =item start_skipping
 7140: 
 7141:    Marks a scanline to be skipped. 
 7142: 
 7143: =cut
 7144: 
 7145: sub start_skipping {
 7146:     my ($scan_data,$i)=@_;
 7147:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7148:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7149: 	$remembered{$i}=2;
 7150:     } else {
 7151: 	$remembered{$i}=1;
 7152:     }
 7153:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7154: }
 7155: 
 7156: =pod
 7157: 
 7158: =item should_be_skipped
 7159: 
 7160:    Checks whether a scanline should be skipped.
 7161: 
 7162: =cut
 7163: 
 7164: sub should_be_skipped {
 7165:     my ($scanlines,$scan_data,$i)=@_;
 7166:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7167: 	# not redoing old skips
 7168: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7169: 	return 0;
 7170:     }
 7171:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7172: 
 7173:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7174: 	return 0;
 7175:     }
 7176:     return 1;
 7177: }
 7178: 
 7179: =pod
 7180: 
 7181: =item remember_current_skipped
 7182: 
 7183:    Discovers what scanlines are in the scantron_skipped_<filename>
 7184:    file and remembers them into scan_data for later use.
 7185: 
 7186: =cut
 7187: 
 7188: sub remember_current_skipped {
 7189:     my ($scanlines,$scan_data)=&scantron_getfile();
 7190:     my %to_remember;
 7191:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7192: 	if ($scanlines->{'skipped'}[$i]) {
 7193: 	    $to_remember{$i}=1;
 7194: 	}
 7195:     }
 7196: 
 7197:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7198:     &scantron_putfile(undef,$scan_data);
 7199: }
 7200: 
 7201: =pod
 7202: 
 7203: =item check_for_error
 7204: 
 7205:     Checks if there was an error when attempting to remove a specific
 7206:     scantron_.. bubblesheet data file. Prints out an error if
 7207:     something went wrong.
 7208: 
 7209: =cut
 7210: 
 7211: sub check_for_error {
 7212:     my ($r,$result)=@_;
 7213:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7214: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7215:     }
 7216: }
 7217: 
 7218: =pod
 7219: 
 7220: =item scantron_warning_screen
 7221: 
 7222:    Interstitial screen to make sure the operator has selected the
 7223:    correct options before we start the validation phase.
 7224: 
 7225: =cut
 7226: 
 7227: sub scantron_warning_screen {
 7228:     my ($button_text,$symb)=@_;
 7229:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7230:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7231:     my $CODElist;
 7232:     if ($scantron_config{'CODElocation'} &&
 7233: 	$scantron_config{'CODEstart'} &&
 7234: 	$scantron_config{'CODElength'}) {
 7235: 	$CODElist=$env{'form.scantron_CODElist'};
 7236: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7237: 	$CODElist=
 7238: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7239: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7240:     }
 7241:     my $lastbubblepoints;
 7242:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7243:         $lastbubblepoints =
 7244:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7245:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7246:     }
 7247:     return '
 7248: <p>
 7249: <span class="LC_warning">
 7250: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7251: </p>
 7252: <table>
 7253: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7254: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7255: '.$CODElist.$lastbubblepoints.'
 7256: </table>
 7257: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7258: '.&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>
 7259: ';
 7260: }
 7261: 
 7262: =pod
 7263: 
 7264: =item scantron_do_warning
 7265: 
 7266:    Check if the operator has picked something for all required
 7267:    fields. Error out if something is missing.
 7268: 
 7269: =cut
 7270: 
 7271: sub scantron_do_warning {
 7272:     my ($r,$symb)=@_;
 7273:     if (!$symb) {return '';}
 7274:     my $default_form_data=&defaultFormData($symb);
 7275:     $r->print(&scantron_form_start().$default_form_data);
 7276:     if ( $env{'form.selectpage'} eq '' ||
 7277: 	 $env{'form.scantron_selectfile'} eq '' ||
 7278: 	 $env{'form.scantron_format'} eq '' ) {
 7279: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7280: 	if ( $env{'form.selectpage'} eq '') {
 7281: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7282: 	} 
 7283: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7284: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7285: 	}
 7286: 	if ( $env{'form.scantron_format'} eq '') {
 7287: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7288: 	}
 7289:     } else {
 7290: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7291:         my ($checksec,@possibles) = &gradable_sections();
 7292:         my $gradesections;
 7293:         if ($checksec) {
 7294:             my $file=$env{'form.scantron_selectfile'};
 7295:             if (&valid_file($file)) {
 7296:                 my %bysec = &scantron_get_sections();
 7297:                 my $table;
 7298:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7299:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7300:                     $table = &Apache::loncommon::start_data_table()."\n".
 7301:                              &Apache::loncommon::start_data_table_header_row().
 7302:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7303:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7304:                     if ($bysec{'none'}) {
 7305:                         $table .= &Apache::loncommon::start_data_table_row().
 7306:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7307:                                   &Apache::loncommon::end_data_table_row()."\n";
 7308:                     }
 7309:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7310:                         next if ($sec eq 'none');
 7311:                         $table .= &Apache::loncommon::start_data_table_row().
 7312:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7313:                                   &Apache::loncommon::end_data_table_row()."\n";
 7314:                     }
 7315:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7316:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7317:                                       '<p>'.$table.'</p>';
 7318:                     if (@possibles) {
 7319:                         $gradesections .= '<p>'.
 7320:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7321:                                               scalar(@possibles)).'<br />'.
 7322:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7323:                                               '<i>'.$checksec.'</i>').' ';
 7324:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7325:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7326:                         }
 7327:                         $gradesections .= '</p>';
 7328:                     }
 7329:                 }
 7330:             } else {
 7331:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7332:             }
 7333:         }
 7334:         my $bubbledbyhand=&hand_bubble_option();
 7335: 	$r->print('
 7336: '.$warning.$gradesections.$bubbledbyhand.'
 7337: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7338: <input type="hidden" name="command" value="scantron_validate" />
 7339: ');
 7340:     }
 7341:     $r->print("</form><br />");
 7342:     return '';
 7343: }
 7344: 
 7345: =pod
 7346: 
 7347: =item scantron_form_start
 7348: 
 7349:     html hidden input for remembering all selected grading options
 7350: 
 7351: =cut
 7352: 
 7353: sub scantron_form_start {
 7354:     my ($max_bubble)=@_;
 7355:     my $result= <<SCANTRONFORM;
 7356: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7357:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7358:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7359:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7360:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7361:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7362:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7363:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7364:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7365:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7366: SCANTRONFORM
 7367: 
 7368:   my $line = 0;
 7369:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7370:        my $chunk =
 7371: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7372:        $chunk .=
 7373: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7374:        $chunk .= 
 7375:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7376:        $chunk .=
 7377:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7378:        $chunk .=
 7379:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7380:        $result .= $chunk;
 7381:        $line++;
 7382:     }
 7383:     return $result;
 7384: }
 7385: 
 7386: =pod
 7387: 
 7388: =item scantron_validate_file
 7389: 
 7390:     Dispatch routine for doing validation of a bubblesheet data file.
 7391: 
 7392:     Also processes any necessary information resets that need to
 7393:     occur before validation begins (ignore previous corrections,
 7394:     restarting the skipped records processing)
 7395: 
 7396: =cut
 7397: 
 7398: sub scantron_validate_file {
 7399:     my ($r,$symb) = @_;
 7400:     if (!$symb) {return '';}
 7401:     my $default_form_data=&defaultFormData($symb);
 7402:     
 7403:     # do the detection of only doing skipped records first before we delete
 7404:     # them when doing the corrections reset
 7405:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7406: 	&reset_skipping_status();
 7407:     }
 7408:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7409: 	&remember_current_skipped();
 7410: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7411:     }
 7412: 
 7413:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7414: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7415: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7416: 	&check_for_error($r,&scantron_remove_scan_data());
 7417: 	$env{'form.scantron_options_ignore'}='done';
 7418:     }
 7419: 
 7420:     if ($env{'form.scantron_corrections'}) {
 7421: 	&scantron_process_corrections($r);
 7422:     }
 7423: 
 7424:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7425:     my ($checksec,@gradable);
 7426:     if ($env{'request.course.sec'}) {
 7427:         ($checksec,my @possibles) = &gradable_sections();
 7428:         if ($checksec) {
 7429:             if (@possibles) {
 7430:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7431:                 if (@chosensecs) {
 7432:                     foreach my $sec (@chosensecs) {
 7433:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7434:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7435:                                 push(@gradable,$sec);
 7436:                             }
 7437:                         }
 7438:                     }
 7439:                 }
 7440:             }
 7441:             $r->print('<p><table>');
 7442:             if (@gradable) {
 7443:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7444:                 $r->print(
 7445:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7446:             } else {
 7447:                 $r->print(
 7448:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7449:             }
 7450:             $r->print('</table></p>');
 7451:         }
 7452:     }
 7453:     $r->rflush();
 7454: 
 7455:     #get the student pick code ready
 7456:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7457:     my $nav_error;
 7458:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7459:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7460:     if ($nav_error) {
 7461:         $r->print(&navmap_errormsg());
 7462:         return '';
 7463:     }
 7464:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7465:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7466:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7467:     }
 7468:     $r->print($result);
 7469:     
 7470:     my @validate_phases=( 'sequence',
 7471: 			  'ID',
 7472: 			  'CODE',
 7473: 			  'doublebubble',
 7474: 			  'missingbubbles');
 7475:     if (!$env{'form.validatepass'}) {
 7476: 	$env{'form.validatepass'} = 0;
 7477:     }
 7478:     my $currentphase=$env{'form.validatepass'};
 7479:     my %skipbysec=();
 7480: 
 7481:     my $stop=0;
 7482:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7483: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7484: 	$r->rflush();
 7485:      
 7486: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7487: 	{
 7488: 	    no strict 'refs';
 7489:             my @extras=();
 7490:             if ($validate_phases[$currentphase] eq 'ID') {
 7491:                 @extras = (\%skipbysec,$checksec,@gradable);
 7492:             }
 7493: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7494: 	}
 7495:     }
 7496:     if (!$stop) {
 7497: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7498:         my $secinfo;
 7499:         if (keys(%skipbysec) > 0) {
 7500:             my $seclist = '<ul>';
 7501:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7502:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7503:             }
 7504:             $seclist .= '</ul>';
 7505:             $secinfo = '<p class="LC_info">'.
 7506:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7507:                            $seclist).
 7508:                        '</p>';
 7509:         }
 7510: 	$r->print(&mt('Validation process complete.').'<br />'.
 7511:                   $secinfo.$warning.
 7512:                   &mt('Perform verification for each student after storage of submissions?').
 7513:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7514:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7515:                   ('&nbsp;'x3).'<label>'.
 7516:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7517:                   '</label></span><br />'.
 7518:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7519:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7520:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7521:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7522:     } else {
 7523: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7524: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7525:     }
 7526:     if ($stop) {
 7527: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7528: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7529: 	    $r->print(' '.&mt('this error').' <br />');
 7530: 
 7531: 	    $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>');
 7532: 	} else {
 7533:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7534: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7535:             } else {
 7536:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7537:             }
 7538: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7539: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7540: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7541: 	}
 7542:     }
 7543:     $r->print(" </form><br />");
 7544:     return '';
 7545: }
 7546: 
 7547: 
 7548: =pod
 7549: 
 7550: =item scantron_remove_file
 7551: 
 7552:    Removes the requested bubblesheet data file, makes sure that
 7553:    scantron_original_<filename> is never removed
 7554: 
 7555: 
 7556: =cut
 7557: 
 7558: sub scantron_remove_file {
 7559:     my ($which)=@_;
 7560:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7561:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7562:     my $file='scantron_';
 7563:     if ($which eq 'corrected' || $which eq 'skipped') {
 7564: 	$file.=$which.'_';
 7565:     } else {
 7566: 	return 'refused';
 7567:     }
 7568:     $file.=$env{'form.scantron_selectfile'};
 7569:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7570: }
 7571: 
 7572: 
 7573: =pod
 7574: 
 7575: =item scantron_remove_scan_data
 7576: 
 7577:    Removes all scan_data correction for the requested bubblesheet
 7578:    data file.  (In the case that both the are doing skipped records we need
 7579:    to remember the old skipped lines for the time being so that element
 7580:    persists for a while.)
 7581: 
 7582: =cut
 7583: 
 7584: sub scantron_remove_scan_data {
 7585:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7586:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7587:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7588:     my @todelete;
 7589:     my $filename=$env{'form.scantron_selectfile'};
 7590:     foreach my $key (@keys) {
 7591: 	if ($key=~/^\Q$filename\E_/) {
 7592: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7593: 		$key=~/remember_skipping/) {
 7594: 		next;
 7595: 	    }
 7596: 	    push(@todelete,$key);
 7597: 	}
 7598:     }
 7599:     my $result;
 7600:     if (@todelete) {
 7601: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7602: 				       \@todelete,$cdom,$cname);
 7603:     } else {
 7604: 	$result = 'ok';
 7605:     }
 7606:     return $result;
 7607: }
 7608: 
 7609: 
 7610: =pod
 7611: 
 7612: =item scantron_getfile
 7613: 
 7614:     Fetches the requested bubblesheet data file (all 3 versions), and
 7615:     the scan_data hash
 7616:   
 7617:   Arguments:
 7618:     None
 7619: 
 7620:   Returns:
 7621:     2 hash references
 7622: 
 7623:      - first one has 
 7624:          orig      -
 7625:          corrected -
 7626:          skipped   -  each of which points to an array ref of the specified
 7627:                       file broken up into individual lines
 7628:          count     - number of scanlines
 7629:  
 7630:      - second is the scan_data hash possible keys are
 7631:        ($number refers to scanline numbered $number and thus the key affects
 7632:         only that scanline
 7633:         $bubline refers to the specific bubble line element and the aspects
 7634:         refers to that specific bubble line element)
 7635: 
 7636:        $number.user - username:domain to use
 7637:        $number.CODE_ignore_dup 
 7638:                     - ignore the duplicate CODE error 
 7639:        $number.useCODE
 7640:                     - use the CODE in the scanline as is
 7641:        $number.no_bubble.$bubline
 7642:                     - it is valid that there is no bubbled in bubble
 7643:                       at $number $bubline
 7644:        remember_skipping
 7645:                     - a frozen hash containing keys of $number and values
 7646:                       of either 
 7647:                         1 - we are on a 'do skipped records pass' and plan
 7648:                             on processing this line
 7649:                         2 - we are on a 'do skipped records pass' and this
 7650:                             scanline has been marked to skip yet again
 7651: 
 7652: =cut
 7653: 
 7654: sub scantron_getfile {
 7655:     #FIXME really would prefer a scantron directory
 7656:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7658:     my $lines;
 7659:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7660: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7661:     my %scanlines;
 7662:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7663:     my $temp=$scanlines{'orig'};
 7664:     $scanlines{'count'}=$#$temp;
 7665: 
 7666:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7667: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7668:     if ($lines eq '-1') {
 7669: 	$scanlines{'corrected'}=[];
 7670:     } else {
 7671: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7672:     }
 7673:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7674: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7675:     if ($lines eq '-1') {
 7676: 	$scanlines{'skipped'}=[];
 7677:     } else {
 7678: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7679:     }
 7680:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7681:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7682:     my %scan_data = @tmp;
 7683:     return (\%scanlines,\%scan_data);
 7684: }
 7685: 
 7686: =pod
 7687: 
 7688: =item lonnet_putfile
 7689: 
 7690:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7691: 
 7692:  Arguments:
 7693:    $contents - data to store
 7694:    $filename - filename to store $contents into
 7695: 
 7696:  Returns:
 7697:    result value from &Apache::lonnet::finishuserfileupload
 7698: 
 7699: =cut
 7700: 
 7701: sub lonnet_putfile {
 7702:     my ($contents,$filename)=@_;
 7703:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7704:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7705:     $env{'form.sillywaytopassafilearound'}=$contents;
 7706:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7707: 
 7708: }
 7709: 
 7710: =pod
 7711: 
 7712: =item scantron_putfile
 7713: 
 7714:     Stores the current version of the bubblesheet data files, and the
 7715:     scan_data hash. (Does not modify the original version only the
 7716:     corrected and skipped versions.
 7717: 
 7718:  Arguments:
 7719:     $scanlines - hash ref that looks like the first return value from
 7720:                  &scantron_getfile()
 7721:     $scan_data - hash ref that looks like the second return value from
 7722:                  &scantron_getfile()
 7723: 
 7724: =cut
 7725: 
 7726: sub scantron_putfile {
 7727:     my ($scanlines,$scan_data) = @_;
 7728:     #FIXME really would prefer a scantron directory
 7729:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7730:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7731:     if ($scanlines) {
 7732: 	my $prefix='scantron_';
 7733: # no need to update orig, shouldn't change
 7734: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7735: #		    $env{'form.scantron_selectfile'});
 7736: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7737: 			$prefix.'corrected_'.
 7738: 			$env{'form.scantron_selectfile'});
 7739: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7740: 			$prefix.'skipped_'.
 7741: 			$env{'form.scantron_selectfile'});
 7742:     }
 7743:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7744: }
 7745: 
 7746: =pod
 7747: 
 7748: =item scantron_get_line
 7749: 
 7750:    Returns the correct version of the scanline
 7751: 
 7752:  Arguments:
 7753:     $scanlines - hash ref that looks like the first return value from
 7754:                  &scantron_getfile()
 7755:     $scan_data - hash ref that looks like the second return value from
 7756:                  &scantron_getfile()
 7757:     $i         - number of the requested line (starts at 0)
 7758: 
 7759:  Returns:
 7760:    A scanline, (either the original or the corrected one if it
 7761:    exists), or undef if the requested scanline should be
 7762:    skipped. (Either because it's an skipped scanline, or it's an
 7763:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7764:    pass.
 7765: 
 7766: =cut
 7767: 
 7768: sub scantron_get_line {
 7769:     my ($scanlines,$scan_data,$i)=@_;
 7770:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7771:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7772:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7773:     return $scanlines->{'orig'}[$i]; 
 7774: }
 7775: 
 7776: =pod
 7777: 
 7778: =item scantron_todo_count
 7779: 
 7780:     Counts the number of scanlines that need processing.
 7781: 
 7782:  Arguments:
 7783:     $scanlines - hash ref that looks like the first return value from
 7784:                  &scantron_getfile()
 7785:     $scan_data - hash ref that looks like the second return value from
 7786:                  &scantron_getfile()
 7787: 
 7788:  Returns:
 7789:     $count - number of scanlines to process
 7790: 
 7791: =cut
 7792: 
 7793: sub get_todo_count {
 7794:     my ($scanlines,$scan_data)=@_;
 7795:     my $count=0;
 7796:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7797: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7798: 	if ($line=~/^[\s\cz]*$/) { next; }
 7799: 	$count++;
 7800:     }
 7801:     return $count;
 7802: }
 7803: 
 7804: =pod
 7805: 
 7806: =item scantron_put_line
 7807: 
 7808:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7809:     data file.
 7810: 
 7811:  Arguments:
 7812:     $scanlines - hash ref that looks like the first return value from
 7813:                  &scantron_getfile()
 7814:     $scan_data - hash ref that looks like the second return value from
 7815:                  &scantron_getfile()
 7816:     $i         - line number to update
 7817:     $newline   - contents of the updated scanline
 7818:     $skip      - if true make the line for skipping and update the
 7819:                  'skipped' file
 7820: 
 7821: =cut
 7822: 
 7823: sub scantron_put_line {
 7824:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7825:     if ($skip) {
 7826: 	$scanlines->{'skipped'}[$i]=$newline;
 7827: 	&start_skipping($scan_data,$i);
 7828: 	return;
 7829:     }
 7830:     $scanlines->{'corrected'}[$i]=$newline;
 7831: }
 7832: 
 7833: =pod
 7834: 
 7835: =item scantron_clear_skip
 7836: 
 7837:    Remove a line from the 'skipped' file
 7838: 
 7839:  Arguments:
 7840:     $scanlines - hash ref that looks like the first return value from
 7841:                  &scantron_getfile()
 7842:     $scan_data - hash ref that looks like the second return value from
 7843:                  &scantron_getfile()
 7844:     $i         - line number to update
 7845: 
 7846: =cut
 7847: 
 7848: sub scantron_clear_skip {
 7849:     my ($scanlines,$scan_data,$i)=@_;
 7850:     if (exists($scanlines->{'skipped'}[$i])) {
 7851: 	undef($scanlines->{'skipped'}[$i]);
 7852: 	return 1;
 7853:     }
 7854:     return 0;
 7855: }
 7856: 
 7857: =pod
 7858: 
 7859: =item scantron_filter_not_exam
 7860: 
 7861:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7862:    filter out resources that are not marked as 'exam' mode
 7863: 
 7864: =cut
 7865: 
 7866: sub scantron_filter_not_exam {
 7867:     my ($curres)=@_;
 7868:     
 7869:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7870: 	# if the user has asked to not have either hidden
 7871: 	# or 'randomout' controlled resources to be graded
 7872: 	# don't include them
 7873: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7874: 	    && $curres->randomout) {
 7875: 	    return 0;
 7876: 	}
 7877: 	return 1;
 7878:     }
 7879:     return 0;
 7880: }
 7881: 
 7882: =pod
 7883: 
 7884: =item scantron_validate_sequence
 7885: 
 7886:     Validates the selected sequence, checking for resource that are
 7887:     not set to exam mode.
 7888: 
 7889: =cut
 7890: 
 7891: sub scantron_validate_sequence {
 7892:     my ($r,$currentphase) = @_;
 7893: 
 7894:     my $navmap=Apache::lonnavmaps::navmap->new();
 7895:     unless (ref($navmap)) {
 7896:         $r->print(&navmap_errormsg());
 7897:         return (1,$currentphase);
 7898:     }
 7899:     my (undef,undef,$sequence)=
 7900: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7901: 
 7902:     my $map=$navmap->getResourceByUrl($sequence);
 7903: 
 7904:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7905:                                     value="ignore" />');
 7906:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7907: 	my @resources=
 7908: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7909: 	if (@resources) {
 7910: 	    $r->print(
 7911:                 '<p class="LC_warning">'
 7912:                .&mt('Some resources in the sequence currently are not set to'
 7913:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7914:                    .' work correctly.')
 7915:                .'</p>'
 7916:             );
 7917: 	    return (1,$currentphase);
 7918: 	}
 7919:     }
 7920: 
 7921:     return (0,$currentphase+1);
 7922: }
 7923: 
 7924: 
 7925: 
 7926: sub scantron_validate_ID {
 7927:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7928:     
 7929:     #get student info
 7930:     my $classlist=&Apache::loncoursedata::get_classlist();
 7931:     my %idmap=&username_to_idmap($classlist);
 7932:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7933: 
 7934:     #get scantron line setup
 7935:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7936:     my ($scanlines,$scan_data)=&scantron_getfile();
 7937: 
 7938:     my $nav_error;
 7939:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7940:     if ($nav_error) {
 7941:         $r->print(&navmap_errormsg());
 7942:         return(1,$currentphase);
 7943:     }
 7944: 
 7945:     my %found=('ids'=>{},'usernames'=>{});
 7946:     my $unsavedskips = 0;
 7947:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7948: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7949: 	if ($line=~/^[\s\cz]*$/) { next; }
 7950: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7951: 						 $scan_data);
 7952: 	my $id=$$scan_record{'scantron.ID'};
 7953: 	my $found;
 7954: 	foreach my $checkid (keys(%idmap)) {
 7955: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7956: 	}
 7957: 	if ($found) {
 7958: 	    my $username=$idmap{$found};
 7959:             if ($checksec) {
 7960:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7961:                     my $stusec = $classlist->{$username}->[$secidx];
 7962:                     if ($stusec ne $checksec) {
 7963:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7964:                             my $skip=1;
 7965:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7966:                             if (ref($skipbysec) eq 'HASH') {
 7967:                                 if ($stusec eq '') {
 7968:                                     $skipbysec->{'none'} ++;
 7969:                                 } else {
 7970:                                     $skipbysec->{$stusec} ++;
 7971:                                 }
 7972:                             }
 7973:                             $unsavedskips ++;
 7974:                             next;
 7975:                         }
 7976:                     }
 7977:                 }
 7978:             }
 7979: 	    if ($found{'ids'}{$found}) {
 7980: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7981: 					 $line,'duplicateID',$found);
 7982:                 if ($unsavedskips) {
 7983:                     &scantron_putfile($scanlines,$scan_data);
 7984:                     $unsavedskips = 0;
 7985:                 }
 7986: 		return(1,$currentphase);
 7987: 	    } elsif ($found{'usernames'}{$username}) {
 7988: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7989: 					 $line,'duplicateID',$username);
 7990:                 if ($unsavedskips) {
 7991:                     &scantron_putfile($scanlines,$scan_data);
 7992:                     $unsavedskips = 0;
 7993:                 }
 7994: 		return(1,$currentphase);
 7995: 	    }
 7996: 	    #FIXME store away line we previously saw the ID on to use above
 7997: 	    $found{'ids'}{$found}++;
 7998: 	    $found{'usernames'}{$username}++;
 7999: 	} else {
 8000: 	    if ($id =~ /^\s*$/) {
 8001: 		my $username=&scan_data($scan_data,"$i.user");
 8002:                 if (($checksec && $username ne '')) {
 8003:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 8004:                         my $stusec = $classlist->{$username}->[$secidx];
 8005:                         if ($stusec ne $checksec) {
 8006:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 8007:                                 my $skip=1;
 8008:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 8009:                                 if (ref($skipbysec) eq 'HASH') {
 8010:                                     if ($stusec eq '') {
 8011:                                         $skipbysec->{'none'} ++;
 8012:                                     } else {
 8013:                                         $skipbysec->{$stusec} ++;
 8014:                                     }
 8015:                                 }
 8016:                                 $unsavedskips ++;
 8017:                                 next;
 8018:                             }
 8019:                         }
 8020:                     }
 8021: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 8022: 		    &scantron_get_correction($r,$i,$scan_record,
 8023: 					     \%scantron_config,
 8024: 					     $line,'duplicateID',$username);
 8025:                     if ($unsavedskips) {
 8026:                         &scantron_putfile($scanlines,$scan_data);
 8027:                         $unsavedskips = 0;
 8028:                     }
 8029: 		    return(1,$currentphase);
 8030: 		} elsif (!defined($username)) {
 8031: 		    &scantron_get_correction($r,$i,$scan_record,
 8032: 					     \%scantron_config,
 8033: 					     $line,'incorrectID');
 8034:                     if ($unsavedskips) {
 8035:                         &scantron_putfile($scanlines,$scan_data);
 8036:                         $unsavedskips = 0;
 8037:                     }
 8038: 		    return(1,$currentphase);
 8039: 		}
 8040: 		$found{'usernames'}{$username}++;
 8041: 	    } else {
 8042: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8043: 					 $line,'incorrectID');
 8044:                 if ($unsavedskips) {
 8045:                     &scantron_putfile($scanlines,$scan_data);
 8046:                     $unsavedskips = 0;
 8047:                 }
 8048: 		return(1,$currentphase);
 8049: 	    }
 8050: 	}
 8051:     }
 8052:     if ($unsavedskips) {
 8053:         &scantron_putfile($scanlines,$scan_data);
 8054:         $unsavedskips = 0;
 8055:     }
 8056:     return (0,$currentphase+1);
 8057: }
 8058: 
 8059: sub scantron_get_sections {
 8060:     my %bysec;
 8061:     if ($env{'form.scantron_format'} ne '') {
 8062:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8063:         my ($scanlines,$scan_data)=&scantron_getfile();
 8064:         my $classlist=&Apache::loncoursedata::get_classlist();
 8065:         my %idmap=&username_to_idmap($classlist);
 8066:         foreach my $key (keys(%idmap)) {
 8067:             my $lckey = lc($key);
 8068:             $idmap{$lckey} = $idmap{$key};
 8069:         }
 8070:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 8071:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8072:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8073:             if ($line=~/^[\s\cz]*$/) { next; }
 8074:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8075:                                                      $scan_data);
 8076:             my $id=lc($$scan_record{'scantron.ID'});
 8077:             if (exists($idmap{$id})) {
 8078:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 8079:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 8080:                     if ($stusec eq '') {
 8081:                         $bysec{'none'} ++;
 8082:                     } else {
 8083:                         $bysec{$stusec} ++;
 8084:                     }
 8085:                 }
 8086:             }
 8087:         }
 8088:     }
 8089:     return %bysec;
 8090: }
 8091: 
 8092: sub scantron_get_correction {
 8093:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 8094:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 8095: #FIXME in the case of a duplicated ID the previous line, probably need
 8096: #to show both the current line and the previous one and allow skipping
 8097: #the previous one or the current one
 8098: 
 8099:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8100:         $r->print(
 8101:             '<p class="LC_warning">'
 8102:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8103:                 "<b>$error</b>",
 8104:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8105:            ."</p> \n");
 8106:     } else {
 8107:         $r->print(
 8108:             '<p class="LC_warning">'
 8109:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8110:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8111:            ."</p> \n");
 8112:     }
 8113:     my $message =
 8114:         '<p>'
 8115:        .&mt('The ID on the form is [_1]',
 8116:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8117:        .'<br />'
 8118:        .&mt('The name on the paper is [_1], [_2]',
 8119:             $$scan_record{'scantron.LastName'},
 8120:             $$scan_record{'scantron.FirstName'})
 8121:        .'</p>';
 8122: 
 8123:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8124:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8125:                            # Array populated for doublebubble or
 8126:     my @lines_to_correct;  # missingbubble errors to build javascript
 8127:                            # to validate radio button checking   
 8128: 
 8129:     if ($error =~ /ID$/) {
 8130: 	if ($error eq 'incorrectID') {
 8131:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8132: 		      "</p>\n");
 8133: 	} elsif ($error eq 'duplicateID') {
 8134:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8135: 	}
 8136: 	$r->print($message);
 8137: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8138: 	$r->print("\n<ul><li> ");
 8139: 	#FIXME it would be nice if this sent back the user ID and
 8140: 	#could do partial userID matches
 8141: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8142: 				       'scantron_username','scantron_domain'));
 8143: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8144: 	$r->print("\n:\n".
 8145: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8146: 
 8147: 	$r->print('</li>');
 8148:     } elsif ($error =~ /CODE$/) {
 8149: 	if ($error eq 'incorrectCODE') {
 8150: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8151: 	} elsif ($error eq 'duplicateCODE') {
 8152: 	    $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");
 8153: 	}
 8154: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8155: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8156:                  ."</p>\n");
 8157: 	$r->print($message);
 8158: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8159: 	$r->print("\n<br /> ");
 8160: 	my $i=0;
 8161: 	if ($error eq 'incorrectCODE' 
 8162: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8163: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8164: 	    if ($closest > 0) {
 8165: 		foreach my $testcode (@{$closest}) {
 8166: 		    my $checked='';
 8167: 		    if (!$i) { $checked=' checked="checked"'; }
 8168: 		    $r->print("
 8169:    <label>
 8170:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8171:        ".&mt("Use the similar CODE [_1] instead.",
 8172: 	    "<b><tt>".$testcode."</tt></b>")."
 8173:     </label>
 8174:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8175: 		    $r->print("\n<br />");
 8176: 		    $i++;
 8177: 		}
 8178: 	    }
 8179: 	}
 8180: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8181: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8182: 	    $r->print("
 8183:     <label>
 8184:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8185:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8186: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8187:     </label>");
 8188: 	    $r->print("\n<br />");
 8189: 	}
 8190: 
 8191: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8192: function change_radio(field) {
 8193:     var slct=document.scantronupload.scantron_CODE_resolution;
 8194:     var i;
 8195:     for (i=0;i<slct.length;i++) {
 8196:         if (slct[i].value==field) { slct[i].checked=true; }
 8197:     }
 8198: }
 8199: ENDSCRIPT
 8200: 	my $href="/adm/pickcode?".
 8201: 	   "form=".&escape("scantronupload").
 8202: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8203: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8204: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8205: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8206: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8207: 	    $r->print("
 8208:     <label>
 8209:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8210:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8211: 	     "<a target='_blank' href='$href'>","</a>")."
 8212:     </label> 
 8213:     ".&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\')" />'));
 8214: 	    $r->print("\n<br />");
 8215: 	}
 8216: 	$r->print("
 8217:     <label>
 8218:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8219:        ".&mt("Use [_1] as the CODE.",
 8220: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8221: 	$r->print("\n<br /><br />");
 8222:     } elsif ($error eq 'doublebubble') {
 8223: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8224: 
 8225: 	# The form field scantron_questions is acutally a list of line numbers.
 8226: 	# represented by this form so:
 8227: 
 8228: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8229:                                                 $respnumlookup,$startline);
 8230: 
 8231: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8232: 		  $line_list.'" />');
 8233: 	$r->print($message);
 8234: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8235: 	foreach my $question (@{$arg}) {
 8236: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8237:                                                    $scan_record, $error,
 8238:                                                    $randomorder,$randompick,
 8239:                                                    $respnumlookup,$startline);
 8240:             push(@lines_to_correct,@linenums);
 8241: 	}
 8242:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8243:     } elsif ($error eq 'missingbubble') {
 8244: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8245: 	$r->print($message);
 8246: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8247: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8248: 
 8249: 	# The form field scantron_questions is actually a list of line numbers not
 8250: 	# a list of question numbers. Therefore:
 8251: 	#
 8252: 
 8253: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8254:                                                 $respnumlookup,$startline);
 8255: 
 8256: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8257: 		  $line_list.'" />');
 8258: 	foreach my $question (@{$arg}) {
 8259: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8260:                                                    $scan_record, $error,
 8261:                                                    $randomorder,$randompick,
 8262:                                                    $respnumlookup,$startline);
 8263:             push(@lines_to_correct,@linenums);
 8264: 	}
 8265:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8266:     } else {
 8267: 	$r->print("\n<ul>");
 8268:     }
 8269:     $r->print("\n</li></ul>");
 8270: }
 8271: 
 8272: sub verify_bubbles_checked {
 8273:     my (@ansnums) = @_;
 8274:     my $ansnumstr = join('","',@ansnums);
 8275:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8276:     &js_escape(\$warning);
 8277:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8278: function verify_bubble_radio(form) {
 8279:     var ansnumArray = new Array ("$ansnumstr");
 8280:     var need_bubble_count = 0;
 8281:     for (var i=0; i<ansnumArray.length; i++) {
 8282:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8283:             var bubble_picked = 0; 
 8284:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8285:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8286:                     bubble_picked = 1;
 8287:                 }
 8288:             }
 8289:             if (bubble_picked == 0) {
 8290:                 need_bubble_count ++;
 8291:             }
 8292:         }
 8293:     }
 8294:     if (need_bubble_count) {
 8295:         alert("$warning");
 8296:         return;
 8297:     }
 8298:     form.submit(); 
 8299: }
 8300: ENDSCRIPT
 8301:     return $output;
 8302: }
 8303: 
 8304: =pod
 8305: 
 8306: =item  questions_to_line_list
 8307: 
 8308: Converts a list of questions into a string of comma separated
 8309: line numbers in the answer sheet used by the questions.  This is
 8310: used to fill in the scantron_questions form field.
 8311: 
 8312:   Arguments:
 8313:      questions    - Reference to an array of questions.
 8314:      randomorder  - True if randomorder in use.
 8315:      randompick   - True if randompick in use.
 8316:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8317:                      for current line to question number used for same question
 8318:                      in "Master Seqence" (as seen by Course Coordinator).
 8319:      startline    - Reference to hash where key is question number (0 is first)
 8320:                     and key is number of first bubble line for current student
 8321:                     or code-based randompick and/or randomorder.
 8322: 
 8323: =cut
 8324: 
 8325: 
 8326: sub questions_to_line_list {
 8327:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8328:     my @lines;
 8329: 
 8330:     foreach my $item (@{$questions}) {
 8331:         my $question = $item;
 8332:         my ($first,$count,$last);
 8333:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8334:             $question = $1;
 8335:             my $subquestion = $2;
 8336:             my $responsenum = $question-1;
 8337:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8338:                 $responsenum = $respnumlookup->{$question-1};
 8339:                 if (ref($startline) eq 'HASH') {
 8340:                     $first = $startline->{$question-1} + 1;
 8341:                 }
 8342:             } else {
 8343:                 $first = $first_bubble_line{$responsenum} + 1;
 8344:             }
 8345:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8346:             my $subcount = 1;
 8347:             while ($subcount<$subquestion) {
 8348:                 $first += $subans[$subcount-1];
 8349:                 $subcount ++;
 8350:             }
 8351:             $count = $subans[$subquestion-1];
 8352:         } else {
 8353:             my $responsenum = $question-1;
 8354:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8355:                 $responsenum = $respnumlookup->{$question-1};
 8356:                 if (ref($startline) eq 'HASH') {
 8357:                     $first = $startline->{$question-1} + 1;
 8358:                 }
 8359:             } else {
 8360:                 $first = $first_bubble_line{$responsenum} + 1;
 8361:             }
 8362: 	    $count   = $bubble_lines_per_response{$responsenum};
 8363:         }
 8364:         $last = $first+$count-1;
 8365:         push(@lines, ($first..$last));
 8366:     }
 8367:     return join(',', @lines);
 8368: }
 8369: 
 8370: =pod 
 8371: 
 8372: =item prompt_for_corrections
 8373: 
 8374: Prompts for a potentially multiline correction to the
 8375: user's bubbling (factors out common code from scantron_get_correction
 8376: for multi and missing bubble cases).
 8377: 
 8378:  Arguments:
 8379:    $r           - Apache request object.
 8380:    $question    - The question number to prompt for.
 8381:    $scan_config - The scantron file configuration hash.
 8382:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8383:    $error       - Type of error
 8384:    $randomorder - True if randomorder in use.
 8385:    $randompick  - True if randompick in use.
 8386:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8387:                     for current line to question number used for same question
 8388:                     in "Master Seqence" (as seen by Course Coordinator).
 8389:    $startline   - Reference to hash where key is question number (0 is first)
 8390:                   and value is number of first bubble line for current student
 8391:                   or code-based randompick and/or randomorder.
 8392: 
 8393: 
 8394:  Implicit inputs:
 8395:    %bubble_lines_per_response   - Starting line numbers for each question.
 8396:                                   Numbered from 0 (but question numbers are from
 8397:                                   1.
 8398:    %first_bubble_line           - Starting bubble line for each question.
 8399:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8400:                                   type problems render as separate sub-questions, 
 8401:                                   in exam mode. This hash contains a 
 8402:                                   comma-separated list of the lines per 
 8403:                                   sub-question.
 8404:    %responsetype_per_response   - essayresponse, formularesponse,
 8405:                                   stringresponse, imageresponse, reactionresponse,
 8406:                                   and organicresponse type problem parts can have
 8407:                                   multiple lines per response if the weight
 8408:                                   assigned exceeds 10.  In this case, only
 8409:                                   one bubble per line is permitted, but more 
 8410:                                   than one line might contain bubbles, e.g.
 8411:                                   bubbling of: line 1 - J, line 2 - J, 
 8412:                                   line 3 - B would assign 22 points.  
 8413: 
 8414: =cut
 8415: 
 8416: sub prompt_for_corrections {
 8417:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8418:         $randompick, $respnumlookup, $startline) = @_;
 8419:     my ($current_line,$lines);
 8420:     my @linenums;
 8421:     my $questionnum = $question;
 8422:     my ($first,$responsenum);
 8423:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8424:         $question = $1;
 8425:         my $subquestion = $2;
 8426:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8427:             $responsenum = $respnumlookup->{$question-1};
 8428:             if (ref($startline) eq 'HASH') {
 8429:                 $first = $startline->{$question-1};
 8430:             }
 8431:         } else {
 8432:             $responsenum = $question-1;
 8433:             $first = $first_bubble_line{$responsenum};
 8434:         }
 8435:         $current_line = $first + 1 ;
 8436:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8437:         my $subcount = 1;
 8438:         while ($subcount<$subquestion) {
 8439:             $current_line += $subans[$subcount-1];
 8440:             $subcount ++;
 8441:         }
 8442:         $lines = $subans[$subquestion-1];
 8443:     } else {
 8444:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8445:             $responsenum = $respnumlookup->{$question-1};
 8446:             if (ref($startline) eq 'HASH') { 
 8447:                 $first = $startline->{$question-1};
 8448:             }
 8449:         } else {
 8450:             $responsenum = $question-1;
 8451:             $first = $first_bubble_line{$responsenum};
 8452:         }
 8453:         $current_line = $first + 1;
 8454:         $lines        = $bubble_lines_per_response{$responsenum};
 8455:     }
 8456:     if ($lines > 1) {
 8457:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8458:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8459:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8460:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8461:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8462:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8463:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8464:             $r->print(
 8465:                 &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)
 8466:                .'<br /><br />'
 8467:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8468:                .'<br />'
 8469:                .&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.')
 8470:                .'<br />'
 8471:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8472:                .'<br /><br />'
 8473:             );
 8474:         } else {
 8475:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8476:         }
 8477:     }
 8478:     for (my $i =0; $i < $lines; $i++) {
 8479:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8480: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8481: 	        		  $questionnum,$error,split('', $selected));
 8482:         push(@linenums,$current_line);
 8483: 	$current_line++;
 8484:     }
 8485:     if ($lines > 1) {
 8486: 	$r->print("<hr /><br />");
 8487:     }
 8488:     return @linenums;
 8489: }
 8490: 
 8491: =pod
 8492: 
 8493: =item scantron_bubble_selector
 8494:   
 8495:    Generates the html radiobuttons to correct a single bubble line
 8496:    possibly showing the existing the selected bubbles if known
 8497: 
 8498:  Arguments:
 8499:     $r           - Apache request object
 8500:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8501:     $line        - Number of the line being displayed.
 8502:     $questionnum - Question number (may include subquestion)
 8503:     $error       - Type of error.
 8504:     @selected    - Array of bubbles picked on this line.
 8505: 
 8506: =cut
 8507: 
 8508: sub scantron_bubble_selector {
 8509:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8510:     my $max=$$scan_config{'Qlength'};
 8511: 
 8512:     my $scmode=$$scan_config{'Qon'};
 8513:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8514:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8515:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8516:             $max=$$scan_config{'BubblesPerRow'};
 8517:             if (($scmode eq 'number') && ($max > 10)) {
 8518:                 $max = 10;
 8519:             } elsif (($scmode eq 'letter') && $max > 26) {
 8520:                 $max = 26;
 8521:             }
 8522:         } else {
 8523:             $max = 10;
 8524:         }
 8525:     }
 8526: 
 8527:     my @alphabet=('A'..'Z');
 8528:     $r->print(&Apache::loncommon::start_data_table().
 8529:               &Apache::loncommon::start_data_table_row());
 8530:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8531:     for (my $i=0;$i<$max+1;$i++) {
 8532: 	$r->print("\n".'<td align="center">');
 8533: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8534: 	else { $r->print('&nbsp;'); }
 8535: 	$r->print('</td>');
 8536:     }
 8537:     $r->print(&Apache::loncommon::end_data_table_row().
 8538:               &Apache::loncommon::start_data_table_row());
 8539:     for (my $i=0;$i<$max;$i++) {
 8540: 	$r->print("\n".
 8541: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8542: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8543:     }
 8544:     my $nobub_checked = ' ';
 8545:     if ($error eq 'missingbubble') {
 8546:         $nobub_checked = ' checked = "checked" ';
 8547:     }
 8548:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8549: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8550:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8551:               $line.'" value="'.$questionnum.'" /></td>');
 8552:     $r->print(&Apache::loncommon::end_data_table_row().
 8553:               &Apache::loncommon::end_data_table());
 8554: }
 8555: 
 8556: =pod
 8557: 
 8558: =item num_matches
 8559: 
 8560:    Counts the number of characters that are the same between the two arguments.
 8561: 
 8562:  Arguments:
 8563:    $orig - CODE from the scanline
 8564:    $code - CODE to match against
 8565: 
 8566:  Returns:
 8567:    $count - integer count of the number of same characters between the
 8568:             two arguments
 8569: 
 8570: =cut
 8571: 
 8572: sub num_matches {
 8573:     my ($orig,$code) = @_;
 8574:     my @code=split(//,$code);
 8575:     my @orig=split(//,$orig);
 8576:     my $same=0;
 8577:     for (my $i=0;$i<scalar(@code);$i++) {
 8578: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8579:     }
 8580:     return $same;
 8581: }
 8582: 
 8583: =pod
 8584: 
 8585: =item scantron_get_closely_matching_CODEs
 8586: 
 8587:    Cycles through all CODEs and finds the set that has the greatest
 8588:    number of same characters as the provided CODE
 8589: 
 8590:  Arguments:
 8591:    $allcodes - hash ref returned by &get_codes()
 8592:    $CODE     - CODE from the current scanline
 8593: 
 8594:  Returns:
 8595:    2 element list
 8596:     - first elements is number of how closely matching the best fit is 
 8597:       (5 means best set has 5 matching characters)
 8598:     - second element is an arrary ref containing the set of valid CODEs
 8599:       that best fit the passed in CODE
 8600: 
 8601: =cut
 8602: 
 8603: sub scantron_get_closely_matching_CODEs {
 8604:     my ($allcodes,$CODE)=@_;
 8605:     my @CODEs;
 8606:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8607: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8608:     }
 8609: 
 8610:     return ($#CODEs,$CODEs[-1]);
 8611: }
 8612: 
 8613: =pod
 8614: 
 8615: =item get_codes
 8616: 
 8617:    Builds a hash which has keys of all of the valid CODEs from the selected
 8618:    set of remembered CODEs.
 8619: 
 8620:  Arguments:
 8621:   $old_name - name of the set of remembered CODEs
 8622:   $cdom     - domain of the course
 8623:   $cnum     - internal course name
 8624: 
 8625:  Returns:
 8626:   %allcodes - keys are the valid CODEs, values are all 1
 8627: 
 8628: =cut
 8629: 
 8630: sub get_codes {
 8631:     my ($old_name, $cdom, $cnum) = @_;
 8632:     if (!$old_name) {
 8633: 	$old_name=$env{'form.scantron_CODElist'};
 8634:     }
 8635:     if (!$cdom) {
 8636: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8637:     }
 8638:     if (!$cnum) {
 8639: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8640:     }
 8641:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8642: 				    $cdom,$cnum);
 8643:     my %allcodes;
 8644:     if ($result{"type\0$old_name"} eq 'number') {
 8645: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8646:     } else {
 8647: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8648:     }
 8649:     return %allcodes;
 8650: }
 8651: 
 8652: =pod
 8653: 
 8654: =item scantron_validate_CODE
 8655: 
 8656:    Validates all scanlines in the selected file to not have any
 8657:    invalid or underspecified CODEs and that none of the codes are
 8658:    duplicated if this was requested.
 8659: 
 8660: =cut
 8661: 
 8662: sub scantron_validate_CODE {
 8663:     my ($r,$currentphase) = @_;
 8664:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8665:     if ($scantron_config{'CODElocation'} &&
 8666: 	$scantron_config{'CODEstart'} &&
 8667: 	$scantron_config{'CODElength'}) {
 8668: 	if (!defined($env{'form.scantron_CODElist'})) {
 8669: 	    &FIXME_blow_up()
 8670: 	}
 8671:     } else {
 8672: 	return (0,$currentphase+1);
 8673:     }
 8674:     
 8675:     my %usedCODEs;
 8676: 
 8677:     my %allcodes=&get_codes();
 8678: 
 8679:     my $nav_error;
 8680:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8681:     if ($nav_error) {
 8682:         $r->print(&navmap_errormsg());
 8683:         return(1,$currentphase);
 8684:     }
 8685: 
 8686:     my ($scanlines,$scan_data)=&scantron_getfile();
 8687:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8688: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8689: 	if ($line=~/^[\s\cz]*$/) { next; }
 8690: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8691: 						 $scan_data);
 8692: 	my $CODE=$$scan_record{'scantron.CODE'};
 8693: 	my $error=0;
 8694: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8695: 	    &scantron_get_correction($r,$i,$scan_record,
 8696: 				     \%scantron_config,
 8697: 				     $line,'incorrectCODE',\%allcodes);
 8698: 	    return(1,$currentphase);
 8699: 	}
 8700: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8701: 	    && !$$scan_record{'scantron.useCODE'}) {
 8702: 	    &scantron_get_correction($r,$i,$scan_record,
 8703: 				     \%scantron_config,
 8704: 				     $line,'incorrectCODE',\%allcodes);
 8705: 	    return(1,$currentphase);
 8706: 	}
 8707: 	if (exists($usedCODEs{$CODE}) 
 8708: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8709: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8710: 	    &scantron_get_correction($r,$i,$scan_record,
 8711: 				     \%scantron_config,
 8712: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8713: 	    return(1,$currentphase);
 8714: 	}
 8715: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8716:     }
 8717:     return (0,$currentphase+1);
 8718: }
 8719: 
 8720: =pod
 8721: 
 8722: =item scantron_validate_doublebubble
 8723: 
 8724:    Validates all scanlines in the selected file to not have any
 8725:    bubble lines with multiple bubbles marked.
 8726: 
 8727: =cut
 8728: 
 8729: sub scantron_validate_doublebubble {
 8730:     my ($r,$currentphase) = @_;
 8731:     #get student info
 8732:     my $classlist=&Apache::loncoursedata::get_classlist();
 8733:     my %idmap=&username_to_idmap($classlist);
 8734:     my (undef,undef,$sequence)=
 8735:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8736: 
 8737:     #get scantron line setup
 8738:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8739:     my ($scanlines,$scan_data)=&scantron_getfile();
 8740: 
 8741:     my $navmap = Apache::lonnavmaps::navmap->new();
 8742:     unless (ref($navmap)) {
 8743:         $r->print(&navmap_errormsg());
 8744:         return(1,$currentphase);
 8745:     }
 8746:     my $map=$navmap->getResourceByUrl($sequence);
 8747:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8748:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8749:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8750:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8751: 
 8752:     my $nav_error;
 8753:     if (ref($map)) {
 8754:         $randomorder = $map->randomorder();
 8755:         $randompick = $map->randompick();
 8756:         if ($randomorder || $randompick) {
 8757:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8758:             if ($nav_error) {
 8759:                 $r->print(&navmap_errormsg());
 8760:                 return(1,$currentphase);
 8761:             }
 8762:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8763:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8764:         }
 8765:     } else {
 8766:         $r->print(&navmap_errormsg());
 8767:         return(1,$currentphase);
 8768:     }
 8769: 
 8770:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8771:     if ($nav_error) {
 8772:         $r->print(&navmap_errormsg());
 8773:         return(1,$currentphase);
 8774:     }
 8775: 
 8776:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8777: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8778: 	if ($line=~/^[\s\cz]*$/) { next; }
 8779: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8780: 						 $scan_data,undef,\%idmap,$randomorder,
 8781:                                                  $randompick,$sequence,\@master_seq,
 8782:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8783:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8784: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8785: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8786: 				 'doublebubble',
 8787: 				 $$scan_record{'scantron.doubleerror'},
 8788:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8789:     	return (1,$currentphase);
 8790:     }
 8791:     return (0,$currentphase+1);
 8792: }
 8793: 
 8794: 
 8795: sub scantron_get_maxbubble {
 8796:     my ($nav_error,$scantron_config) = @_;
 8797:     if (defined($env{'form.scantron_maxbubble'}) &&
 8798: 	$env{'form.scantron_maxbubble'}) {
 8799: 	&restore_bubble_lines();
 8800: 	return $env{'form.scantron_maxbubble'};
 8801:     }
 8802: 
 8803:     my (undef, undef, $sequence) =
 8804: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8805: 
 8806:     my $navmap=Apache::lonnavmaps::navmap->new();
 8807:     unless (ref($navmap)) {
 8808:         if (ref($nav_error)) {
 8809:             $$nav_error = 1;
 8810:         }
 8811:         return;
 8812:     }
 8813:     my $map=$navmap->getResourceByUrl($sequence);
 8814:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8815:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8816: 
 8817:     &Apache::lonxml::clear_problem_counter();
 8818: 
 8819:     my $uname       = $env{'user.name'};
 8820:     my $udom        = $env{'user.domain'};
 8821:     my $cid         = $env{'request.course.id'};
 8822:     my $total_lines = 0;
 8823:     %bubble_lines_per_response = ();
 8824:     %first_bubble_line         = ();
 8825:     %subdivided_bubble_lines   = ();
 8826:     %responsetype_per_response = ();
 8827:     %masterseq_id_responsenum  = ();
 8828: 
 8829:     my $response_number = 0;
 8830:     my $bubble_line     = 0;
 8831:     foreach my $resource (@resources) {
 8832:         my $resid = $resource->id(); 
 8833:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8834:                                                           $udom,undef,$bubbles_per_row);
 8835:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8836: 	    foreach my $part_id (@{$parts}) {
 8837:                 my $lines;
 8838: 
 8839: 	        # TODO - make this a persistent hash not an array.
 8840: 
 8841:                 # optionresponse, matchresponse and rankresponse type items 
 8842:                 # render as separate sub-questions in exam mode.
 8843:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8844:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8845:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8846:                     my ($numbub,$numshown);
 8847:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8848:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8849:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8850:                         }
 8851:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8852:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8853:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8854:                         }
 8855:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8856:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8857:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8858:                         }
 8859:                     }
 8860:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8861:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8862:                     }
 8863:                     my $bubbles_per_row =
 8864:                         &bubblesheet_bubbles_per_row($scantron_config);
 8865:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8866:                     if (($numbub % $bubbles_per_row) != 0) {
 8867:                         $inner_bubble_lines++;
 8868:                     }
 8869:                     for (my $i=0; $i<$numshown; $i++) {
 8870:                         $subdivided_bubble_lines{$response_number} .= 
 8871:                             $inner_bubble_lines.',';
 8872:                     }
 8873:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8874:                     $lines = $numshown * $inner_bubble_lines;
 8875:                 } else {
 8876:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8877:                 }
 8878: 
 8879:                 $first_bubble_line{$response_number} = $bubble_line;
 8880: 	        $bubble_lines_per_response{$response_number} = $lines;
 8881:                 $responsetype_per_response{$response_number} = 
 8882:                     $analysis->{$part_id.'.type'};
 8883:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8884: 	        $response_number++;
 8885: 
 8886: 	        $bubble_line +=  $lines;
 8887: 	        $total_lines +=  $lines;
 8888: 	    }
 8889:         }
 8890:     }
 8891:     &Apache::lonnet::delenv('scantron.');
 8892: 
 8893:     &save_bubble_lines();
 8894:     $env{'form.scantron_maxbubble'} =
 8895: 	$total_lines;
 8896:     return $env{'form.scantron_maxbubble'};
 8897: }
 8898: 
 8899: sub bubblesheet_bubbles_per_row {
 8900:     my ($scantron_config) = @_;
 8901:     my $bubbles_per_row;
 8902:     if (ref($scantron_config) eq 'HASH') {
 8903:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8904:     }
 8905:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8906:         $bubbles_per_row = 10;
 8907:     }
 8908:     return $bubbles_per_row;
 8909: }
 8910: 
 8911: sub scantron_validate_missingbubbles {
 8912:     my ($r,$currentphase) = @_;
 8913:     #get student info
 8914:     my $classlist=&Apache::loncoursedata::get_classlist();
 8915:     my %idmap=&username_to_idmap($classlist);
 8916:     my (undef,undef,$sequence)=
 8917:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8918: 
 8919:     #get scantron line setup
 8920:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8921:     my ($scanlines,$scan_data)=&scantron_getfile();
 8922: 
 8923:     my $navmap = Apache::lonnavmaps::navmap->new();
 8924:     unless (ref($navmap)) {
 8925:         $r->print(&navmap_errormsg());
 8926:         return(1,$currentphase);
 8927:     }
 8928: 
 8929:     my $map=$navmap->getResourceByUrl($sequence);
 8930:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8931:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8932:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8933:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8934: 
 8935:     my $nav_error;
 8936:     if (ref($map)) {
 8937:         $randomorder = $map->randomorder();
 8938:         $randompick = $map->randompick();
 8939:         if ($randomorder || $randompick) {
 8940:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8941:             if ($nav_error) {
 8942:                 $r->print(&navmap_errormsg());
 8943:                 return(1,$currentphase);
 8944:             }
 8945:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8946:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8947:         }
 8948:     } else {
 8949:         $r->print(&navmap_errormsg());
 8950:         return(1,$currentphase);
 8951:     }
 8952: 
 8953: 
 8954:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8955:     if ($nav_error) {
 8956:         $r->print(&navmap_errormsg());
 8957:         return(1,$currentphase);
 8958:     }
 8959: 
 8960:     if (!$max_bubble) { $max_bubble=2**31; }
 8961:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8962: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8963: 	if ($line=~/^[\s\cz]*$/) { next; }
 8964: 	my $scan_record =
 8965:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8966: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8967:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8968:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8969: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8970: 	my @to_correct;
 8971: 	
 8972: 	# Probably here's where the error is...
 8973: 
 8974: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8975:             my $lastbubble;
 8976:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8977:                my $question = $1;
 8978:                my $subquestion = $2;
 8979:                my ($first,$responsenum);
 8980:                if ($randomorder || $randompick) {
 8981:                    $responsenum = $respnumlookup{$question-1};
 8982:                    $first = $startline{$question-1};
 8983:                } else {
 8984:                    $responsenum = $question-1; 
 8985:                    $first = $first_bubble_line{$responsenum};
 8986:                }
 8987:                if (!defined($first)) { next; }
 8988:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8989:                my $subcount = 1;
 8990:                while ($subcount<$subquestion) {
 8991:                    $first += $subans[$subcount-1];
 8992:                    $subcount ++;
 8993:                }
 8994:                my $count = $subans[$subquestion-1];
 8995:                $lastbubble = $first + $count;
 8996:             } else {
 8997:                my ($first,$responsenum);
 8998:                if ($randomorder || $randompick) {
 8999:                    $responsenum = $respnumlookup{$missing-1};
 9000:                    $first = $startline{$missing-1};
 9001:                } else {
 9002:                    $responsenum = $missing-1;
 9003:                    $first = $first_bubble_line{$responsenum};
 9004:                }
 9005:                if (!defined($first)) { next; }
 9006:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 9007:             }
 9008:             if ($lastbubble > $max_bubble) { next; }
 9009: 	    push(@to_correct,$missing);
 9010: 	}
 9011: 	if (@to_correct) {
 9012: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 9013: 				     $line,'missingbubble',\@to_correct,
 9014:                                      $randomorder,$randompick,\%respnumlookup,
 9015:                                      \%startline);
 9016: 	    return (1,$currentphase);
 9017: 	}
 9018: 
 9019:     }
 9020:     return (0,$currentphase+1);
 9021: }
 9022: 
 9023: sub hand_bubble_option {
 9024:     my (undef, undef, $sequence) =
 9025:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9026:     return if ($sequence eq '');
 9027:     my $navmap = Apache::lonnavmaps::navmap->new();
 9028:     unless (ref($navmap)) {
 9029:         return;
 9030:     }
 9031:     my $needs_hand_bubbles;
 9032:     my $map=$navmap->getResourceByUrl($sequence);
 9033:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9034:     foreach my $res (@resources) {
 9035:         if (ref($res)) {
 9036:             if ($res->is_problem()) {
 9037:                 my $partlist = $res->parts();
 9038:                 foreach my $part (@{ $partlist }) {
 9039:                     my @types = $res->responseType($part);
 9040:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 9041:                         $needs_hand_bubbles = 1;
 9042:                         last;
 9043:                     }
 9044:                 }
 9045:             }
 9046:         }
 9047:     }
 9048:     if ($needs_hand_bubbles) {
 9049:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9050:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9051:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 9052:                &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 />').
 9053:                '<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;'.
 9054:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 9055:     }
 9056:     return;
 9057: }
 9058: 
 9059: sub scantron_process_students {
 9060:     my ($r,$symb) = @_;
 9061: 
 9062:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 9063:     if (!$symb) {
 9064: 	return '';
 9065:     }
 9066:     my $default_form_data=&defaultFormData($symb);
 9067: 
 9068:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9069:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 9070:     my ($scanlines,$scan_data)=&scantron_getfile();
 9071:     my $classlist=&Apache::loncoursedata::get_classlist();
 9072:     my %idmap=&username_to_idmap($classlist);
 9073:     my $navmap=Apache::lonnavmaps::navmap->new();
 9074:     unless (ref($navmap)) {
 9075:         $r->print(&navmap_errormsg());
 9076:         return '';
 9077:     }
 9078:     my $map=$navmap->getResourceByUrl($sequence);
 9079:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9080:         %grader_randomlists_by_symb);
 9081:     if (ref($map)) {
 9082:         $randomorder = $map->randomorder();
 9083:         $randompick = $map->randompick();
 9084:     } else {
 9085:         $r->print(&navmap_errormsg());
 9086:         return '';
 9087:     }
 9088:     my $nav_error;
 9089:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9090:     if ($randomorder || $randompick) {
 9091:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9092:         if ($nav_error) {
 9093:             $r->print(&navmap_errormsg());
 9094:             return '';
 9095:         }
 9096:     }
 9097:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9098:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9099: 
 9100:     my ($uname,$udom);
 9101:     my $result= <<SCANTRONFORM;
 9102: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9103:   <input type="hidden" name="command" value="scantron_configphase" />
 9104:   $default_form_data
 9105: SCANTRONFORM
 9106:     $r->print($result);
 9107: 
 9108:     my ($checksec,@possibles)=&gradable_sections();
 9109:     my @delayqueue;
 9110:     my (%completedstudents,%scandata);
 9111: 
 9112:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9113:     my $count=&get_todo_count($scanlines,$scan_data);
 9114:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9115:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9116:     $r->print('<br />');
 9117:     my $start=&Time::HiRes::time();
 9118:     my $i=-1;
 9119:     my $started;
 9120: 
 9121:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9122:     if ($nav_error) {
 9123:         $r->print(&navmap_errormsg());
 9124:         return '';
 9125:     }
 9126: 
 9127:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9128:     # the user and return.
 9129: 
 9130:     if ($ssi_error) {
 9131: 	$r->print("</form>");
 9132: 	&ssi_print_error($r);
 9133:         &Apache::lonnet::remove_lock($lock);
 9134: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9135:     }
 9136: 
 9137:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9138:     my $numletts = scalar(keys(%lettdig));
 9139:     my %orderedforcode;
 9140: 
 9141:     while ($i<$scanlines->{'count'}) {
 9142:  	($uname,$udom)=('','');
 9143:  	$i++;
 9144:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9145:  	if ($line=~/^[\s\cz]*$/) { next; }
 9146: 	if ($started) {
 9147: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9148: 	}
 9149: 	$started=1;
 9150:         my %respnumlookup = ();
 9151:         my %startline = ();
 9152:         my $total;
 9153:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9154:                                                  $scan_data,undef,\%idmap,$randomorder,
 9155:                                                  $randompick,$sequence,\@master_seq,
 9156:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9157:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9158:                                                  \$total);
 9159:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9160:  					      \%idmap,$i)) {
 9161:   	    &scantron_add_delay(\@delayqueue,$line,
 9162:  				'Unable to find a student that matches',1);
 9163:  	    next;
 9164:   	}
 9165:  	if (exists $completedstudents{$uname}) {
 9166:  	    &scantron_add_delay(\@delayqueue,$line,
 9167:  				'Student '.$uname.' has multiple sheets',2);
 9168:  	    next;
 9169:  	}
 9170:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9171:         if (($checksec ne '') && ($checksec ne $usec)) {
 9172:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9173:                 &scantron_add_delay(\@delayqueue,$line,
 9174:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9175:                 next;
 9176:             }
 9177:         }
 9178:         my $user = $uname.':'.$usec;
 9179:   	($uname,$udom)=split(/:/,$uname);
 9180: 
 9181:         my $scancode;
 9182:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9183:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9184:             $scancode = $scan_record->{'scantron.CODE'};
 9185:         } else {
 9186:             $scancode = '';
 9187:         }
 9188: 
 9189:         my @mapresources = @resources;
 9190:         if ($randomorder || $randompick) {
 9191:             @mapresources = 
 9192:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9193:                              \%orderedforcode);
 9194:         }
 9195:         my (%partids_by_symb,$res_error);
 9196:         foreach my $resource (@mapresources) {
 9197:             my $ressymb;
 9198:             if (ref($resource)) {
 9199:                 $ressymb = $resource->symb();
 9200:             } else {
 9201:                 $res_error = 1;
 9202:                 last;
 9203:             }
 9204:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9205:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9206:                 my $currcode;
 9207:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9208:                     $currcode = $scancode;
 9209:                 }
 9210:                 my ($analysis,$parts) =
 9211:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9212:                                               $uname,$udom,undef,$bubbles_per_row,
 9213:                                               $currcode);
 9214:                 $partids_by_symb{$ressymb} = $parts;
 9215:             } else {
 9216:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9217:             }
 9218:         }
 9219: 
 9220:         if ($res_error) {
 9221:             &scantron_add_delay(\@delayqueue,$line,
 9222:                                 'An error occurred while grading student '.$uname,2);
 9223:             next;
 9224:         }
 9225: 
 9226: 	&Apache::lonxml::clear_problem_counter();
 9227:   	&Apache::lonnet::appenv($scan_record);
 9228: 
 9229: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9230: 	    &scantron_putfile($scanlines,$scan_data);
 9231: 	}
 9232: 	
 9233:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9234:                                    \@mapresources,\%partids_by_symb,
 9235:                                    $bubbles_per_row,$randomorder,$randompick,
 9236:                                    \%respnumlookup,\%startline) 
 9237:             eq 'ssi_error') {
 9238:             $ssi_error = 0; # So end of handler error message does not trigger.
 9239:             $r->print("</form>");
 9240:             &ssi_print_error($r);
 9241:             &Apache::lonnet::remove_lock($lock);
 9242:             return '';      # Why return ''?  Beats me.
 9243:         }
 9244: 
 9245:         if (($scancode) && ($randomorder || $randompick)) {
 9246:             my $parmresult =
 9247:                 &Apache::lonparmset::storeparm_by_symb($symb,
 9248:                                                        '0_examcode',2,$scancode,
 9249:                                                        'string_examcode',$uname,
 9250:                                                        $udom);
 9251:         }
 9252: 	$completedstudents{$uname}={'line'=>$line};
 9253:         if ($env{'form.verifyrecord'}) {
 9254:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9255:             if ($randompick) {
 9256:                 if ($total) {
 9257:                     $lastpos = $total*$scantron_config{'Qlength'};
 9258:                 }
 9259:             }
 9260: 
 9261:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9262:             chomp($studentdata);
 9263:             $studentdata =~ s/\r$//;
 9264:             my $studentrecord = '';
 9265:             my $counter = -1;
 9266:             foreach my $resource (@mapresources) {
 9267:                 my $ressymb = $resource->symb();
 9268:                 ($counter,my $recording) =
 9269:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9270:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9271:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9272:                                              $randompick,\%respnumlookup,\%startline);
 9273:                 $studentrecord .= $recording;
 9274:             }
 9275:             if ($studentrecord ne $studentdata) {
 9276:                 &Apache::lonxml::clear_problem_counter();
 9277:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9278:                                            \@mapresources,\%partids_by_symb,
 9279:                                            $bubbles_per_row,$randomorder,$randompick,
 9280:                                            \%respnumlookup,\%startline) 
 9281:                     eq 'ssi_error') {
 9282:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9283:                     $r->print("</form>");
 9284:                     &ssi_print_error($r);
 9285:                     &Apache::lonnet::remove_lock($lock);
 9286:                     delete($completedstudents{$uname});
 9287:                     return '';
 9288:                 }
 9289:                 $counter = -1;
 9290:                 $studentrecord = '';
 9291:                 foreach my $resource (@mapresources) {
 9292:                     my $ressymb = $resource->symb();
 9293:                     ($counter,my $recording) =
 9294:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9295:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9296:                                                  \%scantron_config,\%lettdig,$numletts,
 9297:                                                  $randomorder,$randompick,\%respnumlookup,
 9298:                                                  \%startline);
 9299:                     $studentrecord .= $recording;
 9300:                 }
 9301:                 if ($studentrecord ne $studentdata) {
 9302:                     $r->print('<p><span class="LC_warning">');
 9303:                     if ($scancode eq '') {
 9304:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9305:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9306:                     } else {
 9307:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9308:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9309:                     }
 9310:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9311:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9312:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9313:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9314:                               &Apache::loncommon::start_data_table_row().
 9315:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9316:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9317:                               &Apache::loncommon::end_data_table_row().
 9318:                               &Apache::loncommon::start_data_table_row().
 9319:                               '<td>'.&mt('Stored submissions').'</td>'.
 9320:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9321:                               &Apache::loncommon::end_data_table_row().
 9322:                               &Apache::loncommon::end_data_table().'</p>');
 9323:                 } else {
 9324:                     $r->print('<br /><span class="LC_warning">'.
 9325:                              &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 />'.
 9326:                              &mt("As a consequence, this user's submission history records two tries.").
 9327:                                  '</span><br />');
 9328:                 }
 9329:             }
 9330:         }
 9331:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9332:     } continue {
 9333: 	&Apache::lonxml::clear_problem_counter();
 9334: 	&Apache::lonnet::delenv('scantron.');
 9335:     }
 9336:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9337:     &Apache::lonnet::remove_lock($lock);
 9338: #    my $lasttime = &Time::HiRes::time()-$start;
 9339: #    $r->print("<p>took $lasttime</p>");
 9340: 
 9341:     $r->print("</form>");
 9342:     return '';
 9343: }
 9344: 
 9345: sub graders_resources_pass {
 9346:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9347:         $bubbles_per_row) = @_;
 9348:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9349:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9350:         foreach my $resource (@{$resources}) {
 9351:             my $ressymb = $resource->symb();
 9352:             my ($analysis,$parts) =
 9353:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9354:                                           $env{'user.name'},$env{'user.domain'},
 9355:                                           1,$bubbles_per_row);
 9356:             $grader_partids_by_symb->{$ressymb} = $parts;
 9357:             if (ref($analysis) eq 'HASH') {
 9358:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9359:                     $grader_randomlists_by_symb->{$ressymb} =
 9360:                         $analysis->{'parts_withrandomlist'};
 9361:                 }
 9362:             }
 9363:         }
 9364:     }
 9365:     return;
 9366: }
 9367: 
 9368: =pod
 9369: 
 9370: =item users_order
 9371: 
 9372:   Returns array of resources in current map, ordered based on either CODE,
 9373:   if this is a CODEd exam, or based on student's identity if this is a 
 9374:   "NAMEd" exam.
 9375: 
 9376:   Should be used when randomorder and/or randompick applied when the 
 9377:   corresponding exam was printed, prior to students completing bubblesheets 
 9378:   for the version of the exam the student received.
 9379: 
 9380: =cut
 9381: 
 9382: sub users_order  {
 9383:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9384:     my @mapresources;
 9385:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9386:         return @mapresources;
 9387:     }
 9388:     if ($scancode) {
 9389:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9390:             @mapresources = @{$orderedforcode->{$scancode}};
 9391:         } else {
 9392:             $env{'form.CODE'} = $scancode;
 9393:             my $actual_seq =
 9394:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9395:                                                                $master_seq,
 9396:                                                                $user,$scancode,1);
 9397:             if (ref($actual_seq) eq 'ARRAY') {
 9398:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9399:                 if (ref($orderedforcode) eq 'HASH') {
 9400:                     if (@mapresources > 0) { 
 9401:                         $orderedforcode->{$scancode} = \@mapresources;
 9402:                     }
 9403:                 }
 9404:             }
 9405:             delete($env{'form.CODE'});
 9406:         }
 9407:     } else {
 9408:         my $actual_seq =
 9409:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9410:                                                            $master_seq,
 9411:                                                            $user,undef,1);
 9412:         if (ref($actual_seq) eq 'ARRAY') {
 9413:             @mapresources = 
 9414:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9415:         }
 9416:     }
 9417:     return @mapresources;
 9418: }
 9419: 
 9420: sub grade_student_bubbles {
 9421:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9422:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9423:     my $uselookup = 0;
 9424:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9425:         (ref($startline) eq 'HASH')) {
 9426:         $uselookup = 1;
 9427:     }
 9428: 
 9429:     if (ref($resources) eq 'ARRAY') {
 9430:         my $count = 0;
 9431:         foreach my $resource (@{$resources}) {
 9432:             my $ressymb = $resource->symb();
 9433:             my %form = ('submitted'      => 'scantron',
 9434:                         'grade_target'   => 'grade',
 9435:                         'grade_username' => $uname,
 9436:                         'grade_domain'   => $udom,
 9437:                         'grade_courseid' => $env{'request.course.id'},
 9438:                         'grade_symb'     => $ressymb,
 9439:                         'CODE'           => $scancode
 9440:                        );
 9441:             if ($bubbles_per_row ne '') {
 9442:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9443:             }
 9444:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9445:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9446:             }
 9447:             if (ref($parts) eq 'HASH') {
 9448:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9449:                     foreach my $part (@{$parts->{$ressymb}}) {
 9450:                         if ($uselookup) {
 9451:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9452:                         } else {
 9453:                             $form{'scantron_questnum_start.'.$part} =
 9454:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9455:                         }
 9456:                         $count++;
 9457:                     }
 9458:                 }
 9459:             }
 9460:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9461:             return 'ssi_error' if ($ssi_error);
 9462:             last if (&Apache::loncommon::connection_aborted($r));
 9463:         }
 9464:     }
 9465:     return;
 9466: }
 9467: 
 9468: sub scantron_upload_scantron_data {
 9469:     my ($r,$symb) = @_;
 9470:     my $dom = $env{'request.role.domain'};
 9471:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9472:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9473:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9474:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9475: 							  'domainid',
 9476: 							  'coursename',$dom);
 9477:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9478:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9479:     my $default_form_data=&defaultFormData($symb);
 9480:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9481:     &js_escape(\$nofile_alert);
 9482:     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.");
 9483:     &js_escape(\$nocourseid_alert);
 9484:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9485:     function checkUpload(formname) {
 9486: 	if (formname.upfile.value == "") {
 9487: 	    alert("'.$nofile_alert.'");
 9488: 	    return false;
 9489: 	}
 9490:         if (formname.courseid.value == "") {
 9491:             alert("'.$nocourseid_alert.'");
 9492:             return false;
 9493:         }
 9494: 	formname.submit();
 9495:     }
 9496: 
 9497:     function ToSyllabus() {
 9498:         var cdom = '."'$dom'".';
 9499:         var cnum = document.rules.courseid.value;
 9500:         if (cdom == "" || cdom == null) {
 9501:             return;
 9502:         }
 9503:         if (cnum == "" || cnum == null) {
 9504:            return;
 9505:         }
 9506:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9507:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9508:         return;
 9509:     }
 9510: 
 9511:     '.$formatjs.'
 9512: '));
 9513:     $r->print('
 9514: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9515: 
 9516: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9517: '.$default_form_data.
 9518:   &Apache::lonhtmlcommon::start_pick_box().
 9519:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9520:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9521:   &Apache::lonhtmlcommon::row_closure().
 9522:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9523:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9524:   &Apache::lonhtmlcommon::row_closure().
 9525:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9526:   '<input name="domainid" type="hidden" />'.$domdesc.
 9527:   &Apache::lonhtmlcommon::row_closure());
 9528:     if ($formatoptions) {
 9529:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9530:                   &Apache::lonhtmlcommon::row_closure());
 9531:     }
 9532:     $r->print(
 9533:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9534:   '<input type="file" name="upfile" size="50" />'.
 9535:   &Apache::lonhtmlcommon::row_closure(1).
 9536:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9537: 
 9538: <input name="command" value="scantronupload_save" type="hidden" />
 9539: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9540: </form>
 9541: ');
 9542:     return '';
 9543: }
 9544: 
 9545: sub scantron_upload_dataformat {
 9546:     my ($dom) = @_;
 9547:     my ($formatoptions,$formattitle,$formatjs);
 9548:     $formatjs = <<'END';
 9549: function toggleScantab(form) {
 9550:    return;
 9551: }
 9552: END
 9553:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9554:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9555:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9556:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9557:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9558:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9559:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9560:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9561:                             my ($onclick,$formatextra,$singleline);
 9562:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9563:                             my $count = 0;
 9564:                             foreach my $line (@lines) {
 9565:                                 next if ($line =~ /^#/);
 9566:                                 $singleline = $line;
 9567:                                 $count ++;
 9568:                             }
 9569:                             if ($count > 1) {
 9570:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9571:                                                '<span class="LC_nobreak">'.
 9572:                                                &mt('Bubblesheet type').':&nbsp;'.
 9573:                                                &scantron_scantab().'</span></div>';
 9574:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9575:                                 $formatjs = <<"END";
 9576: function toggleScantab(form) {
 9577:     var divid = 'bubbletype';
 9578:     if (document.getElementById(divid)) {
 9579:         var radioname = 'fileformat';
 9580:         var num = form.elements[radioname].length;
 9581:         if (num) {
 9582:             for (var i=0; i<num; i++) {
 9583:                 if (form.elements[radioname][i].checked) {
 9584:                     var chosen = form.elements[radioname][i].value;
 9585:                     if (chosen == 'dat') {
 9586:                         document.getElementById(divid).style.display = 'none';
 9587:                     } else if (chosen == 'csv') {
 9588:                         document.getElementById(divid).style.display = 'block';
 9589:                     }
 9590:                 }
 9591:             }
 9592:         }
 9593:     }
 9594:     return;
 9595: }
 9596: 
 9597: END
 9598:                             } elsif ($count == 1) {
 9599:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9600:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9601:                             }
 9602:                             $formattitle = &mt('File format');
 9603:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9604:                                              &mt('Plain Text (no delimiters)').
 9605:                                              '</label>'.('&nbsp;'x2).
 9606:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9607:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9608:                         }
 9609:                     }
 9610:                 }
 9611:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9612:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9613:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9614:                         $formattitle = &mt('Bubblesheet type');
 9615:                         $formatoptions = &scantron_scantab();
 9616:                     }
 9617:                 }
 9618:             }
 9619:         }
 9620:     }
 9621:     return ($formatoptions,$formattitle,$formatjs);
 9622: }
 9623: 
 9624: sub scantron_upload_scantron_data_save {
 9625:     my ($r,$symb) = @_;
 9626:     my $doanotherupload=
 9627: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9628: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9629: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9630: 	'</form>'."\n";
 9631:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9632: 	!&Apache::lonnet::allowed('usc',
 9633: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9634:         !&Apache::lonnet::allowed('usc',
 9635:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9636: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9637: 	unless ($symb) {
 9638: 	    $r->print($doanotherupload);
 9639: 	}
 9640: 	return '';
 9641:     }
 9642:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9643:     my $uploadedfile;
 9644:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9645:     if (length($env{'form.upfile'}) < 2) {
 9646:         $r->print(
 9647:             &Apache::lonhtmlcommon::confirm_success(
 9648:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9649:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9650:     } else {
 9651:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9652:         my $parser;
 9653:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9654:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9655:                 my $is_csv;
 9656:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9657:                 if (@possibles > 1) {
 9658:                     if ($env{'form.fileformat'} eq 'csv') {
 9659:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9660:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9661:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9662:                                     $is_csv = 1;
 9663:                                 }
 9664:                             }
 9665:                         }
 9666:                     }
 9667:                 } elsif (@possibles == 1) {
 9668:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9669:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9670:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9671:                                 $is_csv = 1;
 9672:                             }
 9673:                         }
 9674:                     }
 9675:                 }
 9676:                 if ($is_csv) {
 9677:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9678:                 }
 9679:             }
 9680:         }
 9681:         my $result =
 9682:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9683:                                             $env{'form.courseid'},$env{'form.domainid'});
 9684:         if ($result =~ m{^/uploaded/}) {
 9685:             $r->print(
 9686:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9687:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9688:                         (length($env{'form.upfile'})-1),
 9689:                         '<span class="LC_filename">'.$result.'</span>'));
 9690:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9691:             if ($uploadedfile =~ /^scantron_orig_/) {
 9692:                 my $logname = $uploadedfile;
 9693:                 $logname =~ s/^scantron_orig_//;
 9694:                 if ($logname ne '') {
 9695:                     my $now = time;
 9696:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9697:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9698:                 }
 9699:             }
 9700:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9701:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9702:         } else {
 9703:             $r->print(
 9704:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9705:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9706:                           $result,
 9707: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9708: 	}
 9709:     }
 9710:     if ($symb) {
 9711: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9712:     } else {
 9713: 	$r->print($doanotherupload);
 9714:     }
 9715:     return '';
 9716: }
 9717: 
 9718: sub validate_uploaded_scantron_file {
 9719:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9720: 
 9721:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9722:     my @lines;
 9723:     if ($scanlines ne '-1') {
 9724:         @lines=split("\n",$scanlines,-1);
 9725:     }
 9726:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9727:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9728:     if ($context eq 'download') {
 9729:         $priv = 'mgr';
 9730:     } else {
 9731:         $priv = 'usc';
 9732:     }
 9733:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9734:             (($env{'request.course.id'}) &&
 9735:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9736:         if ($env{'request.course.sec'} ne '') {
 9737:             unless (&Apache::lonnet::allowed($priv,
 9738:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9739:                 unless ($context eq 'download') {
 9740:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9741:                 }
 9742:                 return $output;
 9743:             }
 9744:             ($checksec,@possibles)=&gradable_sections();
 9745:         }
 9746:     }
 9747:     if (@lines) {
 9748:         my (%counts,$max_match_format);
 9749:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9750:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9751:         my %idmap = &username_to_idmap($classlist);
 9752:         foreach my $key (keys(%idmap)) {
 9753:             my $lckey = lc($key);
 9754:             $idmap{$lckey} = $idmap{$key};
 9755:         }
 9756:         my %unique_formats;
 9757:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9758:         foreach my $line (@formatlines) {
 9759:             chomp($line);
 9760:             my @config = split(/:/,$line);
 9761:             my $idstart = $config[5];
 9762:             my $idlength = $config[6];
 9763:             if (($idstart ne '') && ($idlength > 0)) {
 9764:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9765:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9766:                 } else {
 9767:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9768:                 }
 9769:             }
 9770:         }
 9771:         foreach my $key (keys(%unique_formats)) {
 9772:             my ($idstart,$idlength) = split(':',$key);
 9773:             %{$counts{$key}} = (
 9774:                                'found'   => 0,
 9775:                                'total'   => 0,
 9776:                                'totalanysec' => 0,
 9777:                                'othersec' => 0,
 9778:                               );
 9779:             foreach my $line (@lines) {
 9780:                 next if ($line =~ /^#/);
 9781:                 next if ($line =~ /^[\s\cz]*$/);
 9782:                 my $id = substr($line,$idstart-1,$idlength);
 9783:                 $id = lc($id);
 9784:                 if (exists($idmap{$id})) {
 9785:                     if ($checksec ne '') {
 9786:                         $counts{$key}{'totalanysec'} ++;
 9787:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9788:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9789:                             if ($stusec ne $checksec) {
 9790:                                 if (@possibles) {
 9791:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9792:                                         $counts{$key}{'othersec'} ++;
 9793:                                         next;
 9794:                                     }
 9795:                                 } else {
 9796:                                     $counts{$key}{'othersec'} ++;
 9797:                                     next;
 9798:                                 }
 9799:                             }
 9800:                         }
 9801:                     }
 9802:                     $counts{$key}{'found'} ++;
 9803:                 }
 9804:                 $counts{$key}{'total'} ++;
 9805:             }
 9806:             if ($counts{$key}{'total'}) {
 9807:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9808:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9809:                     $max_match_pct = $percent_match;
 9810:                     $max_match_format = $key;
 9811:                     $found_match_count = $counts{$key}{'found'};
 9812:                     $max_match_count = $counts{$key}{'total'};
 9813:                 }
 9814:             }
 9815:         }
 9816:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9817:             my $format_descs;
 9818:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9819:             for (my $i=0; $i<$numwithformat; $i++) {
 9820:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9821:                 if ($i<$numwithformat-2) {
 9822:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9823:                 } elsif ($i==$numwithformat-2) {
 9824:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9825:                 } elsif ($i==$numwithformat-1) {
 9826:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9827:                 }
 9828:             }
 9829:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9830:             $output .= '<br />';
 9831:             if ($found_match_count == $max_match_count) {
 9832:                 # 100% matching entries
 9833:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9834:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9835:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9836:                 &mt('Comparison of student IDs in the uploaded file with'.
 9837:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9838:                     ' in the file (for the format defined for [_3]).',
 9839:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9840:             } else {
 9841:                 # Not all entries matching? -> Show warning and additional info
 9842:                 $output .=
 9843:                     &Apache::lonhtmlcommon::confirm_success(
 9844:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9845:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9846:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9847:                     &mt('Comparison of student IDs in the uploaded file with'.
 9848:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9849:                         ' in the file (for the format defined for [_3]).',
 9850:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9851:                     '<p class="LC_info">'.
 9852:                     &mt('A low percentage of matches results from one of the following:').
 9853:                     '</p><ul>'.
 9854:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9855:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9856:                                '<i>'.$cdom.'</i>').'</li>'.
 9857:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9858:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9859:                     '</ul>';
 9860:             }
 9861:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9862:                 if ($counts{$max_match_format}{'othersec'}) {
 9863:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9864:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9865:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9866:                     &js_escape(\$confirmdel);
 9867:                     $output .= '<p class="LC_warning">'.
 9868:                                &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',
 9869:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9870:                                '<br />'.
 9871:                                &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>').
 9872:                                '</p><p>'.
 9873:                                &mt('If you prefer to delete the file now, use: [_1]').
 9874:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9875:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9876:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9877:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9878:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9879:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9880:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9881:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9882:                                '</form></p>';
 9883:                 }
 9884:             }
 9885:         }
 9886:         if (($context eq 'download') && ($checksec ne '')) {
 9887:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9888:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9889:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9890:             }
 9891:         } 
 9892:     } elsif ($context ne 'download') {
 9893:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9894:     }
 9895:     return $output;
 9896: }
 9897: 
 9898: sub gradable_sections {
 9899:     my $checksec = $env{'request.course.sec'};
 9900:     my @oksecs;
 9901:     if ($checksec) {
 9902:         my %availablesecs = &sections_grade_privs();
 9903:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9904:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9905:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9906:                     push(@oksecs,$sec);
 9907:                 }
 9908:             }
 9909:             if (grep(/^all$/,@oksecs)) {
 9910:                 undef($checksec);
 9911:             }
 9912:         }
 9913:     }
 9914:     return($checksec,@oksecs);
 9915: }
 9916: 
 9917: sub sections_grade_privs {
 9918:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9919:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9920:     my %availablesecs = (
 9921:                           mgr => [],
 9922:                           vgr => [],
 9923:                           usc => [],
 9924:                         );
 9925:     my $ccrole = 'cc';
 9926:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9927:         $ccrole = 'co';
 9928:     }
 9929:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9930:                                                      'userroles',['active'],
 9931:                                                      [$ccrole,'in','cr'],$cdom,1);
 9932:     my $crsid = $cnum.':'.$cdom;
 9933:     foreach my $item (keys(%crsroleshash)) {
 9934:         next unless ($item =~ /^$crsid\:/);
 9935:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9936:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9937:         if ($sec ne '') {
 9938:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9939:         }
 9940:         if (($role eq $ccrole) || ($role eq 'in')) {
 9941:             foreach my $priv ('mgr','vgr','usc') { 
 9942:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9943:                     if ($sec eq '') {
 9944:                         $availablesecs{$priv} = ['all'];
 9945:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9946:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9947:                             push(@{$availablesecs{$priv}},$sec);
 9948:                         }
 9949:                     }
 9950:                 }
 9951:             }
 9952:         } elsif ($role =~ m{^cr/}) {
 9953:             foreach my $priv ('mgr','vgr','usc') {
 9954:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9955:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9956:                         if ($sec eq '') {
 9957:                             $availablesecs{$priv} = ['all'];
 9958:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9959:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9960:                                 push(@{$availablesecs{$priv}},$sec);
 9961:                             }
 9962:                         }
 9963:                     }
 9964:                 }
 9965:             }
 9966:         }
 9967:     }
 9968:     return %availablesecs;
 9969: }
 9970: 
 9971: sub scantron_upload_delete {
 9972:     my ($r,$symb) = @_;
 9973:     my $filename = $env{'form.uploadedfile'};
 9974:     if ($filename =~ /^scantron_orig_/) {
 9975:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9976:             &Apache::lonnet::allowed('usc',
 9977:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9978:             &Apache::lonnet::allowed('usc',
 9979:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9980:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9981:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9982:             if ($retrieval eq '-1') {
 9983:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9984:                           &mt('File requested for deletion not found.'));
 9985:             } else {
 9986:                 $filename =~ s/^scantron_orig_//;
 9987:                 if ($filename ne '') {
 9988:                     my ($is_valid,$numleft);
 9989:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9990:                     if (keys(%info)) {
 9991:                         if (ref($info{$filename}) eq 'HASH') {
 9992:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9993:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9994:                                     $is_valid = 1;
 9995:                                     delete($info{$filename}{$timestamp}); 
 9996:                                 }
 9997:                             }
 9998:                             $numleft = scalar(keys(%{$info{$filename}}));
 9999:                         }
10000:                     }
10001:                     if ($is_valid) {
10002:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
10003:                         if ($result eq 'ok') {
10004:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
10005:                             if ($numleft) {
10006:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
10007:                             } else {
10008:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
10009:                             }
10010:                         } else {
10011:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10012:                                       &mt('Result was [_1]',$result));
10013:                         }
10014:                     } else {
10015:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10016:                                   &mt('File requested for deletion was uploaded by a different user.'));
10017:                     }
10018:                 } else {
10019:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10020:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10021:                 }
10022:             }
10023:         } else {
10024:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
10025:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
10026:         }
10027:     } else {
10028:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10029:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10030:     }
10031:     return;
10032: }
10033: 
10034: sub valid_file {
10035:     my ($requested_file)=@_;
10036:     foreach my $filename (sort(&scantron_filenames())) {
10037: 	if ($requested_file eq $filename) { return 1; }
10038:     }
10039:     return 0;
10040: }
10041: 
10042: sub scantron_download_scantron_data {
10043:     my ($r,$symb) = @_;
10044:     my $default_form_data=&defaultFormData($symb);
10045:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10046:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10047:     my $file=$env{'form.scantron_selectfile'};
10048:     if (! &valid_file($file)) {
10049: 	$r->print('
10050: 	<p>
10051: 	    '.&mt('The requested filename was invalid.').'
10052:         </p>
10053: ');
10054: 	return;
10055:     }
10056:     my (%uploader,$is_owner,%counts,$percent);
10057:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
10058:     if (ref($uploader{$file}) eq 'HASH') {
10059:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
10060:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10061:                 $is_owner = 1;
10062:                 last;
10063:             }
10064:         }
10065:     }
10066:     unless ($is_owner) {
10067:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
10068:         if ($counts{'totalanysec'}) {
10069:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
10070:             if ($percent_othersec >= 10) {
10071:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
10072:                 $r->print('<p class="LC_warning">'.
10073:                           &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).
10074:                           '</p>');
10075:                 return;
10076:             }
10077:         }
10078:     }
10079:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
10080:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
10081:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
10082:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
10083:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
10084:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
10085:     $r->print('
10086:     <p>
10087: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
10088: 	      '<a href="'.$orig.'">','</a>').'
10089:     </p>
10090:     <p>
10091: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
10092: 	      '<a href="'.$corrected.'">','</a>').'
10093:     </p>
10094:     <p>
10095: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
10096: 	      '<a href="'.$skipped.'">','</a>').'
10097:     </p>
10098: ');
10099:     return '';
10100: }
10101: 
10102: sub checkscantron_results {
10103:     my ($r,$symb) = @_;
10104:     if (!$symb) {return '';}
10105:     my $cid = $env{'request.course.id'};
10106:     my %lettdig = &Apache::lonnet::letter_to_digits();
10107:     my $numletts = scalar(keys(%lettdig));
10108:     my $cnum = $env{'course.'.$cid.'.num'};
10109:     my $cdom = $env{'course.'.$cid.'.domain'};
10110:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10111:     my %record;
10112:     my %scantron_config =
10113:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10114:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10115:     my ($scanlines,$scan_data)=&scantron_getfile();
10116:     my $classlist=&Apache::loncoursedata::get_classlist();
10117:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10118:     my $navmap=Apache::lonnavmaps::navmap->new();
10119:     unless (ref($navmap)) {
10120:         $r->print(&navmap_errormsg());
10121:         return '';
10122:     }
10123:     my $map=$navmap->getResourceByUrl($sequence);
10124:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10125:         %grader_randomlists_by_symb,%orderedforcode);
10126:     if (ref($map)) { 
10127:         $randomorder=$map->randomorder();
10128:         $randompick=$map->randompick();
10129:     }
10130:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10131:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10132:     if ($nav_error) {
10133:         $r->print(&navmap_errormsg());
10134:         return '';
10135:     }
10136:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10137:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10138:     my ($uname,$udom);
10139:     my (%scandata,%lastname,%bylast);
10140:     $r->print('
10141: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10142: 
10143:     my @delayqueue;
10144:     my %completedstudents;
10145: 
10146:     my $count=&get_todo_count($scanlines,$scan_data);
10147:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10148:     my ($username,$domain,$started);
10149:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10150:     if ($nav_error) {
10151:         $r->print(&navmap_errormsg());
10152:         return '';
10153:     }
10154: 
10155:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10156:     my $start=&Time::HiRes::time();
10157:     my $i=-1;
10158: 
10159:     while ($i<$scanlines->{'count'}) {
10160:         ($username,$domain,$uname)=('','','');
10161:         $i++;
10162:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10163:         if ($line=~/^[\s\cz]*$/) { next; }
10164:         if ($started) {
10165:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10166:         }
10167:         $started=1;
10168:         my $scan_record=
10169:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10170:                                                      $scan_data);
10171:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10172:                                               \%idmap,$i)) {
10173:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10174:                                 'Unable to find a student that matches',1);
10175:             next;
10176:         }
10177:         if (exists $completedstudents{$uname}) {
10178:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10179:                                 'Student '.$uname.' has multiple sheets',2);
10180:             next;
10181:         }
10182:         my $pid = $scan_record->{'scantron.ID'};
10183:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10184:         push(@{$bylast{$lastname{$pid}}},$pid);
10185:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10186:         my $user = $uname.':'.$usec;
10187:         ($username,$domain)=split(/:/,$uname);
10188: 
10189:         my $scancode;
10190:         if ((exists($scan_record->{'scantron.CODE'})) &&
10191:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10192:             $scancode = $scan_record->{'scantron.CODE'};
10193:         } else {
10194:             $scancode = '';
10195:         }
10196: 
10197:         my @mapresources = @resources;
10198:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10199:         my %respnumlookup=();
10200:         my %startline=();
10201:         if ($randomorder || $randompick) {
10202:             @mapresources =
10203:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10204:                              \%orderedforcode);
10205:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10206:                                              $scan_record,\@master_seq,\%symb_to_resource,
10207:                                              \%grader_partids_by_symb,\%orderedforcode,
10208:                                              \%respnumlookup,\%startline);
10209:             if ($randompick && $total) {
10210:                 $lastpos = $total*$scantron_config{'Qlength'};
10211:             }
10212:         }
10213:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10214:         chomp($scandata{$pid});
10215:         $scandata{$pid} =~ s/\r$//;
10216: 
10217:         my $counter = -1;
10218:         foreach my $resource (@mapresources) {
10219:             my $parts;
10220:             my $ressymb = $resource->symb();
10221:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10222:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10223:                 my $currcode;
10224:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10225:                     $currcode = $scancode;
10226:                 }
10227:                 (my $analysis,$parts) =
10228:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10229:                                               $username,$domain,undef,
10230:                                               $bubbles_per_row,$currcode);
10231:             } else {
10232:                 $parts = $grader_partids_by_symb{$ressymb};
10233:             }
10234:             ($counter,my $recording) =
10235:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10236:                                          $scandata{$pid},$parts,
10237:                                          \%scantron_config,\%lettdig,$numletts,
10238:                                          $randomorder,$randompick,
10239:                                          \%respnumlookup,\%startline);
10240:             $record{$pid} .= $recording;
10241:         }
10242:     }
10243:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10244:     $r->print('<br />');
10245:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10246:     $passed = 0;
10247:     $failed = 0;
10248:     $numstudents = 0;
10249:     foreach my $last (sort(keys(%bylast))) {
10250:         if (ref($bylast{$last}) eq 'ARRAY') {
10251:             foreach my $pid (sort(@{$bylast{$last}})) {
10252:                 my $showscandata = $scandata{$pid};
10253:                 my $showrecord = $record{$pid};
10254:                 $showscandata =~ s/\s/&nbsp;/g;
10255:                 $showrecord =~ s/\s/&nbsp;/g;
10256:                 if ($scandata{$pid} eq $record{$pid}) {
10257:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10258:                     $okstudents .= '<tr class="'.$css_class.'">'.
10259: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10260: '</tr>'."\n".
10261: '<tr class="'.$css_class.'">'."\n".
10262: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10263:                     $passed ++;
10264:                 } else {
10265:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10266:                     $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".
10267: '</tr>'."\n".
10268: '<tr class="'.$css_class.'">'."\n".
10269: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10270: '</tr>'."\n";
10271:                     $failed ++;
10272:                 }
10273:                 $numstudents ++;
10274:             }
10275:         }
10276:     }
10277:     $r->print(
10278:         '<p>'
10279:        .&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).',
10280:             '<b>',
10281:             $numstudents,
10282:             '</b>',
10283:             $env{'form.scantron_maxbubble'})
10284:        .'</p>'
10285:     );
10286:     $r->print('<p>'
10287:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10288:              .'<br />'
10289:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10290:              .'</p>'
10291:     );
10292:     if ($passed) {
10293:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10294:         $r->print(&Apache::loncommon::start_data_table()."\n".
10295:                  &Apache::loncommon::start_data_table_header_row()."\n".
10296:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10297:                  &Apache::loncommon::end_data_table_header_row()."\n".
10298:                  $okstudents."\n".
10299:                  &Apache::loncommon::end_data_table().'<br />');
10300:     }
10301:     if ($failed) {
10302:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10303:         $r->print(&Apache::loncommon::start_data_table()."\n".
10304:                  &Apache::loncommon::start_data_table_header_row()."\n".
10305:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10306:                  &Apache::loncommon::end_data_table_header_row()."\n".
10307:                  $badstudents."\n".
10308:                  &Apache::loncommon::end_data_table()).'<br />'.
10309:                  &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.');  
10310:     }
10311:     $r->print('</form><br />');
10312:     return;
10313: }
10314: 
10315: sub verify_scantron_grading {
10316:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10317:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10318:         $respnumlookup,$startline) = @_;
10319:     my ($record,%expected,%startpos);
10320:     return ($counter,$record) if (!ref($resource));
10321:     return ($counter,$record) if (!$resource->is_problem());
10322:     my $symb = $resource->symb();
10323:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10324:     foreach my $part_id (@{$partids}) {
10325:         $counter ++;
10326:         $expected{$part_id} = 0;
10327:         my $respnum = $counter;
10328:         if ($randomorder || $randompick) {
10329:             $respnum = $respnumlookup->{$counter};
10330:             $startpos{$part_id} = $startline->{$counter} + 1;
10331:         } else {
10332:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10333:         }
10334:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10335:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10336:             foreach my $item (@sub_lines) {
10337:                 $expected{$part_id} += $item;
10338:             }
10339:         } else {
10340:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10341:         }
10342:     }
10343:     if ($symb) {
10344:         my %recorded;
10345:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10346:         if ($returnhash{'version'}) {
10347:             my %lasthash=();
10348:             my $version;
10349:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10350:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10351:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10352:                 }
10353:             }
10354:             foreach my $key (keys(%lasthash)) {
10355:                 if ($key =~ /\.scantron$/) {
10356:                     my $value = &unescape($lasthash{$key});
10357:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10358:                     if ($value eq '') {
10359:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10360:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10361:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10362:                             }
10363:                         }
10364:                     } else {
10365:                         my @tocheck;
10366:                         my @items = split(//,$value);
10367:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10368:                             ($scantron_config->{'Qon'} eq 'number')) {
10369:                             if (@items < $expected{$part_id}) {
10370:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10371:                                 my @singles = split(//,$fragment);
10372:                                 foreach my $pos (@singles) {
10373:                                     if ($pos eq ' ') {
10374:                                         push(@tocheck,$pos);
10375:                                     } else {
10376:                                         my $next = shift(@items);
10377:                                         push(@tocheck,$next);
10378:                                     }
10379:                                 }
10380:                             } else {
10381:                                 @tocheck = @items;
10382:                             }
10383:                             foreach my $letter (@tocheck) {
10384:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10385:                                     if ($letter !~ /^[A-J]$/) {
10386:                                         $letter = $scantron_config->{'Qoff'};
10387:                                     }
10388:                                     $recorded{$part_id} .= $letter;
10389:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10390:                                     my $digit;
10391:                                     if ($letter !~ /^[A-J]$/) {
10392:                                         $digit = $scantron_config->{'Qoff'};
10393:                                     } else {
10394:                                         $digit = $lettdig->{$letter};
10395:                                     }
10396:                                     $recorded{$part_id} .= $digit;
10397:                                 }
10398:                             }
10399:                         } else {
10400:                             @tocheck = @items;
10401:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10402:                                 my $curr_sub = shift(@tocheck);
10403:                                 my $digit;
10404:                                 if ($curr_sub =~ /^[A-J]$/) {
10405:                                     $digit = $lettdig->{$curr_sub}-1;
10406:                                 }
10407:                                 if ($curr_sub eq 'J') {
10408:                                     $digit += scalar($numletts);
10409:                                 }
10410:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10411:                                     if ($j == $digit) {
10412:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10413:                                     } else {
10414:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10415:                                     }
10416:                                 }
10417:                             }
10418:                         }
10419:                     }
10420:                 }
10421:             }
10422:         }
10423:         foreach my $part_id (@{$partids}) {
10424:             if ($recorded{$part_id} eq '') {
10425:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10426:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10427:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10428:                     }
10429:                 }
10430:             }
10431:             $record .= $recorded{$part_id};
10432:         }
10433:     }
10434:     return ($counter,$record);
10435: }
10436: 
10437: #-------- end of section for handling grading scantron forms -------
10438: #
10439: #-------------------------------------------------------------------
10440: 
10441: #-------------------------- Menu interface -------------------------
10442: #
10443: #--- Href with symb and command ---
10444: 
10445: sub href_symb_cmd {
10446:     my ($symb,$cmd)=@_;
10447:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10448: }
10449: 
10450: sub grading_menu {
10451:     my ($request,$symb) = @_;
10452:     if (!$symb) {return '';}
10453: 
10454:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10455:                   'command'=>'individual');
10456:     
10457:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10458: 
10459:     $fields{'command'}='ungraded';
10460:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10461: 
10462:     $fields{'command'}='table';
10463:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10464: 
10465:     $fields{'command'}='all_for_one';
10466:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10467: 
10468:     $fields{'command'}='downloadfilesselect';
10469:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10470: 
10471:     $fields{'command'} = 'csvform';
10472:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10473:     
10474:     $fields{'command'} = 'processclicker';
10475:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10476:     
10477:     $fields{'command'} = 'scantron_selectphase';
10478:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10479: 
10480:     $fields{'command'} = 'initialverifyreceipt';
10481:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10482: 
10483:     my %permissions;
10484:     if ($perm{'mgr'}) {
10485:         $permissions{'either'} = 'F';
10486:         $permissions{'mgr'} = 'F';
10487:     }
10488:     if ($perm{'vgr'}) {
10489:         $permissions{'either'} = 'F';
10490:         $permissions{'vgr'} = 'F';
10491:     }
10492: 
10493:     my @menu = ({	categorytitle=>'Hand Grading',
10494:             items =>[
10495:                         {	linktext => 'Select individual students to grade',
10496:                     		url => $url1a,
10497:                     		permission => $permissions{'either'},
10498:                     		icon => 'grade_students.png',
10499:                     		linktitle => 'Grade current resource for a selection of students.'
10500:                         }, 
10501:                         {       linktext => 'Grade ungraded submissions',
10502:                                 url => $url1b,
10503:                                 permission => $permissions{'either'},
10504:                                 icon => 'ungrade_sub.png',
10505:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10506:                         },
10507: 
10508:                         {       linktext => 'Grading table',
10509:                                 url => $url1c,
10510:                                 permission => $permissions{'either'},
10511:                                 icon => 'grading_table.png',
10512:                                 linktitle => 'Grade current resource for all students.'
10513:                         },
10514:                         {       linktext => 'Grade page/folder for one student',
10515:                                 url => $url1d,
10516:                                 permission => $permissions{'either'},
10517:                                 icon => 'grade_PageFolder.png',
10518:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10519:                         },
10520:                         {       linktext => 'Download submissions',
10521:                                 url => $url1e,
10522:                                 permission => $permissions{'either'},
10523:                                 icon => 'download_sub.png',
10524:                                 linktitle => 'Download all students submissions.'
10525:                         }]},
10526:                          { categorytitle=>'Automated Grading',
10527:                items =>[
10528: 
10529:                 	    {	linktext => 'Upload Scores',
10530:                     		url => $url2,
10531:                     		permission => $permissions{'mgr'},
10532:                     		icon => 'uploadscores.png',
10533:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10534:                 	    },
10535:                 	    {	linktext => 'Process Clicker',
10536:                     		url => $url3,
10537:                     		permission => $permissions{'mgr'},
10538:                     		icon => 'addClickerInfoFile.png',
10539:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10540:                 	    },
10541:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10542:                     		url => $url4,
10543:                     		permission => $permissions{'mgr'},
10544:                     		icon => 'bubblesheet.png',
10545:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10546:                 	    },
10547:                             {   linktext => 'Verify Receipt Number',
10548:                                 url => $url5,
10549:                                 permission => $permissions{'either'},
10550:                                 icon => 'receipt_number.png',
10551:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10552:                             }
10553: 
10554:                     ]
10555:             });
10556: 
10557:     # Create the menu
10558:     my $Str;
10559:     $Str .= '<form method="post" action="" name="gradingMenu">';
10560:     $Str .= '<input type="hidden" name="command" value="" />'.
10561:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10562: 
10563:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10564:     return $Str;    
10565: }
10566: 
10567: sub ungraded {
10568:     my ($request)=@_;
10569:     &submit_options($request);
10570: }
10571: 
10572: sub submit_options_sequence {
10573:     my ($request,$symb) = @_;
10574:     if (!$symb) {return '';}
10575:     &commonJSfunctions($request);
10576:     my $result;
10577: 
10578:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10579:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10580:     $result.=&selectfield(0).
10581:             '<input type="hidden" name="command" value="pickStudentPage" />
10582:             <div>
10583:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10584:             </div>
10585:         </div>
10586:   </form>';
10587:     return $result;
10588: }
10589: 
10590: sub submit_options_table {
10591:     my ($request,$symb) = @_;
10592:     if (!$symb) {return '';}
10593:     &commonJSfunctions($request);
10594:     my $is_tool = ($symb =~ /ext\.tool$/);
10595:     my $result;
10596: 
10597:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10598:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10599: 
10600:     $result.=&selectfield(1,$is_tool).
10601:             '<input type="hidden" name="command" value="viewgrades" />
10602:             <div>
10603:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10604:             </div>
10605:         </div>
10606:   </form>';
10607:     return $result;
10608: }
10609: 
10610: sub submit_options_download {
10611:     my ($request,$symb) = @_;
10612:     if (!$symb) {return '';}
10613: 
10614:     my $res_error;
10615:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10616:         &response_type($symb,\$res_error);
10617:     if ($res_error) {
10618:         $request->print(&mt('An error occurred retrieving response types'));
10619:         return;
10620:     }
10621:     unless ($numessay) {
10622:         $request->print(&mt('No essayresponse items found'));
10623:         return;
10624:     }
10625:     my $table;
10626:     if (ref($partlist) eq 'ARRAY') {
10627:         if (scalar(@$partlist) > 1 ) {
10628:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10629:         }
10630:     }
10631: 
10632:     my $is_tool = ($symb =~ /ext\.tool$/);
10633:     &commonJSfunctions($request);
10634: 
10635:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10636:                $table."\n".
10637:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10638:     $result.='
10639: <h2>
10640:   '.&mt('Select Students for whom to Download Submissions').'
10641: </h2>'.&selectfield(1,$is_tool).'
10642:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10643:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10644:             </div>
10645:           </div>
10646: 
10647: 
10648:   </form>';
10649:     return $result;
10650: }
10651: 
10652: #--- Displays the submissions first page -------
10653: sub submit_options {
10654:     my ($request,$symb) = @_;
10655:     if (!$symb) {return '';}
10656: 
10657:     my $is_tool = ($symb =~ /ext\.tool$/);
10658:     &commonJSfunctions($request);
10659:     my $result;
10660: 
10661:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10662: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10663:     $result.=&selectfield(1,$is_tool).'
10664:                 <input type="hidden" name="command" value="submission" /> 
10665: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10666:             </div>
10667:           </div>
10668:   </form>';
10669:     return $result;
10670: }
10671: 
10672: sub selectfield {
10673:    my ($full,$is_tool)=@_;
10674:    my %options;
10675:    if ($is_tool) {
10676:        %options =
10677:            (&transtatus_options,
10678:             'select_form_order' => ['yes','incorrect','all']);
10679:    } else {
10680:        %options = 
10681:            (&substatus_options,
10682:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10683:    }
10684: 
10685:   #
10686:   # PrepareClasslist() needs to be called to avoid getting a sections list
10687:   # for a different course from the @Sections global in lonstatistics.pm, 
10688:   # populated by an earlier request.
10689:   #
10690:    &Apache::lonstatistics::PrepareClasslist();
10691: 
10692:    my $result='<div class="LC_columnSection">
10693:   
10694:     <fieldset>
10695:       <legend>
10696:        '.&mt('Sections').'
10697:       </legend>
10698:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10699:     </fieldset>
10700:   
10701:     <fieldset>
10702:       <legend>
10703:         '.&mt('Groups').'
10704:       </legend>
10705:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10706:     </fieldset>
10707:   
10708:     <fieldset>
10709:       <legend>
10710:         '.&mt('Access Status').'
10711:       </legend>
10712:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10713:     </fieldset>';
10714:     if ($full) {
10715:         my $heading = &mt('Submission Status');
10716:         if ($is_tool) {
10717:             $heading = &mt('Transaction Status');
10718:         }
10719:         $result.='
10720:     <fieldset>
10721:       <legend>
10722:         '.$heading.'
10723:       </legend>'.
10724:        &Apache::loncommon::select_form('all','submitonly',\%options).
10725:    '</fieldset>';
10726:     }
10727:     $result.='</div><br />';
10728:     return $result;
10729: }
10730: 
10731: sub substatus_options {
10732:     return &Apache::lonlocal::texthash(
10733:                                       'yes'       => 'with submissions',
10734:                                       'queued'    => 'in grading queue',
10735:                                       'graded'    => 'with ungraded submissions',
10736:                                       'incorrect' => 'with incorrect submissions',
10737:                                       'all'       => 'with any status',
10738:                                       );
10739: }
10740: 
10741: sub transtatus_options {
10742:     return &Apache::lonlocal::texthash(
10743:                                        'yes'       => 'with score transactions',
10744:                                        'incorrect' => 'with less than full credit',
10745:                                        'all'       => 'with any status',
10746:                                       );
10747: }
10748: 
10749: sub reset_perm {
10750:     undef(%perm);
10751: }
10752: 
10753: sub init_perm {
10754:     &reset_perm();
10755:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10756: 
10757: 	my $scope = $env{'request.course.id'};
10758: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10759: 
10760: 	    $scope .= '/'.$env{'request.course.sec'};
10761: 	    if ( $perm{$test_perm}=
10762: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10763: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10764: 	    } else {
10765: 		delete($perm{$test_perm});
10766: 	    }
10767: 	}
10768:     }
10769: }
10770: 
10771: sub init_old_essays {
10772:     my ($symb,$apath,$adom,$aname) = @_;
10773:     if ($symb ne '') {
10774:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10775:         if (keys(%essays) > 0) {
10776:             $old_essays{$symb} = \%essays;
10777:         }
10778:     }
10779:     return;
10780: }
10781: 
10782: sub reset_old_essays {
10783:     undef(%old_essays);
10784: }
10785: 
10786: sub gather_clicker_ids {
10787:     my %clicker_ids;
10788: 
10789:     my $classlist = &Apache::loncoursedata::get_classlist();
10790: 
10791:     # Set up a couple variables.
10792:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10793:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10794:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10795: 
10796:     foreach my $student (keys(%$classlist)) {
10797:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10798:         my $username = $classlist->{$student}->[$username_idx];
10799:         my $domain   = $classlist->{$student}->[$domain_idx];
10800:         my $clickers =
10801: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10802:         foreach my $id (split(/\,/,$clickers)) {
10803:             $id=~s/^[\#0]+//;
10804:             $id=~s/[\-\:]//g;
10805:             if (exists($clicker_ids{$id})) {
10806: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10807:             } else {
10808: 		$clicker_ids{$id}=$username.':'.$domain;
10809:             }
10810:         }
10811:     }
10812:     return %clicker_ids;
10813: }
10814: 
10815: sub gather_adv_clicker_ids {
10816:     my %clicker_ids;
10817:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10818:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10819:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10820:     foreach my $element (sort(keys(%coursepersonnel))) {
10821:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10822:             my ($puname,$pudom)=split(/\:/,$person);
10823:             my $clickers =
10824: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10825:             foreach my $id (split(/\,/,$clickers)) {
10826: 		$id=~s/^[\#0]+//;
10827:                 $id=~s/[\-\:]//g;
10828: 		if (exists($clicker_ids{$id})) {
10829: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10830: 		} else {
10831: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10832: 		}
10833:             }
10834:         }
10835:     }
10836:     return %clicker_ids;
10837: }
10838: 
10839: sub clicker_grading_parameters {
10840:     return ('gradingmechanism' => 'scalar',
10841:             'upfiletype' => 'scalar',
10842:             'specificid' => 'scalar',
10843:             'pcorrect' => 'scalar',
10844:             'pincorrect' => 'scalar');
10845: }
10846: 
10847: sub process_clicker {
10848:     my ($r,$symb)=@_;
10849:     if (!$symb) {return '';}
10850:     my $result=&checkforfile_js();
10851:     $result.=&Apache::loncommon::start_data_table().
10852:              &Apache::loncommon::start_data_table_header_row().
10853:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10854:              &Apache::loncommon::end_data_table_header_row().
10855:              &Apache::loncommon::start_data_table_row()."<td>\n";
10856: # Attempt to restore parameters from last session, set defaults if not present
10857:     my %Saveable_Parameters=&clicker_grading_parameters();
10858:     &Apache::loncommon::restore_course_settings('grades_clicker',
10859:                                                  \%Saveable_Parameters);
10860:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10861:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10862:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10863:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10864: 
10865:     my %checked;
10866:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10867:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10868:           $checked{$gradingmechanism}=' checked="checked"';
10869:        }
10870:     }
10871: 
10872:     my $upload=&mt("Evaluate File");
10873:     my $type=&mt("Type");
10874:     my $attendance=&mt("Award points just for participation");
10875:     my $personnel=&mt("Correctness determined from response by course personnel");
10876:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10877:     my $given=&mt("Correctness determined from given list of answers").' '.
10878:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10879:     my $pcorrect=&mt("Percentage points for correct solution");
10880:     my $pincorrect=&mt("Percentage points for incorrect solution");
10881:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10882: 						   {'iclicker' => 'i>clicker',
10883:                                                     'interwrite' => 'interwrite PRS',
10884:                                                     'turning' => 'Turning Technologies'});
10885:     $symb = &Apache::lonenc::check_encrypt($symb);
10886:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10887: function sanitycheck() {
10888: // Accept only integer percentages
10889:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10890:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10891: // Find out grading choice
10892:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10893:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10894:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10895:       }
10896:    }
10897: // By default, new choice equals user selection
10898:    newgradingchoice=gradingchoice;
10899: // Not good to give more points for false answers than correct ones
10900:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10901:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10902:    }
10903: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10904:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10905:       document.forms.gradesupload.pcorrect.value=100;
10906:       document.forms.gradesupload.pincorrect.value=100;
10907:    }
10908: // If the values are different, cannot be attendance only
10909:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10910:        (gradingchoice=='attendance')) {
10911:        newgradingchoice='personnel';
10912:    }
10913: // Change grading choice to new one
10914:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10915:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10916:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10917:       } else {
10918:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10919:       }
10920:    }
10921: // Remember the old state
10922:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10923: }
10924: ENDUPFORM
10925:     $result.= <<ENDUPFORM;
10926: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10927: <input type="hidden" name="symb" value="$symb" />
10928: <input type="hidden" name="command" value="processclickerfile" />
10929: <input type="file" name="upfile" size="50" />
10930: <br /><label>$type: $selectform</label>
10931: ENDUPFORM
10932:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10933:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10934:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10935: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10936: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10937: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10938: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10939: <br />&nbsp;&nbsp;&nbsp;
10940: <input type="text" name="givenanswer" size="50" />
10941: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10942: ENDGRADINGFORM
10943:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10944:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10945:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10946: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10947: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10948: </form>
10949: ENDPERCFORM
10950:     $result.='</td>'.
10951:              &Apache::loncommon::end_data_table_row().
10952:              &Apache::loncommon::end_data_table();
10953:     return $result;
10954: }
10955: 
10956: sub process_clicker_file {
10957:     my ($r,$symb) = @_;
10958:     if (!$symb) {return '';}
10959: 
10960:     my %Saveable_Parameters=&clicker_grading_parameters();
10961:     &Apache::loncommon::store_course_settings('grades_clicker',
10962:                                               \%Saveable_Parameters);
10963:     my $result='';
10964:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10965: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10966: 	return $result;
10967:     }
10968:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10969:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10970:         return $result;
10971:     }
10972:     my $foundgiven=0;
10973:     if ($env{'form.gradingmechanism'} eq 'given') {
10974:         $env{'form.givenanswer'}=~s/^\s*//gs;
10975:         $env{'form.givenanswer'}=~s/\s*$//gs;
10976:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10977:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10978:         my @answers=split(/\,/,$env{'form.givenanswer'});
10979:         $foundgiven=$#answers+1;
10980:     }
10981:     my %clicker_ids=&gather_clicker_ids();
10982:     my %correct_ids;
10983:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10984: 	%correct_ids=&gather_adv_clicker_ids();
10985:     }
10986:     if ($env{'form.gradingmechanism'} eq 'specific') {
10987: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10988: 	   $correct_id=~tr/a-z/A-Z/;
10989: 	   $correct_id=~s/\s//gs;
10990: 	   $correct_id=~s/^[\#0]+//;
10991:            $correct_id=~s/[\-\:]//g;
10992:            if ($correct_id) {
10993: 	      $correct_ids{$correct_id}='specified';
10994:            }
10995:         }
10996:     }
10997:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10998: 	$result.=&mt('Score based on attendance only');
10999:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
11000:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
11001:     } else {
11002: 	my $number=0;
11003: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
11004: 	foreach my $id (sort(keys(%correct_ids))) {
11005: 	    $result.='<br /><tt>'.$id.'</tt> - ';
11006: 	    if ($correct_ids{$id} eq 'specified') {
11007: 		$result.=&mt('specified');
11008: 	    } else {
11009: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
11010: 		$result.=&Apache::loncommon::plainname($uname,$udom);
11011: 	    }
11012: 	    $number++;
11013: 	}
11014:         $result.="</p>\n";
11015:         if ($number==0) {
11016:             $result .=
11017:                  &Apache::lonhtmlcommon::confirm_success(
11018:                      &mt('No IDs found to determine correct answer'),1);
11019:             return $result;
11020:         }
11021:     }
11022:     if (length($env{'form.upfile'}) < 2) {
11023:         $result .=
11024:             &Apache::lonhtmlcommon::confirm_success(
11025:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
11026:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
11027:         return $result;
11028:     }
11029:     my $mimetype;
11030:     if ($env{'form.upfiletype'} eq 'iclicker') {
11031:         my $mm = new File::MMagic;
11032:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
11033:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
11034:             $result.= '<p>'.
11035:                 &Apache::lonhtmlcommon::confirm_success(
11036:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
11037:             return $result;
11038:         }
11039:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
11040:         $result .= '<p>'.
11041:             &Apache::lonhtmlcommon::confirm_success(
11042:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
11043:         return $result;
11044:     }
11045: 
11046: # Were able to get all the info needed, now analyze the file
11047: 
11048:     $result.=&Apache::loncommon::studentbrowser_javascript();
11049:     $symb = &Apache::lonenc::check_encrypt($symb);
11050:     $result.=&Apache::loncommon::start_data_table().
11051:              &Apache::loncommon::start_data_table_header_row().
11052:              '<th>'.&mt('Evaluate clicker file').'</th>'.
11053:              &Apache::loncommon::end_data_table_header_row().
11054:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
11055: <td>
11056: <form method="post" action="/adm/grades" name="clickeranalysis">
11057: <input type="hidden" name="symb" value="$symb" />
11058: <input type="hidden" name="command" value="assignclickergrades" />
11059: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
11060: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
11061: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
11062: ENDHEADER
11063:     if ($env{'form.gradingmechanism'} eq 'given') {
11064:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
11065:     } 
11066:     my %responses;
11067:     my @questiontitles;
11068:     my $errormsg='';
11069:     my $number=0;
11070:     if ($env{'form.upfiletype'} eq 'iclicker') {
11071:         if ($mimetype eq 'text/plain') {
11072:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
11073:         } elsif ($mimetype eq 'text/html') {
11074:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
11075:         }
11076:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
11077:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
11078:     } elsif ($env{'form.upfiletype'} eq 'turning') {
11079:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
11080:     }
11081:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
11082:              '<input type="hidden" name="number" value="'.$number.'" />'.
11083:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
11084:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
11085:              '<br />';
11086:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
11087:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
11088:        return $result;
11089:     } 
11090: # Remember Question Titles
11091: # FIXME: Possibly need delimiter other than ":"
11092:     for (my $i=0;$i<$number;$i++) {
11093:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
11094:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
11095:     }
11096:     my $correct_count=0;
11097:     my $student_count=0;
11098:     my $unknown_count=0;
11099: # Match answers with usernames
11100: # FIXME: Possibly need delimiter other than ":"
11101:     foreach my $id (keys(%responses)) {
11102:        if ($correct_ids{$id}) {
11103:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
11104:           $correct_count++;
11105:        } elsif ($clicker_ids{$id}) {
11106:           if ($clicker_ids{$id}=~/\,/) {
11107: # More than one user with the same clicker!
11108:              $result.="</td>".&Apache::loncommon::end_data_table_row().
11109:                            &Apache::loncommon::start_data_table_row()."<td>".
11110:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
11111:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11112:                            "<select name='multi".$id."'>";
11113:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
11114:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
11115:              }
11116:              $result.='</select>';
11117:              $unknown_count++;
11118:           } else {
11119: # Good: found one and only one user with the right clicker
11120:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
11121:              $student_count++;
11122:           }
11123:        } else {
11124:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11125:                            &Apache::loncommon::start_data_table_row()."<td>".
11126:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11127:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11128:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11129:                    "\n".&mt("Domain").": ".
11130:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11131:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11132:           $unknown_count++;
11133:        }
11134:     }
11135:     $result.='<hr />'.
11136:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11137:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11138:        if ($correct_count==0) {
11139:           $errormsg.="Found no correct answers for grading!";
11140:        } elsif ($correct_count>1) {
11141:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11142:        }
11143:     }
11144:     if ($number<1) {
11145:        $errormsg.="Found no questions.";
11146:     }
11147:     if ($errormsg) {
11148:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11149:     } else {
11150:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11151:     }
11152:     $result.='</form></td>'.
11153:              &Apache::loncommon::end_data_table_row().
11154:              &Apache::loncommon::end_data_table();
11155:     return $result;
11156: }
11157: 
11158: sub iclicker_eval {
11159:     my ($questiontitles,$responses)=@_;
11160:     my $number=0;
11161:     my $errormsg='';
11162:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11163:         my %components=&Apache::loncommon::record_sep($line);
11164:         my @entries=map {$components{$_}} (sort(keys(%components)));
11165: 	if ($entries[0] eq 'Question') {
11166: 	    for (my $i=3;$i<$#entries;$i+=6) {
11167: 		$$questiontitles[$number]=$entries[$i];
11168: 		$number++;
11169: 	    }
11170: 	}
11171: 	if ($entries[0]=~/^\#/) {
11172: 	    my $id=$entries[0];
11173: 	    my @idresponses;
11174: 	    $id=~s/^[\#0]+//;
11175: 	    for (my $i=0;$i<$number;$i++) {
11176: 		my $idx=3+$i*6;
11177:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11178: 		push(@idresponses,$entries[$idx]);
11179: 	    }
11180: 	    $$responses{$id}=join(',',@idresponses);
11181: 	}
11182:     }
11183:     return ($errormsg,$number);
11184: }
11185: 
11186: sub iclickerxml_eval {
11187:     my ($questiontitles,$responses)=@_;
11188:     my $number=0;
11189:     my $errormsg='';
11190:     my @state;
11191:     my %respbyid;
11192:     my $p = HTML::Parser->new
11193:     (
11194:         xml_mode => 1,
11195:         start_h =>
11196:             [sub {
11197:                  my ($tagname,$attr) = @_;
11198:                  push(@state,$tagname);
11199:                  if ("@state" eq "ssn p") {
11200:                      my $title = $attr->{qn};
11201:                      $title =~ s/(^\s+|\s+$)//g;
11202:                      $questiontitles->[$number]=$title;
11203:                  } elsif ("@state" eq "ssn p v") {
11204:                      my $id = $attr->{id};
11205:                      my $entry = $attr->{ans};
11206:                      $id=~s/^[\#0]+//;
11207:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11208:                      $respbyid{$id}[$number] = $entry;
11209:                  }
11210:             }, "tagname, attr"],
11211:          end_h =>
11212:                [sub {
11213:                    my ($tagname) = @_;
11214:                    if ("@state" eq "ssn p") {
11215:                        $number++;
11216:                    }
11217:                    pop(@state);
11218:                 }, "tagname"],
11219:     );
11220: 
11221:     $p->parse($env{'form.upfile'});
11222:     $p->eof;
11223:     foreach my $id (keys(%respbyid)) {
11224:         $responses->{$id}=join(',',@{$respbyid{$id}});
11225:     }
11226:     return ($errormsg,$number);
11227: }
11228: 
11229: sub interwrite_eval {
11230:     my ($questiontitles,$responses)=@_;
11231:     my $number=0;
11232:     my $errormsg='';
11233:     my $skipline=1;
11234:     my $questionnumber=0;
11235:     my %idresponses=();
11236:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11237:         my %components=&Apache::loncommon::record_sep($line);
11238:         my @entries=map {$components{$_}} (sort(keys(%components)));
11239:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11240:         if ($entries[1] eq 'Response') { $skipline=1; }
11241:         next if $skipline;
11242:         if ($entries[0]!=$questionnumber) {
11243:            $questionnumber=$entries[0];
11244:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11245:            $number++;
11246:         }
11247:         my $id=$entries[4];
11248:         $id=~s/^[\#0]+//;
11249:         $id=~s/^v\d*\://i;
11250:         $id=~s/[\-\:]//g;
11251:         $idresponses{$id}[$number]=$entries[6];
11252:     }
11253:     foreach my $id (keys(%idresponses)) {
11254:        $$responses{$id}=join(',',@{$idresponses{$id}});
11255:        $$responses{$id}=~s/^\s*\,//;
11256:     }
11257:     return ($errormsg,$number);
11258: }
11259: 
11260: sub turning_eval {
11261:     my ($questiontitles,$responses)=@_;
11262:     my $number=0;
11263:     my $errormsg='';
11264:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11265:         my %components=&Apache::loncommon::record_sep($line);
11266:         my @entries=map {$components{$_}} (sort(keys(%components)));
11267:         if ($#entries>$number) { $number=$#entries; }
11268:         my $id=$entries[0];
11269:         my @idresponses;
11270:         $id=~s/^[\#0]+//;
11271:         unless ($id) { next; }
11272:         for (my $idx=1;$idx<=$#entries;$idx++) {
11273:             $entries[$idx]=~s/\,/\;/g;
11274:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11275:             push(@idresponses,$entries[$idx]);
11276:         }
11277:         $$responses{$id}=join(',',@idresponses);
11278:     }
11279:     for (my $i=1; $i<=$number; $i++) {
11280:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11281:     }
11282:     return ($errormsg,$number);
11283: }
11284: 
11285: 
11286: sub assign_clicker_grades {
11287:     my ($r,$symb) = @_;
11288:     if (!$symb) {return '';}
11289: # See which part we are saving to
11290:     my $res_error;
11291:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11292:     if ($res_error) {
11293:         return &navmap_errormsg();
11294:     }
11295: # FIXME: This should probably look for the first handgradeable part
11296:     my $part=$$partlist[0];
11297: # Start screen output
11298:     my $result = &Apache::loncommon::start_data_table().
11299:                  &Apache::loncommon::start_data_table_header_row().
11300:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11301:                  &Apache::loncommon::end_data_table_header_row().
11302:                  &Apache::loncommon::start_data_table_row().'<td>';
11303: # Get correct result
11304: # FIXME: Possibly need delimiter other than ":"
11305:     my @correct=();
11306:     my $gradingmechanism=$env{'form.gradingmechanism'};
11307:     my $number=$env{'form.number'};
11308:     if ($gradingmechanism ne 'attendance') {
11309:        foreach my $key (keys(%env)) {
11310:           if ($key=~/^form\.correct\:/) {
11311:              my @input=split(/\,/,$env{$key});
11312:              for (my $i=0;$i<=$#input;$i++) {
11313:                  if (($correct[$i]) && ($input[$i]) &&
11314:                      ($correct[$i] ne $input[$i])) {
11315:                     $result.='<br /><span class="LC_warning">'.
11316:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11317:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11318:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11319:                     $correct[$i]=$input[$i];
11320:                  }
11321:              }
11322:           }
11323:        }
11324:        for (my $i=0;$i<$number;$i++) {
11325:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11326:              $result.='<br /><span class="LC_error">'.
11327:                       &mt('No correct result given for question "[_1]"!',
11328:                           $env{'form.question:'.$i}).'</span>';
11329:           }
11330:        }
11331:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11332:     }
11333: # Start grading
11334:     my $pcorrect=$env{'form.pcorrect'};
11335:     my $pincorrect=$env{'form.pincorrect'};
11336:     my $storecount=0;
11337:     my %users=();
11338:     foreach my $key (keys(%env)) {
11339:        my $user='';
11340:        if ($key=~/^form\.student\:(.*)$/) {
11341:           $user=$1;
11342:        }
11343:        if ($key=~/^form\.unknown\:(.*)$/) {
11344:           my $id=$1;
11345:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11346:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11347:           } elsif ($env{'form.multi'.$id}) {
11348:              $user=$env{'form.multi'.$id};
11349:           }
11350:        }
11351:        if ($user) {
11352:           if ($users{$user}) {
11353:              $result.='<br /><span class="LC_warning">'.
11354:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11355:                       '</span><br />';
11356:           }
11357:           $users{$user}=1; 
11358:           my @answer=split(/\,/,$env{$key});
11359:           my $sum=0;
11360:           my $realnumber=$number;
11361:           for (my $i=0;$i<$number;$i++) {
11362:              if  ($correct[$i] eq '-') {
11363:                 $realnumber--;
11364:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11365:                 if ($gradingmechanism eq 'attendance') {
11366:                    $sum+=$pcorrect;
11367:                 } elsif ($correct[$i] eq '*') {
11368:                    $sum+=$pcorrect;
11369:                 } else {
11370: # We actually grade if correct or not
11371:                    my $increment=$pincorrect;
11372: # Special case: numerical answer "0"
11373:                    if ($correct[$i] eq '0') {
11374:                       if ($answer[$i]=~/^[0\.]+$/) {
11375:                          $increment=$pcorrect;
11376:                       }
11377: # General numerical answer, both evaluate to something non-zero
11378:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11379:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11380:                          $increment=$pcorrect;
11381:                       }
11382: # Must be just alphanumeric
11383:                    } elsif ($answer[$i] eq $correct[$i]) {
11384:                       $increment=$pcorrect;
11385:                    }
11386:                    $sum+=$increment;
11387:                 }
11388:              }
11389:           }
11390:           my $ave=$sum/(100*$realnumber);
11391: # Store
11392:           my ($username,$domain)=split(/\:/,$user);
11393:           my %grades=();
11394:           $grades{"resource.$part.solved"}='correct_by_override';
11395:           $grades{"resource.$part.awarded"}=$ave;
11396:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11397:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11398:                                                  $env{'request.course.id'},
11399:                                                  $domain,$username);
11400:           if ($returncode ne 'ok') {
11401:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11402:           } else {
11403:              $storecount++;
11404:           }
11405:        }
11406:     }
11407: # We are done
11408:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11409:              '</td>'.
11410:              &Apache::loncommon::end_data_table_row().
11411:              &Apache::loncommon::end_data_table();
11412:     return $result;
11413: }
11414: 
11415: sub navmap_errormsg {
11416:     return '<div class="LC_error">'.
11417:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11418:            &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>').
11419:            '</div>';
11420: }
11421: 
11422: sub startpage {
11423:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11424:     my %args;
11425:     if ($onload) {
11426:          my %loaditems = (
11427:                         'onload' => $onload,
11428:                       );
11429:          $args{'add_entries'} = \%loaditems;
11430:     }
11431:     if ($nomenu) {
11432:         $args{'only_body'} = 1; 
11433:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11434:     } else {
11435:         if ($env{'request.course.id'}) { 
11436:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11437:         }
11438:         $args{'bread_crumbs'} = $crumbs;
11439:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11440:         if ($env{'request.course.id'}) {
11441:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11442:         }
11443:     }
11444:     unless ($nodisplayflag) {
11445:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11446:     }
11447: }
11448: 
11449: sub select_problem {
11450:     my ($r)=@_;
11451:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11452:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11453:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11454:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11455: }
11456: 
11457: sub handler {
11458:     my $request=$_[0];
11459:     &reset_caches();
11460:     if ($request->header_only) {
11461:         &Apache::loncommon::content_type($request,'text/html');
11462:         $request->send_http_header;
11463:         return OK;
11464:     }
11465:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11466: 
11467: # see what command we need to execute
11468: 
11469:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11470:     my $command=$commands[0];
11471: 
11472:     &init_perm();
11473:     if (!$env{'request.course.id'}) {
11474:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11475:                 ($command =~ /^scantronupload/)) {
11476:             # Not in a course.
11477:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11478:             return HTTP_NOT_ACCEPTABLE;
11479:         }
11480:     } elsif (!%perm) {
11481:         $request->internal_redirect('/adm/quickgrades');
11482:         return OK;
11483:     }
11484:     &Apache::loncommon::content_type($request,'text/html');
11485:     $request->send_http_header;
11486: 
11487:     if ($#commands > 0) {
11488: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11489:     }
11490: 
11491: # see what the symb is
11492: 
11493:     my $symb=$env{'form.symb'};
11494:     unless ($symb) {
11495:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11496:        $symb=&Apache::lonnet::symbread($url);
11497:     }
11498:     &Apache::lonenc::check_decrypt(\$symb);
11499: 
11500:     $ssi_error = 0;
11501:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11502: #
11503: # Not called from a resource, but inside a course
11504: #    
11505:         &startpage($request,undef,[],1,1);
11506:         &select_problem($request);
11507:     } else {
11508: 	if ($command eq 'submission' && $perm{'vgr'}) {
11509:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11510:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11511:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11512:                     &choose_task_version_form($symb,$env{'form.student'},
11513:                                               $env{'form.userdom'});
11514:             }
11515:             my $divforres;
11516:             if ($env{'form.student'} eq '') {
11517:                 $js .= &part_selector_js();
11518:                 $onload = "toggleParts('gradesub');";
11519:             } else {
11520:                 $divforres = 1;
11521:             }
11522:             my $head_extra = $js;
11523:             unless ($env{'form.vProb'} eq 'no') {
11524:                 my $csslinks = &Apache::loncommon::css_links($symb);
11525:                 if ($csslinks) {
11526:                     $head_extra .= "\n$csslinks";
11527:                 }
11528:             }
11529:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11530:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11531:             if ($versionform) {
11532:                 if ($divforres) {
11533:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11534:                 }
11535:                 $request->print($versionform);
11536:             }
11537: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11538:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11539:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11540:                 &choose_task_version_form($symb,$env{'form.student'},
11541:                                           $env{'form.userdom'},
11542:                                           $env{'form.inhibitmenu'});
11543:             my $head_extra = $js;
11544:             unless ($env{'form.vProb'} eq 'no') {
11545:                 my $csslinks = &Apache::loncommon::css_links($symb);
11546:                 if ($csslinks) {
11547:                     $head_extra .= "\n$csslinks";
11548:                 }
11549:             }
11550:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11551:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11552:             if ($versionform) {
11553:                 $request->print($versionform);
11554:             }
11555:             $request->print('<br clear="all" />');
11556:             $request->print(&show_previous_task_version($request,$symb));
11557: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11558:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11559:                                        {href=>'',text=>'Select student'}],1,1);
11560: 	    &pickStudentPage($request,$symb);
11561: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11562:             my $csslinks;
11563:             unless ($env{'form.vProb'} eq 'no') {
11564:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11565:             }
11566:             &startpage($request,$symb,
11567:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11568:                                        {href=>'',text=>'Select student'},
11569:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11570: 	    &displayPage($request,$symb);
11571: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11572:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11573:                                        {href=>'',text=>'Select student'},
11574:                                        {href=>'',text=>'Grade student'},
11575:                                        {href=>'',text=>'Store grades'}],1,1);
11576: 	    &updateGradeByPage($request,$symb);
11577: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11578:             my $csslinks;
11579:             unless ($env{'form.vProb'} eq 'no') {
11580:                 $csslinks = &Apache::loncommon::css_links($symb);
11581:             }
11582:             &startpage($request,$symb,[{href=>'',text=>'...'},
11583:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11584: 	    &processGroup($request,$symb);
11585: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11586:             &startpage($request,$symb);
11587: 	    $request->print(&grading_menu($request,$symb));
11588: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11589:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11590: 	    $request->print(&submit_options($request,$symb));
11591:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11592:             my $js = &part_selector_js();
11593:             my $onload = "toggleParts('gradesub');";
11594:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11595:                        undef,undef,undef,undef,undef,$js,$onload);
11596:             $request->print(&listStudents($request,$symb,'graded'));
11597:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11598:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11599:             $request->print(&submit_options_table($request,$symb));
11600:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11601:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11602:             $request->print(&submit_options_sequence($request,$symb));
11603: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11604:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11605: 	    $request->print(&viewgrades($request,$symb));
11606: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11607:             &startpage($request,$symb,[{href=>'',text=>'...'},
11608:                                        {href=>'',text=>'Store grades'}]);
11609: 	    $request->print(&processHandGrade($request,$symb));
11610: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11611:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11612:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11613:                                                                              text=>"Modify grades"},
11614:                                        {href=>'', text=>"Store grades"}]);
11615: 	    $request->print(&editgrades($request,$symb));
11616:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11617:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11618:             $request->print(&initialverifyreceipt($request,$symb));
11619: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11620:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11621:                                        {href=>'',text=>'Verification Result'}]);
11622: 	    $request->print(&verifyreceipt($request,$symb));
11623:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11624:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11625:             $request->print(&process_clicker($request,$symb));
11626:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11627:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11628:                                        {href=>'', text=>'Process clicker file'}]);
11629:             $request->print(&process_clicker_file($request,$symb));
11630:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11631:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11632:                                        {href=>'', text=>'Process clicker file'},
11633:                                        {href=>'', text=>'Store grades'}]);
11634:             $request->print(&assign_clicker_grades($request,$symb));
11635: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11636:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11637: 	    $request->print(&upcsvScores_form($request,$symb));
11638: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11639:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11640: 	    $request->print(&csvupload($request,$symb));
11641: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11642:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11643: 	    $request->print(&csvuploadmap($request,$symb));
11644: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11645: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11646:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11647: 		$request->print(&csvuploadoptions($request,$symb));
11648: 	    } else {
11649: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11650: 		    $env{'form.upfile_associate'} = 'reverse';
11651: 		} else {
11652: 		    $env{'form.upfile_associate'} = 'forward';
11653: 		}
11654:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11655: 		$request->print(&csvuploadmap($request,$symb));
11656: 	    }
11657: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11658:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11659: 	    $request->print(&csvuploadassign($request,$symb));
11660: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11661:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11662:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11663: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11664:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11665:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11666:  	    $request->print(&scantron_do_warning($request,$symb));
11667: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11668:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11669: 	    $request->print(&scantron_validate_file($request,$symb));
11670: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11671:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11672: 	    $request->print(&scantron_process_students($request,$symb));
11673:  	} elsif ($command eq 'scantronupload' && 
11674:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11675:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11676:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11677:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11678:  	} elsif ($command eq 'scantronupload_save' &&
11679:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11680:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11681:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11682:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11683:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11684:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11685:         } elsif ($command eq 'scantronupload_delete' &&
11686:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11687:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11688:             &scantron_upload_delete($request,$symb);
11689:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11690:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11691:             $request->print(&checkscantron_results($request,$symb));
11692:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11693:             my $js = &part_selector_js();
11694:             my $onload = "toggleParts('gradingMenu');";
11695:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11696:                        undef,undef,undef,undef,undef,$js,$onload);
11697:             $request->print(&submit_options_download($request,$symb));
11698:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11699:             &startpage($request,$symb,
11700:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11701:     {href=>'', text=>'Download submitted files'}],
11702:                undef,undef,undef,undef,undef,undef,undef,1);
11703:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11704:             &submit_download_link($request,$symb);
11705: 	} elsif ($command) {
11706:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11707: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11708: 	}
11709:     }
11710:     if ($ssi_error) {
11711: 	&ssi_print_error($request);
11712:     }
11713:     if ($env{'form.inhibitmenu'}) {
11714:         $request->print(&Apache::loncommon::end_page());
11715:     } elsif ($env{'request.course.id'}) {
11716:         &Apache::lonquickgrades::endGradeScreen($request);
11717:     }
11718:     &reset_caches();
11719:     return OK;
11720: }
11721: 
11722: 1;
11723: 
11724: __END__;
11725: 
11726: 
11727: =head1 NAME
11728: 
11729: Apache::grades
11730: 
11731: =head1 SYNOPSIS
11732: 
11733: Handles the viewing of grades.
11734: 
11735: This is part of the LearningOnline Network with CAPA project
11736: described at http://www.lon-capa.org.
11737: 
11738: =head1 OVERVIEW
11739: 
11740: Do an ssi with retries:
11741: While I'd love to factor out this with the version in lonprintout,
11742: 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
11743: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11744: 
11745: At least the logic that drives this has been pulled out into loncommon.
11746: 
11747: 
11748: 
11749: ssi_with_retries - Does the server side include of a resource.
11750:                      if the ssi call returns an error we'll retry it up to
11751:                      the number of times requested by the caller.
11752:                      If we still have a problem, no text is appended to the
11753:                      output and we set some global variables.
11754:                      to indicate to the caller an SSI error occurred.  
11755:                      All of this is supposed to deal with the issues described
11756:                      in LON-CAPA BZ 5631 see:
11757:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11758:                      by informing the user that this happened.
11759: 
11760: Parameters:
11761:   resource   - The resource to include.  This is passed directly, without
11762:                interpretation to lonnet::ssi.
11763:   form       - The form hash parameters that guide the interpretation of the resource
11764:                
11765:   retries    - Number of retries allowed before giving up completely.
11766: Returns:
11767:   On success, returns the rendered resource identified by the resource parameter.
11768: Side Effects:
11769:   The following global variables can be set:
11770:    ssi_error                - If an unrecoverable error occurred this becomes true.
11771:                               It is up to the caller to initialize this to false
11772:                               if desired.
11773:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11774:                               of the resource that could not be rendered by the ssi
11775:                               call.
11776:    ssi_error_message   - The error string fetched from the ssi response
11777:                               in the event of an error.
11778: 
11779: 
11780: =head1 HANDLER SUBROUTINE
11781: 
11782: ssi_with_retries()
11783: 
11784: =head1 SUBROUTINES
11785: 
11786: =over
11787: 
11788: =head1 Routines to display previous version of a Task for a specific student
11789: 
11790: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11791: can receive another opportunity. Access to tasks is slot-based. If a slot
11792: requires a proctor to check-in the student, a new version of the Task will
11793: be created when the student is checked in to the new opportunity.
11794: 
11795: If a particular student has tried two or more versions of a particular task,
11796: the submission screen provides a user with vgr privileges (e.g., a Course
11797: Coordinator) the ability to display a previous version worked on by the
11798: student.  By default, the current version is displayed. If a previous version
11799: has been selected for display, submission data are only shown that pertain
11800: to that particular version, and the interface to submit grades is not shown.
11801: 
11802: =over 4
11803: 
11804: =item show_previous_task_version()
11805: 
11806: Displays a specified version of a student's Task, as the student sees it.
11807: 
11808: Inputs: 2
11809:         request - request object
11810:         symb    - unique symb for current instance of resource
11811: 
11812: Output: None.
11813: 
11814: Side Effects: calls &show_problem() to print version of Task, with
11815:               version contained in form item: $env{'form.previousversion'}
11816: 
11817: =item choose_task_version_form()
11818: 
11819: Displays a web form used to select which version of a student's view of a
11820: Task should be displayed.  Either launches a pop-up window, or replaces
11821: content in existing pop-up, or replaces page in main window.
11822: 
11823: Inputs: 4
11824:         symb    - unique symb for current instance of resource
11825:         uname   - username of student
11826:         udom    - domain of student
11827:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11828:                   breadcrumbs etc., are displayed
11829: 
11830: Output: 4
11831:         current   - student's current version
11832:         displayed - student's version being displayed
11833:         result    - scalar containing HTML for web form used to switch to
11834:                     a different version (or a link to close window, if pop-up).
11835:         js        - javascript for processing selection in versions web form
11836: 
11837: Side Effects: None.
11838: 
11839: =item previous_display_javascript()
11840: 
11841: Inputs: 2
11842:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11843:                   breadcrumbs etc., are displayed.
11844:         current - student's current version number.
11845: 
11846: Output: 1
11847:         js      - javascript for processing selection in versions web form.
11848: 
11849: Side Effects: None.
11850: 
11851: =back
11852: 
11853: =head1 Routines to process bubblesheet data.
11854: 
11855: =over 4
11856: 
11857: =item scantron_get_correction() : 
11858: 
11859:    Builds the interface screen to interact with the operator to fix a
11860:    specific error condition in a specific scanline
11861: 
11862:  Arguments:
11863:     $r           - Apache request object
11864:     $i           - number of the current scanline
11865:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11866:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11867:     $line        - full contents of the current scanline
11868:     $error       - error condition, valid values are
11869:                    'incorrectCODE', 'duplicateCODE',
11870:                    'doublebubble', 'missingbubble',
11871:                    'duplicateID', 'incorrectID'
11872:     $arg         - extra information needed
11873:        For errors:
11874:          - duplicateID   - paper number that this studentID was seen before on
11875:          - duplicateCODE - array ref of the paper numbers this CODE was
11876:                            seen on before
11877:          - incorrectCODE - current incorrect CODE 
11878:          - doublebubble  - array ref of the bubble lines that have double
11879:                            bubble errors
11880:          - missingbubble - array ref of the bubble lines that have missing
11881:                            bubble errors
11882: 
11883:    $randomorder - True if exam folder has randomorder set
11884:    $randompick  - True if exam folder has randompick set
11885:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11886:                      for current line to question number used for same question
11887:                      in "Master Seqence" (as seen by Course Coordinator).
11888:    $startline   - Reference to hash where key is question number (0 is first)
11889:                   and value is number of first bubble line for current student
11890:                   or code-based randompick and/or randomorder.
11891: 
11892: 
11893: 
11894: =item  scantron_get_maxbubble() : 
11895: 
11896:    Arguments:
11897:        $nav_error  - Reference to scalar which is a flag to indicate a
11898:                       failure to retrieve a navmap object.
11899:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11900:        calling routine should trap the error condition and display the warning
11901:        found in &navmap_errormsg().
11902: 
11903:        $scantron_config - Reference to bubblesheet format configuration hash.
11904: 
11905:    Returns the maximum number of bubble lines that are expected to
11906:    occur. Does this by walking the selected sequence rendering the
11907:    resource and then checking &Apache::lonxml::get_problem_counter()
11908:    for what the current value of the problem counter is.
11909: 
11910:    Caches the results to $env{'form.scantron_maxbubble'},
11911:    $env{'form.scantron.bubble_lines.n'}, 
11912:    $env{'form.scantron.first_bubble_line.n'} and
11913:    $env{"form.scantron.sub_bubblelines.n"}
11914:    which are the total number of bubble lines, the number of bubble
11915:    lines for response n and number of the first bubble line for response n,
11916:    and a comma separated list of numbers of bubble lines for sub-questions
11917:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11918: 
11919: 
11920: =item  scantron_validate_missingbubbles() : 
11921: 
11922:    Validates all scanlines in the selected file to not have any
11923:     answers that don't have bubbles that have not been verified
11924:     to be bubble free.
11925: 
11926: =item  scantron_process_students() : 
11927: 
11928:    Routine that does the actual grading of the bubblesheet information.
11929: 
11930:    The parsed scanline hash is added to %env 
11931: 
11932:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11933:    foreach resource , with the form data of
11934: 
11935: 	'submitted'     =>'scantron' 
11936: 	'grade_target'  =>'grade',
11937: 	'grade_username'=> username of student
11938: 	'grade_domain'  => domain of student
11939: 	'grade_courseid'=> of course
11940: 	'grade_symb'    => symb of resource to grade
11941: 
11942:     This triggers a grading pass. The problem grading code takes care
11943:     of converting the bubbled letter information (now in %env) into a
11944:     valid submission.
11945: 
11946: =item  scantron_upload_scantron_data() :
11947: 
11948:     Creates the screen for adding a new bubblesheet data file to a course.
11949: 
11950: =item  scantron_upload_scantron_data_save() : 
11951: 
11952:    Adds a provided bubble information data file to the course if user
11953:    has the correct privileges to do so.
11954: 
11955: = item scantron_upload_delete() :
11956: 
11957:    Deletes a previously uploaded bubble information data file, if user
11958:    was the one who uploaded the file, and has the privileges to do so.
11959: 
11960: =item  valid_file() :
11961: 
11962:    Validates that the requested bubble data file exists in the course.
11963: 
11964: =item  scantron_download_scantron_data() : 
11965: 
11966:    Shows a list of the three internal files (original, corrected,
11967:    skipped) for a specific bubblesheet data file that exists in the
11968:    course.
11969: 
11970: =item  scantron_validate_ID() : 
11971: 
11972:    Validates all scanlines in the selected file to not have any
11973:    invalid or underspecified student/employee IDs
11974: 
11975: =item navmap_errormsg() :
11976: 
11977:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11978:    Should be called whenever the request to instantiate a navmap object fails.
11979: 
11980: =back
11981: 
11982: =back
11983: 
11984: =cut

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