File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.786: download - view: text, annotated - select for diffs
Fri Dec 17 15:16:51 2021 UTC (2 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6965. Removal of a problem from grading queue ignore awarded status
  of parts with non-handgradeable responses.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.786 2021/12/17 15:16:51 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:             if ($env{'form.HIDE'.$prob}) {
 5735:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5736:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5737:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5738:                 $hideflag += $numchgs;
 5739:             }
 5740: 	    foreach my $partid (@{$parts}) {
 5741: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5742: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5743:                 my @types = $curRes->responseType($part);
 5744:                 if (grep(/^essay$/,@types)) {
 5745:                     $queueable{$partid} = 1;
 5746:                 } else {
 5747:                     my @ids = $curRes->responseIds($part);
 5748:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5749:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
 5750:                                                           '.handgrade',$symb);
 5751:                         if (lc($hndgrd) eq 'yes') {
 5752:                             $queueable{$partid} = 1;
 5753:                             last;
 5754:                         }
 5755:                     }
 5756:                 }
 5757: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5758: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5759: 		my $partial = $newpts/$wgt;
 5760: 		my $score;
 5761: 		if ($partial > 0) {
 5762: 		    $score = 'correct_by_override';
 5763: 		} elsif ($newpts ne '') { #empty is taken as 0
 5764: 		    $score = 'incorrect_by_override';
 5765: 		}
 5766: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5767: 		if ($dropMenu eq 'excused') {
 5768: 		    $partial = '';
 5769: 		    $score = 'excused';
 5770: 		} elsif ($dropMenu eq 'reset status'
 5771: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5772: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5773: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5774: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5775: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5776: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5777: 		    $changeflag++;
 5778: 		    $newpts = '';
 5779:                     
 5780:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5781:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5782:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5783:                     if ($aggtries > 0) {
 5784:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5785:                         $aggregateflag = 1;
 5786:                     }
 5787: 		}
 5788: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5789: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5790: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5791: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5792: 		    '&nbsp;<br />';
 5793: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5794: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5795: 		    '&nbsp;<br />';
 5796: 		$question++;
 5797: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5798: 
 5799: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5800: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5801: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5802: 		    if (scalar(keys(%newrecord)) > 0);
 5803: 
 5804: 		$changeflag++;
 5805: 	    }
 5806: 	    if (scalar(keys(%newrecord)) > 0) {
 5807: 		my %record = 
 5808: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5809: 					     $udom,$uname);
 5810: 
 5811: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5812: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5813: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5814: 		    $newrecord{'resource.CODE'} = '';
 5815: 		}
 5816: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5817: 					$udom,$uname);
 5818: 		%record = &Apache::lonnet::restore($symbx,
 5819: 						   $env{'request.course.id'},
 5820: 						   $udom,$uname);
 5821: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5822: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5823: 	    }
 5824: 	    
 5825:             if ($aggregateflag) {
 5826:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5827:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5828:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5829:             }
 5830: 
 5831: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5832: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5833: 		&Apache::loncommon::end_data_table_row();
 5834: 
 5835: 	    $prob++;
 5836: 	}
 5837:         $curRes = $iterator->next();
 5838:     }
 5839: 
 5840:     $studentTable.=&Apache::loncommon::end_data_table();
 5841:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5842: 		  &mt('The scores were changed for [quant,_1,problem].',
 5843: 		  $changeflag).'<br />');
 5844:     my $hidemsg=($hideflag == 0 ? '' :
 5845:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5846:                      $hideflag).'<br />');
 5847:     $request->print($hidemsg.$grademsg.$studentTable);
 5848: 
 5849:     return '';
 5850: }
 5851: 
 5852: #-------- end of section for handling grading by page/sequence ---------
 5853: #
 5854: #-------------------------------------------------------------------
 5855: 
 5856: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5857: #
 5858: #------ start of section for handling grading by page/sequence ---------
 5859: 
 5860: =pod
 5861: 
 5862: =head1 Bubble sheet grading routines
 5863: 
 5864:   For this documentation:
 5865: 
 5866:    'scanline' refers to the full line of characters
 5867:    from the file that we are parsing that represents one entire sheet
 5868: 
 5869:    'bubble line' refers to the data
 5870:    representing the line of bubbles that are on the physical bubblesheet
 5871: 
 5872: 
 5873: The overall process is that a scanned in bubblesheet data is uploaded
 5874: into a course. When a user wants to grade, they select a
 5875: sequence/folder of resources, a file of bubblesheet info, and pick
 5876: one of the predefined configurations for what each scanline looks
 5877: like.
 5878: 
 5879: Next each scanline is checked for any errors of either 'missing
 5880: bubbles' (it's an error because it may have been mis-scanned
 5881: because too light bubbling), 'double bubble' (each bubble line should
 5882: have no more than one letter picked), invalid or duplicated CODE,
 5883: invalid student/employee ID
 5884: 
 5885: If the CODE option is used that determines the randomization of the
 5886: homework problems, either way the student/employee ID is looked up into a
 5887: username:domain.
 5888: 
 5889: During the validation phase the instructor can choose to skip scanlines. 
 5890: 
 5891: After the validation phase, there are now 3 bubblesheet files
 5892: 
 5893:   scantron_original_filename (unmodified original file)
 5894:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5895:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5896: 
 5897: Also there is a separate hash nohist_scantrondata that contains extra
 5898: correction information that isn't representable in the bubblesheet
 5899: file (see &scantron_getfile() for more information)
 5900: 
 5901: After all scanlines are either valid, marked as valid or skipped, then
 5902: foreach line foreach problem in the picked sequence, an ssi request is
 5903: made that simulates a user submitting their selected letter(s) against
 5904: the homework problem.
 5905: 
 5906: =over 4
 5907: 
 5908: 
 5909: 
 5910: =item defaultFormData
 5911: 
 5912:   Returns html hidden inputs used to hold context/default values.
 5913: 
 5914:  Arguments:
 5915:   $symb - $symb of the current resource 
 5916: 
 5917: =cut
 5918: 
 5919: sub defaultFormData {
 5920:     my ($symb)=@_;
 5921:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5922: }
 5923: 
 5924: 
 5925: =pod 
 5926: 
 5927: =item getSequenceDropDown
 5928: 
 5929:    Return html dropdown of possible sequences to grade
 5930:  
 5931:  Arguments:
 5932:    $symb - $symb of the current resource
 5933:    $map_error - ref to scalar which will container error if
 5934:                 $navmap object is unavailable in &getSymbMap().
 5935: 
 5936: =cut
 5937: 
 5938: sub getSequenceDropDown {
 5939:     my ($symb,$map_error)=@_;
 5940:     my $result='<select name="selectpage">'."\n";
 5941:     my ($titles,$symbx) = &getSymbMap($map_error);
 5942:     if (ref($map_error)) {
 5943:         return if ($$map_error);
 5944:     }
 5945:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5946:     my $ctr=0;
 5947:     foreach (@$titles) {
 5948: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5949: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5950: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5951: 	    '>'.$showtitle.'</option>'."\n";
 5952: 	$ctr++;
 5953:     }
 5954:     $result.= '</select>';
 5955:     return $result;
 5956: }
 5957: 
 5958: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5959:                                    # key is zero-based index - 0, 1, 2 ...
 5960: 
 5961: my %first_bubble_line;             # First bubble line no. for each bubble.
 5962: 
 5963: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5964:                                    # matchresponse or rankresponse, where 
 5965:                                    # an individual response can have multiple 
 5966:                                    # lines
 5967: 
 5968: my %responsetype_per_response;     # responsetype for each response
 5969: 
 5970: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5971:                                    # numbered response. Needed when randomorder
 5972:                                    # or randompick are in use. Key is ID, value 
 5973:                                    # is response number.
 5974: 
 5975: # Save and restore the bubble lines array to the form env.
 5976: 
 5977: 
 5978: sub save_bubble_lines {
 5979:     foreach my $line (keys(%bubble_lines_per_response)) {
 5980: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5981: 	$env{"form.scantron.first_bubble_line.$line"} =
 5982: 	    $first_bubble_line{$line};
 5983:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5984:             $subdivided_bubble_lines{$line};
 5985:         $env{"form.scantron.responsetype.$line"} =
 5986:             $responsetype_per_response{$line};
 5987:     }
 5988:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5989:         my $line = $masterseq_id_responsenum{$resid};
 5990:         $env{"form.scantron.residpart.$line"} = $resid;
 5991:     }
 5992: }
 5993: 
 5994: 
 5995: sub restore_bubble_lines {
 5996:     my $line = 0;
 5997:     %bubble_lines_per_response = ();
 5998:     %masterseq_id_responsenum = ();
 5999:     while ($env{"form.scantron.bubblelines.$line"}) {
 6000: 	my $value = $env{"form.scantron.bubblelines.$line"};
 6001: 	$bubble_lines_per_response{$line} = $value;
 6002: 	$first_bubble_line{$line}  =
 6003: 	    $env{"form.scantron.first_bubble_line.$line"};
 6004:         $subdivided_bubble_lines{$line} =
 6005:             $env{"form.scantron.sub_bubblelines.$line"};
 6006:         $responsetype_per_response{$line} =
 6007:             $env{"form.scantron.responsetype.$line"};
 6008:         my $id = $env{"form.scantron.residpart.$line"};
 6009:         $masterseq_id_responsenum{$id} = $line;
 6010: 	$line++;
 6011:     }
 6012: }
 6013: 
 6014: =pod 
 6015: 
 6016: =item scantron_filenames
 6017: 
 6018:    Returns a list of the scantron files in the current course 
 6019: 
 6020: =cut
 6021: 
 6022: sub scantron_filenames {
 6023:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6024:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6025:     my $getpropath = 1;
 6026:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6027:                                                         $cname,$getpropath);
 6028:     my @possiblenames;
 6029:     if (ref($dirlist) eq 'ARRAY') {
 6030:         foreach my $filename (sort(@{$dirlist})) {
 6031: 	    ($filename)=split(/&/,$filename);
 6032: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6033: 	    $filename=~s/^scantron_orig_//;
 6034: 	    push(@possiblenames,$filename);
 6035:         }
 6036:     }
 6037:     return @possiblenames;
 6038: }
 6039: 
 6040: =pod 
 6041: 
 6042: =item scantron_uploads
 6043: 
 6044:    Returns  html drop-down list of scantron files in current course.
 6045: 
 6046:  Arguments:
 6047:    $file2grade - filename to set as selected in the dropdown
 6048: 
 6049: =cut
 6050: 
 6051: sub scantron_uploads {
 6052:     my ($file2grade) = @_;
 6053:     my $result=	'<select name="scantron_selectfile">';
 6054:     $result.="<option></option>";
 6055:     foreach my $filename (sort(&scantron_filenames())) {
 6056: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6057:     }
 6058:     $result.="</select>";
 6059:     return $result;
 6060: }
 6061: 
 6062: =pod 
 6063: 
 6064: =item scantron_scantab
 6065: 
 6066:   Returns html drop down of the scantron formats in the scantronformat.tab
 6067:   file.
 6068: 
 6069: =cut
 6070: 
 6071: sub scantron_scantab {
 6072:     my $result='<select name="scantron_format">'."\n";
 6073:     $result.='<option></option>'."\n";
 6074:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6075:     if (@lines > 0) {
 6076:         foreach my $line (@lines) {
 6077:             next if (($line =~ /^\#/) || ($line eq ''));
 6078: 	    my ($name,$descrip)=split(/:/,$line);
 6079: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6080:         }
 6081:     }
 6082:     $result.='</select>'."\n";
 6083:     return $result;
 6084: }
 6085: 
 6086: =pod 
 6087: 
 6088: =item scantron_CODElist
 6089: 
 6090:   Returns html drop down of the saved CODE lists from current course,
 6091:   generated from earlier printings.
 6092: 
 6093: =cut
 6094: 
 6095: sub scantron_CODElist {
 6096:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6097:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6098:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6099:     my $namechoice='<option></option>';
 6100:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6101: 	if ($name =~ /^error: 2 /) { next; }
 6102: 	if ($name =~ /^type\0/) { next; }
 6103: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6104:     }
 6105:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6106:     return $namechoice;
 6107: }
 6108: 
 6109: =pod 
 6110: 
 6111: =item scantron_CODEunique
 6112: 
 6113:   Returns the html for "Each CODE to be used once" radio.
 6114: 
 6115: =cut
 6116: 
 6117: sub scantron_CODEunique {
 6118:     my $result='<span class="LC_nobreak">
 6119:                  <label><input type="radio" name="scantron_CODEunique"
 6120:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6121:                 </span>
 6122:                 <span class="LC_nobreak">
 6123:                  <label><input type="radio" name="scantron_CODEunique"
 6124:                         value="no" />'.&mt('No').' </label>
 6125:                 </span>';
 6126:     return $result;
 6127: }
 6128: 
 6129: =pod 
 6130: 
 6131: =item scantron_selectphase
 6132: 
 6133:   Generates the initial screen to start the bubblesheet process.
 6134:   Allows for - starting a grading run.
 6135:              - downloading existing scan data (original, corrected
 6136:                                                 or skipped info)
 6137: 
 6138:              - uploading new scan data
 6139: 
 6140:  Arguments:
 6141:   $r          - The Apache request object
 6142:   $file2grade - name of the file that contain the scanned data to score
 6143: 
 6144: =cut
 6145: 
 6146: sub scantron_selectphase {
 6147:     my ($r,$file2grade,$symb) = @_;
 6148:     if (!$symb) {return '';}
 6149:     my $map_error;
 6150:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6151:     if ($map_error) {
 6152:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6153:         return;
 6154:     }
 6155:     my $default_form_data=&defaultFormData($symb);
 6156:     my $file_selector=&scantron_uploads($file2grade);
 6157:     my $format_selector=&scantron_scantab();
 6158:     my $CODE_selector=&scantron_CODElist();
 6159:     my $CODE_unique=&scantron_CODEunique();
 6160:     my $result;
 6161: 
 6162:     $ssi_error = 0;
 6163: 
 6164:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6165: 
 6166: 	# Chunk of form to prompt for a scantron file upload.
 6167: 
 6168:         $r->print('
 6169:     <br />');
 6170:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6171:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6172:     my $csec= $env{'request.course.sec'};
 6173:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6174:     &js_escape(\$alertmsg);
 6175:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6176:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6177:     function checkUpload(formname) {
 6178: 	if (formname.upfile.value == "") {
 6179: 	    alert("'.$alertmsg.'");
 6180: 	    return false;
 6181: 	}
 6182: 	formname.submit();
 6183:     }'."\n".$formatjs));
 6184:     $r->print('
 6185:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6186:                 '.$default_form_data.'
 6187:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6188:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6189:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6190:                 <input name="command" value="scantronupload_save" type="hidden" />
 6191:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6192:               '.&Apache::loncommon::start_data_table_header_row().'
 6193:                 <th>
 6194:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6195:                 </th>
 6196:               '.&Apache::loncommon::end_data_table_header_row().'
 6197:               '.&Apache::loncommon::start_data_table_row().'
 6198:             <td>
 6199:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6200:     if ($formatoptions) {
 6201:         $r->print('</td>
 6202:                  '.&Apache::loncommon::end_data_table_row().'
 6203:                  '.&Apache::loncommon::start_data_table_row().'
 6204:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6205:                  </td>
 6206:                  '.&Apache::loncommon::end_data_table_row().'
 6207:                  '.&Apache::loncommon::start_data_table_row().'
 6208:                  <td>'
 6209:         );
 6210:     } else {
 6211:         $r->print(' <br />');
 6212:     }
 6213:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6214:               </td>
 6215:              '.&Apache::loncommon::end_data_table_row().'
 6216:              '.&Apache::loncommon::end_data_table().'
 6217:              </form>'
 6218:     );
 6219: 
 6220:     }
 6221: 
 6222:     # Chunk of form to prompt for a file to grade and how:
 6223: 
 6224:     $result.= '
 6225:     <br />
 6226:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6227:     <input type="hidden" name="command" value="scantron_warning" />
 6228:     '.$default_form_data.'
 6229:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6230:        '.&Apache::loncommon::start_data_table_header_row().'
 6231:             <th colspan="2">
 6232:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6233:             </th>
 6234:        '.&Apache::loncommon::end_data_table_header_row().'
 6235:        '.&Apache::loncommon::start_data_table_row().'
 6236:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6237:        '.&Apache::loncommon::end_data_table_row().'
 6238:        '.&Apache::loncommon::start_data_table_row().'
 6239:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6240:        '.&Apache::loncommon::end_data_table_row().'
 6241:        '.&Apache::loncommon::start_data_table_row().'
 6242:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6243:        '.&Apache::loncommon::end_data_table_row().'
 6244:        '.&Apache::loncommon::start_data_table_row().'
 6245:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6246:        '.&Apache::loncommon::end_data_table_row().'
 6247:        '.&Apache::loncommon::start_data_table_row().'
 6248:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6249:        '.&Apache::loncommon::end_data_table_row().'
 6250:        '.&Apache::loncommon::start_data_table_row().'
 6251: 	    <td> '.&mt('Options:').' </td>
 6252:             <td>
 6253: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6254:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6255:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6256: 	    </td>
 6257:        '.&Apache::loncommon::end_data_table_row().'
 6258:        '.&Apache::loncommon::start_data_table_row().'
 6259:             <td colspan="2">
 6260:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6261:             </td>
 6262:        '.&Apache::loncommon::end_data_table_row().'
 6263:     '.&Apache::loncommon::end_data_table().'
 6264:     </form>
 6265: ';
 6266:    
 6267:     $r->print($result);
 6268: 
 6269:     # Chunk of the form that prompts to view a scoring office file,
 6270:     # corrected file, skipped records in a file.
 6271: 
 6272:     $r->print('
 6273:    <br />
 6274:    <form action="/adm/grades" name="scantron_download">
 6275:      '.$default_form_data.'
 6276:      <input type="hidden" name="command" value="scantron_download" />
 6277:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6278:        '.&Apache::loncommon::start_data_table_header_row().'
 6279:               <th>
 6280:                 &nbsp;'.&mt('Download a scoring office file').'
 6281:               </th>
 6282:        '.&Apache::loncommon::end_data_table_header_row().'
 6283:        '.&Apache::loncommon::start_data_table_row().'
 6284:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6285:                 <br />
 6286:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6287:        '.&Apache::loncommon::end_data_table_row().'
 6288:      '.&Apache::loncommon::end_data_table().'
 6289:    </form>
 6290:    <br />
 6291: ');
 6292: 
 6293:     &Apache::lonpickcode::code_list($r,2);
 6294: 
 6295:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6296:              $default_form_data."\n".
 6297:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6298:              &Apache::loncommon::start_data_table_header_row()."\n".
 6299:              '<th colspan="2">
 6300:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6301:              '</th>'."\n".
 6302:               &Apache::loncommon::end_data_table_header_row()."\n".
 6303:               &Apache::loncommon::start_data_table_row()."\n".
 6304:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6305:               '<td> '.$sequence_selector.' </td>'.
 6306:               &Apache::loncommon::end_data_table_row()."\n".
 6307:               &Apache::loncommon::start_data_table_row()."\n".
 6308:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6309:               '<td> '.$file_selector.' </td>'."\n".
 6310:               &Apache::loncommon::end_data_table_row()."\n".
 6311:               &Apache::loncommon::start_data_table_row()."\n".
 6312:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6313:               '<td> '.$format_selector.' </td>'."\n".
 6314:               &Apache::loncommon::end_data_table_row()."\n".
 6315:               &Apache::loncommon::start_data_table_row()."\n".
 6316:               '<td> '.&mt('Options').' </td>'."\n".
 6317:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6318:               &Apache::loncommon::end_data_table_row()."\n".
 6319:               &Apache::loncommon::start_data_table_row()."\n".
 6320:               '<td colspan="2">'."\n".
 6321:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6322:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6323:               '</td>'."\n".
 6324:               &Apache::loncommon::end_data_table_row()."\n".
 6325:               &Apache::loncommon::end_data_table()."\n".
 6326:               '</form><br />');
 6327:     return;
 6328: }
 6329: 
 6330: =pod 
 6331: 
 6332: =item username_to_idmap
 6333: 
 6334:     creates a hash keyed by student/employee ID with values of the corresponding
 6335:     student username:domain. If a single ID occurs for more than one student,
 6336:     the status of the student is checked, and if Active, the value in the hash
 6337:     will be set to the Active student.
 6338: 
 6339:   Arguments:
 6340: 
 6341:     $classlist - reference to the class list hash. This is a hash
 6342:                  keyed by student name:domain  whose elements are references
 6343:                  to arrays containing various chunks of information
 6344:                  about the student. (See loncoursedata for more info).
 6345: 
 6346:   Returns
 6347:     %idmap - the constructed hash
 6348: 
 6349: =cut
 6350: 
 6351: sub username_to_idmap {
 6352:     my ($classlist)= @_;
 6353:     my %idmap;
 6354:     foreach my $student (keys(%$classlist)) {
 6355:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6356:         unless ($id eq '') {
 6357:             if (!exists($idmap{$id})) {
 6358:                 $idmap{$id} = $student;
 6359:             } else {
 6360:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6361:                 if ($status eq 'Active') {
 6362:                     $idmap{$id} = $student;
 6363:                 }
 6364:             }
 6365:         }
 6366:     }
 6367:     return %idmap;
 6368: }
 6369: 
 6370: =pod
 6371: 
 6372: =item scantron_fixup_scanline
 6373: 
 6374:    Process a requested correction to a scanline.
 6375: 
 6376:   Arguments:
 6377:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6378:     $scan_data         - hash of correction information 
 6379:                           (see &scantron_getfile())
 6380:     $line              - existing scanline
 6381:     $whichline         - line number of the passed in scanline
 6382:     $field             - type of change to process 
 6383:                          (either 
 6384:                           'ID'     -> correct the student/employee ID
 6385:                           'CODE'   -> correct the CODE
 6386:                           'answer' -> fixup the submitted answers)
 6387:     
 6388:    $args               - hash of additional info,
 6389:                           - 'ID' 
 6390:                                'newid' -> studentID to use in replacement
 6391:                                           of existing one
 6392:                           - 'CODE' 
 6393:                                'CODE_ignore_dup' - set to true if duplicates
 6394:                                                    should be ignored.
 6395: 	                       'CODE' - is new code or 'use_unfound'
 6396:                                         if the existing unfound code should
 6397:                                         be used as is
 6398:                           - 'answer'
 6399:                                'response' - new answer or 'none' if blank
 6400:                                'question' - the bubble line to change
 6401:                                'questionnum' - the question identifier,
 6402:                                                may include subquestion. 
 6403: 
 6404:   Returns:
 6405:     $line - the modified scanline
 6406: 
 6407:   Side effects: 
 6408:     $scan_data - may be updated
 6409: 
 6410: =cut
 6411: 
 6412: 
 6413: sub scantron_fixup_scanline {
 6414:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6415:     if ($field eq 'ID') {
 6416: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6417: 	    return ($line,1,'New value too large');
 6418: 	}
 6419: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6420: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6421: 				     $args->{'newid'});
 6422: 	}
 6423: 	substr($line,$$scantron_config{'IDstart'}-1,
 6424: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6425: 	if ($args->{'newid'}=~/^\s*$/) {
 6426: 	    &scan_data($scan_data,"$whichline.user",
 6427: 		       $args->{'username'}.':'.$args->{'domain'});
 6428: 	}
 6429:     } elsif ($field eq 'CODE') {
 6430: 	if ($args->{'CODE_ignore_dup'}) {
 6431: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6432: 	}
 6433: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6434: 	if ($args->{'CODE'} ne 'use_unfound') {
 6435: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6436: 		return ($line,1,'New CODE value too large');
 6437: 	    }
 6438: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6439: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6440: 	    }
 6441: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6442: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6443: 	}
 6444:     } elsif ($field eq 'answer') {
 6445: 	my $length=$scantron_config->{'Qlength'};
 6446: 	my $off=$scantron_config->{'Qoff'};
 6447: 	my $on=$scantron_config->{'Qon'};
 6448: 	my $answer=${off}x$length;
 6449: 	if ($args->{'response'} eq 'none') {
 6450: 	    &scan_data($scan_data,
 6451: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6452: 	} else {
 6453: 	    if ($on eq 'letter') {
 6454: 		my @alphabet=('A'..'Z');
 6455: 		$answer=$alphabet[$args->{'response'}];
 6456: 	    } elsif ($on eq 'number') {
 6457: 		$answer=$args->{'response'}+1;
 6458: 		if ($answer == 10) { $answer = '0'; }
 6459: 	    } else {
 6460: 		substr($answer,$args->{'response'},1)=$on;
 6461: 	    }
 6462: 	    &scan_data($scan_data,
 6463: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6464: 	}
 6465: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6466: 	substr($line,$where-1,$length)=$answer;
 6467:     }
 6468:     return $line;
 6469: }
 6470: 
 6471: =pod
 6472: 
 6473: =item scan_data
 6474: 
 6475:     Edit or look up  an item in the scan_data hash.
 6476: 
 6477:   Arguments:
 6478:     $scan_data  - The hash (see scantron_getfile)
 6479:     $key        - shorthand of the key to edit (actual key is
 6480:                   scantronfilename_key).
 6481:     $data        - New value of the hash entry.
 6482:     $delete      - If true, the entry is removed from the hash.
 6483: 
 6484:   Returns:
 6485:     The new value of the hash table field (undefined if deleted).
 6486: 
 6487: =cut
 6488: 
 6489: 
 6490: sub scan_data {
 6491:     my ($scan_data,$key,$value,$delete)=@_;
 6492:     my $filename=$env{'form.scantron_selectfile'};
 6493:     if (defined($value)) {
 6494: 	$scan_data->{$filename.'_'.$key} = $value;
 6495:     }
 6496:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6497:     return $scan_data->{$filename.'_'.$key};
 6498: }
 6499: 
 6500: # ----- These first few routines are general use routines.----
 6501: 
 6502: # Return the number of occurences of a pattern in a string.
 6503: 
 6504: sub occurence_count {
 6505:     my ($string, $pattern) = @_;
 6506: 
 6507:     my @matches = ($string =~ /$pattern/g);
 6508: 
 6509:     return scalar(@matches);
 6510: }
 6511: 
 6512: 
 6513: # Take a string known to have digits and convert all the
 6514: # digits into letters in the range J,A..I.
 6515: 
 6516: sub digits_to_letters {
 6517:     my ($input) = @_;
 6518: 
 6519:     my @alphabet = ('J', 'A'..'I');
 6520: 
 6521:     my @input    = split(//, $input);
 6522:     my $output ='';
 6523:     for (my $i = 0; $i < scalar(@input); $i++) {
 6524: 	if ($input[$i] =~ /\d/) {
 6525: 	    $output .= $alphabet[$input[$i]];
 6526: 	} else {
 6527: 	    $output .= $input[$i];
 6528: 	}
 6529:     }
 6530:     return $output;
 6531: }
 6532: 
 6533: =pod 
 6534: 
 6535: =item scantron_parse_scanline
 6536: 
 6537:   Decodes a scanline from the selected bubblesheet file
 6538: 
 6539:  Arguments:
 6540:     line             - The text of the bubblesheet file line to process
 6541:     whichline        - Line number
 6542:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6543:     scan_data        - Hash of extra information about the scanline
 6544:                        (see scantron_getfile for more information)
 6545:     just_header      - True if should not process question answers but only
 6546:                        the stuff to the left of the answers.
 6547:     randomorder      - True if randomorder in use
 6548:     randompick       - True if randompick in use
 6549:     sequence         - Exam folder URL
 6550:     master_seq       - Ref to array containing symbs in exam folder
 6551:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6552:                        (corresponding values are resource objects)
 6553:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6554:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6555:                        are refs to an array of resource objects, ordered
 6556:                        according to order used for CODE, when randomorder
 6557:                        and or randompick are in use.
 6558:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6559:                        for current line to question number used for same question
 6560:                         in "Master Sequence" (as seen by Course Coordinator).
 6561:     startline        - Ref to hash where key is question number (0 is first)
 6562:                        and value is number of first bubble line for current 
 6563:                        student or code-based randompick and/or randomorder.
 6564:     totalref         - Ref of scalar used to score total number of bubble
 6565:                        lines needed for responses in a scan line (used when
 6566:                        randompick in use. 
 6567:     
 6568:  Returns:
 6569:    Hash containing the result of parsing the scanline
 6570: 
 6571:    Keys are all proceeded by the string 'scantron.'
 6572: 
 6573:        CODE    - the CODE in use for this scanline
 6574:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6575:                  by the operator
 6576:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6577:                             CODEs were selected, but the usage has been
 6578:                             forced by the operator
 6579:        ID  - student/employee ID
 6580:        PaperID - if used, the ID number printed on the sheet when the 
 6581:                  paper was scanned
 6582:        FirstName - first name from the sheet
 6583:        LastName  - last name from the sheet
 6584: 
 6585:      if just_header was not true these key may also exist
 6586: 
 6587:        missingerror - a list of bubble ranges that are considered to be answers
 6588:                       to a single question that don't have any bubbles filled in.
 6589:                       Of the form questionnumber:firstbubblenumber:count.
 6590:        doubleerror  - a list of bubble ranges that are considered to be answers
 6591:                       to a single question that have more than one bubble filled in.
 6592:                       Of the form questionnumber::firstbubblenumber:count
 6593:    
 6594:                 In the above, count is the number of bubble responses in the
 6595:                 input line needed to represent the possible answers to the question.
 6596:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6597:                 per line would have count = 2.
 6598: 
 6599:        maxquest     - the number of the last bubble line that was parsed
 6600: 
 6601:        (<number> starts at 1)
 6602:        <number>.answer - zero or more letters representing the selected
 6603:                          letters from the scanline for the bubble line 
 6604:                          <number>.
 6605:                          if blank there was either no bubble or there where
 6606:                          multiple bubbles, (consult the keys missingerror and
 6607:                          doubleerror if this is an error condition)
 6608: 
 6609: =cut
 6610: 
 6611: sub scantron_parse_scanline {
 6612:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6613:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6614:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6615: 
 6616:     my %record;
 6617:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6618:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6619: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6620: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6621: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6622: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6623: 	    $record{'scantron.CODE'}=substr($data,
 6624: 					    $$scantron_config{'CODEstart'}-1,
 6625: 					    $$scantron_config{'CODElength'});
 6626: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6627: 		$record{'scantron.useCODE'}=1;
 6628: 	    }
 6629: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6630: 		$record{'scantron.CODE_ignore_dup'}=1;
 6631: 	    }
 6632: 	} else {
 6633: 	    #FIXME interpret first N questions
 6634: 	}
 6635:     }
 6636:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6637: 				  $$scantron_config{'IDlength'});
 6638:     $record{'scantron.PaperID'}=
 6639: 	substr($data,$$scantron_config{'PaperID'}-1,
 6640: 	       $$scantron_config{'PaperIDlength'});
 6641:     $record{'scantron.FirstName'}=
 6642: 	substr($data,$$scantron_config{'FirstName'}-1,
 6643: 	       $$scantron_config{'FirstNamelength'});
 6644:     $record{'scantron.LastName'}=
 6645: 	substr($data,$$scantron_config{'LastName'}-1,
 6646: 	       $$scantron_config{'LastNamelength'});
 6647:     if ($just_header) { return \%record; }
 6648: 
 6649:     my @alphabet=('A'..'Z');
 6650:     my $questnum=0;
 6651:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6652: 
 6653:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6654:     if ($randompick || $randomorder) {
 6655:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6656:                                          $master_seq,$symb_to_resource,
 6657:                                          $partids_by_symb,$orderedforcode,
 6658:                                          $respnumlookup,$startline);
 6659:         if ($total) {
 6660:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6661:         }
 6662:         if (ref($totalref)) {
 6663:             $$totalref = $total;
 6664:         }
 6665:     }
 6666:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6667:     chomp($questions);		# Get rid of any trailing \n.
 6668:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6669:     while (length($questions)) {
 6670:         my $answers_needed;
 6671:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6672:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6673:         } else {
 6674: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6675:         }
 6676:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6677:                              || 1;
 6678:         $questnum++;
 6679:         my $quest_id = $questnum;
 6680:         my $currentquest = substr($questions,0,$answer_length);
 6681:         $questions       = substr($questions,$answer_length);
 6682:         if (length($currentquest) < $answer_length) { next; }
 6683: 
 6684:         my $subdivided;
 6685:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6686:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6687:         } else {
 6688:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6689:         }
 6690:         if ($subdivided =~ /,/) {
 6691:             my $subquestnum = 1;
 6692:             my $subquestions = $currentquest;
 6693:             my @subanswers_needed = split(/,/,$subdivided);
 6694:             foreach my $subans (@subanswers_needed) {
 6695:                 my $subans_length =
 6696:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6697:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6698:                 $subquestions   = substr($subquestions,$subans_length);
 6699:                 $quest_id = "$questnum.$subquestnum";
 6700:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6701:                     ($$scantron_config{'Qon'} eq 'number')) {
 6702:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6703:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6704:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6705:                         $randomorder,$randompick,$respnumlookup);
 6706:                 } else {
 6707:                     $ansnum = &scantron_validator_positional($ansnum,
 6708:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6709:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6710:                         $randomorder,$randompick,$respnumlookup);
 6711:                 }
 6712:                 $subquestnum ++;
 6713:             }
 6714:         } else {
 6715:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6716:                 ($$scantron_config{'Qon'} eq 'number')) {
 6717:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6718:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6719:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6720:                     $randomorder,$randompick,$respnumlookup);
 6721:             } else {
 6722:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6723:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6724:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6725:                     $randomorder,$randompick,$respnumlookup);
 6726:             }
 6727:         }
 6728:     }
 6729:     $record{'scantron.maxquest'}=$questnum;
 6730:     return \%record;
 6731: }
 6732: 
 6733: sub get_master_seq {
 6734:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6735:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6736:                    (ref($symb_to_resource) eq 'HASH'));
 6737:     my $resource_error;
 6738:     foreach my $resource (@{$resources}) {
 6739:         my $ressymb;
 6740:         if (ref($resource)) {
 6741:             $ressymb = $resource->symb();
 6742:             push(@{$master_seq},$ressymb);
 6743:             $symb_to_resource->{$ressymb} = $resource;
 6744:         } else {
 6745:             $resource_error = 1;
 6746:             last;
 6747:         }
 6748:     }
 6749:     return $resource_error;
 6750: }
 6751: 
 6752: sub get_respnum_lookups {
 6753:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6754:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6755:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6756:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6757:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6758:                    (ref($startline) eq 'HASH'));
 6759:     my ($user,$scancode);
 6760:     if ((exists($record->{'scantron.CODE'})) &&
 6761:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6762:         $scancode = $record->{'scantron.CODE'};
 6763:     } else {
 6764:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6765:     }
 6766:     my @mapresources =
 6767:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6768:                      $orderedforcode);
 6769:     my $total = 0;
 6770:     my $count = 0;
 6771:     foreach my $resource (@mapresources) {
 6772:         my $id = $resource->id();
 6773:         my $symb = $resource->symb();
 6774:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6775:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6776:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6777:                 if ($respnum ne '') {
 6778:                     $respnumlookup->{$count} = $respnum;
 6779:                     $startline->{$count} = $total;
 6780:                     $total += $bubble_lines_per_response{$respnum};
 6781:                     $count ++;
 6782:                 }
 6783:             }
 6784:         }
 6785:     }
 6786:     return $total;
 6787: }
 6788: 
 6789: sub scantron_validator_lettnum {
 6790:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6791:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6792:         $randompick,$respnumlookup) = @_;
 6793: 
 6794:     # Qon 'letter' implies for each slot in currquest we have:
 6795:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6796:     #    about anything else (esp. a value of Qoff) for missing
 6797:     #    bubbles.
 6798:     #
 6799:     # Qon 'number' implies each slot gives a digit that indexes the
 6800:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6801:     #    and * or ? for double bubbles on a single line.
 6802:     #
 6803: 
 6804:     my $matchon;
 6805:     if ($$scantron_config{'Qon'} eq 'letter') {
 6806:         $matchon = '[A-Z]';
 6807:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6808:         $matchon = '\d';
 6809:     }
 6810:     my $occurrences = 0;
 6811:     my $responsenum = $questnum-1;
 6812:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6813:        $responsenum = $respnumlookup->{$questnum-1} 
 6814:     }
 6815:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6816:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6817:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6818:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6819:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6820:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6821:         my @singlelines = split('',$currquest);
 6822:         foreach my $entry (@singlelines) {
 6823:             $occurrences = &occurence_count($entry,$matchon);
 6824:             if ($occurrences > 1) {
 6825:                 last;
 6826:             }
 6827:         }
 6828:     } else {
 6829:         $occurrences = &occurence_count($currquest,$matchon); 
 6830:     }
 6831:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6832:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6833:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6834:             my $bubble = substr($currquest,$ans,1);
 6835:             if ($bubble =~ /$matchon/ ) {
 6836:                 if ($$scantron_config{'Qon'} eq 'number') {
 6837:                     if ($bubble == 0) {
 6838:                         $bubble = 10; 
 6839:                     }
 6840:                     $record->{"scantron.$ansnum.answer"} = 
 6841:                         $alphabet->[$bubble-1];
 6842:                 } else {
 6843:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6844:                 }
 6845:             } else {
 6846:                 $record->{"scantron.$ansnum.answer"}='';
 6847:             }
 6848:             $ansnum++;
 6849:         }
 6850:     } elsif (!defined($currquest)
 6851:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6852:             || (&occurence_count($currquest,$matchon) == 0)) {
 6853:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6854:             $record->{"scantron.$ansnum.answer"}='';
 6855:             $ansnum++;
 6856:         }
 6857:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6858:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6859:         }
 6860:     } else {
 6861:         if ($$scantron_config{'Qon'} eq 'number') {
 6862:             $currquest = &digits_to_letters($currquest);            
 6863:         }
 6864:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6865:             my $bubble = substr($currquest,$ans,1);
 6866:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6867:             $ansnum++;
 6868:         }
 6869:     }
 6870:     return $ansnum;
 6871: }
 6872: 
 6873: sub scantron_validator_positional {
 6874:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6875:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6876:         $randomorder,$randompick,$respnumlookup) = @_;
 6877: 
 6878:     # Otherwise there's a positional notation;
 6879:     # each bubble line requires Qlength items, and there are filled in
 6880:     # bubbles for each case where there 'Qon' characters.
 6881:     #
 6882: 
 6883:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6884: 
 6885:     # If the split only gives us one element.. the full length of the
 6886:     # answer string, no bubbles are filled in:
 6887: 
 6888:     if ($answers_needed eq '') {
 6889:         return;
 6890:     }
 6891: 
 6892:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6893:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6894:             $record->{"scantron.$ansnum.answer"}='';
 6895:             $ansnum++;
 6896:         }
 6897:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6898:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6899:         }
 6900:     } elsif (scalar(@array) == 2) {
 6901:         my $location = length($array[0]);
 6902:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6903:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6904:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6905:             if ($ans eq $line_num) {
 6906:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6907:             } else {
 6908:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6909:             }
 6910:             $ansnum++;
 6911:          }
 6912:     } else {
 6913:         #  If there's more than one instance of a bubble character
 6914:         #  That's a double bubble; with positional notation we can
 6915:         #  record all the bubbles filled in as well as the
 6916:         #  fact this response consists of multiple bubbles.
 6917:         #
 6918:         my $responsenum = $questnum-1;
 6919:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6920:             $responsenum = $respnumlookup->{$questnum-1}
 6921:         }
 6922:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6923:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6924:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6925:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6926:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6927:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6928:             my $doubleerror = 0;
 6929:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6930:                    (!$doubleerror)) {
 6931:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6932:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6933:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6934:                if (length(@currarray) > 2) {
 6935:                    $doubleerror = 1;
 6936:                } 
 6937:             }
 6938:             if ($doubleerror) {
 6939:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6940:             }
 6941:         } else {
 6942:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6943:         }
 6944:         my $item = $ansnum;
 6945:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6946:             $record->{"scantron.$item.answer"} = '';
 6947:             $item ++;
 6948:         }
 6949: 
 6950:         my @ans=@array;
 6951:         my $i=0;
 6952:         my $increment = 0;
 6953:         while ($#ans) {
 6954:             $i+=length($ans[0]) + $increment;
 6955:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6956:             my $bubble = $i%$$scantron_config{'Qlength'};
 6957:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6958:             shift(@ans);
 6959:             $increment = 1;
 6960:         }
 6961:         $ansnum += $answers_needed;
 6962:     }
 6963:     return $ansnum;
 6964: }
 6965: 
 6966: =pod
 6967: 
 6968: =item scantron_add_delay
 6969: 
 6970:    Adds an error message that occurred during the grading phase to a
 6971:    queue of messages to be shown after grading pass is complete
 6972: 
 6973:  Arguments:
 6974:    $delayqueue  - arrary ref of hash ref of error messages
 6975:    $scanline    - the scanline that caused the error
 6976:    $errormesage - the error message
 6977:    $errorcode   - a numeric code for the error
 6978: 
 6979:  Side Effects:
 6980:    updates the $delayqueue to have a new hash ref of the error
 6981: 
 6982: =cut
 6983: 
 6984: sub scantron_add_delay {
 6985:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6986:     push(@$delayqueue,
 6987: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6988: 	  'ecode' => $errorcode }
 6989: 	 );
 6990: }
 6991: 
 6992: =pod
 6993: 
 6994: =item scantron_find_student
 6995: 
 6996:    Finds the username for the current scanline
 6997: 
 6998:   Arguments:
 6999:    $scantron_record - hash result from scantron_parse_scanline
 7000:    $scan_data       - hash of correction information 
 7001:                       (see &scantron_getfile() form more information)
 7002:    $idmap           - hash from &username_to_idmap()
 7003:    $line            - number of current scanline
 7004:  
 7005:   Returns:
 7006:    Either 'username:domain' or undef if unknown
 7007: 
 7008: =cut
 7009: 
 7010: sub scantron_find_student {
 7011:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 7012:     my $scanID=$$scantron_record{'scantron.ID'};
 7013:     if ($scanID =~ /^\s*$/) {
 7014:  	return &scan_data($scan_data,"$line.user");
 7015:     }
 7016:     foreach my $id (keys(%$idmap)) {
 7017:  	if (lc($id) eq lc($scanID)) {
 7018:  	    return $$idmap{$id};
 7019:  	}
 7020:     }
 7021:     return undef;
 7022: }
 7023: 
 7024: =pod
 7025: 
 7026: =item scantron_filter
 7027: 
 7028:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7029:    hidden resources was selected
 7030: 
 7031: =cut
 7032: 
 7033: sub scantron_filter {
 7034:     my ($curres)=@_;
 7035: 
 7036:     if (ref($curres) && $curres->is_problem()) {
 7037: 	# if the user has asked to not have either hidden
 7038: 	# or 'randomout' controlled resources to be graded
 7039: 	# don't include them
 7040: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7041: 	    && $curres->randomout) {
 7042: 	    return 0;
 7043: 	}
 7044: 	return 1;
 7045:     }
 7046:     return 0;
 7047: }
 7048: 
 7049: =pod
 7050: 
 7051: =item scantron_process_corrections
 7052: 
 7053:    Gets correction information out of submitted form data and corrects
 7054:    the scanline
 7055: 
 7056: =cut
 7057: 
 7058: sub scantron_process_corrections {
 7059:     my ($r) = @_;
 7060:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7061:     my ($scanlines,$scan_data)=&scantron_getfile();
 7062:     my $classlist=&Apache::loncoursedata::get_classlist();
 7063:     my $which=$env{'form.scantron_line'};
 7064:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7065:     my ($skip,$err,$errmsg);
 7066:     if ($env{'form.scantron_skip_record'}) {
 7067: 	$skip=1;
 7068:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7069: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7070: 	    $env{'form.scantron_domain'};
 7071: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7072: 	($line,$err,$errmsg)=
 7073: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7074: 				     'ID',{'newid'=>$newid,
 7075: 				    'username'=>$env{'form.scantron_username'},
 7076: 				    'domain'=>$env{'form.scantron_domain'}});
 7077:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7078: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7079: 	my $newCODE;
 7080: 	my %args;
 7081: 	if      ($resolution eq 'use_unfound') {
 7082: 	    $newCODE='use_unfound';
 7083: 	} elsif ($resolution eq 'use_found') {
 7084: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7085: 	} elsif ($resolution eq 'use_typed') {
 7086: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7087: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7088: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7089: 	}
 7090: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7091: 	    $args{'CODE_ignore_dup'}=1;
 7092: 	}
 7093: 	$args{'CODE'}=$newCODE;
 7094: 	($line,$err,$errmsg)=
 7095: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7096: 				     'CODE',\%args);
 7097:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7098: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7099: 	    ($line,$err,$errmsg)=
 7100: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7101: 					 $which,'answer',
 7102: 					 { 'question'=>$question,
 7103: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7104:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7105: 	    if ($err) { last; }
 7106: 	}
 7107:     }
 7108:     if ($err) {
 7109:         $r->print(
 7110:             '<p class="LC_error">'
 7111:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7112:                 $errmsg)
 7113:            .'</p>');
 7114:     } else {
 7115: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7116: 	&scantron_putfile($scanlines,$scan_data);
 7117:     }
 7118: }
 7119: 
 7120: =pod
 7121: 
 7122: =item reset_skipping_status
 7123: 
 7124:    Forgets the current set of remember skipped scanlines (and thus
 7125:    reverts back to considering all lines in the
 7126:    scantron_skipped_<filename> file)
 7127: 
 7128: =cut
 7129: 
 7130: sub reset_skipping_status {
 7131:     my ($scanlines,$scan_data)=&scantron_getfile();
 7132:     &scan_data($scan_data,'remember_skipping',undef,1);
 7133:     &scantron_putfile(undef,$scan_data);
 7134: }
 7135: 
 7136: =pod
 7137: 
 7138: =item start_skipping
 7139: 
 7140:    Marks a scanline to be skipped. 
 7141: 
 7142: =cut
 7143: 
 7144: sub start_skipping {
 7145:     my ($scan_data,$i)=@_;
 7146:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7147:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7148: 	$remembered{$i}=2;
 7149:     } else {
 7150: 	$remembered{$i}=1;
 7151:     }
 7152:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7153: }
 7154: 
 7155: =pod
 7156: 
 7157: =item should_be_skipped
 7158: 
 7159:    Checks whether a scanline should be skipped.
 7160: 
 7161: =cut
 7162: 
 7163: sub should_be_skipped {
 7164:     my ($scanlines,$scan_data,$i)=@_;
 7165:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7166: 	# not redoing old skips
 7167: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7168: 	return 0;
 7169:     }
 7170:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7171: 
 7172:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7173: 	return 0;
 7174:     }
 7175:     return 1;
 7176: }
 7177: 
 7178: =pod
 7179: 
 7180: =item remember_current_skipped
 7181: 
 7182:    Discovers what scanlines are in the scantron_skipped_<filename>
 7183:    file and remembers them into scan_data for later use.
 7184: 
 7185: =cut
 7186: 
 7187: sub remember_current_skipped {
 7188:     my ($scanlines,$scan_data)=&scantron_getfile();
 7189:     my %to_remember;
 7190:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7191: 	if ($scanlines->{'skipped'}[$i]) {
 7192: 	    $to_remember{$i}=1;
 7193: 	}
 7194:     }
 7195: 
 7196:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7197:     &scantron_putfile(undef,$scan_data);
 7198: }
 7199: 
 7200: =pod
 7201: 
 7202: =item check_for_error
 7203: 
 7204:     Checks if there was an error when attempting to remove a specific
 7205:     scantron_.. bubblesheet data file. Prints out an error if
 7206:     something went wrong.
 7207: 
 7208: =cut
 7209: 
 7210: sub check_for_error {
 7211:     my ($r,$result)=@_;
 7212:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7213: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7214:     }
 7215: }
 7216: 
 7217: =pod
 7218: 
 7219: =item scantron_warning_screen
 7220: 
 7221:    Interstitial screen to make sure the operator has selected the
 7222:    correct options before we start the validation phase.
 7223: 
 7224: =cut
 7225: 
 7226: sub scantron_warning_screen {
 7227:     my ($button_text,$symb)=@_;
 7228:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7229:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7230:     my $CODElist;
 7231:     if ($scantron_config{'CODElocation'} &&
 7232: 	$scantron_config{'CODEstart'} &&
 7233: 	$scantron_config{'CODElength'}) {
 7234: 	$CODElist=$env{'form.scantron_CODElist'};
 7235: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7236: 	$CODElist=
 7237: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7238: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7239:     }
 7240:     my $lastbubblepoints;
 7241:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7242:         $lastbubblepoints =
 7243:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7244:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7245:     }
 7246:     return '
 7247: <p>
 7248: <span class="LC_warning">
 7249: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7250: </p>
 7251: <table>
 7252: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7253: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7254: '.$CODElist.$lastbubblepoints.'
 7255: </table>
 7256: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7257: '.&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>
 7258: ';
 7259: }
 7260: 
 7261: =pod
 7262: 
 7263: =item scantron_do_warning
 7264: 
 7265:    Check if the operator has picked something for all required
 7266:    fields. Error out if something is missing.
 7267: 
 7268: =cut
 7269: 
 7270: sub scantron_do_warning {
 7271:     my ($r,$symb)=@_;
 7272:     if (!$symb) {return '';}
 7273:     my $default_form_data=&defaultFormData($symb);
 7274:     $r->print(&scantron_form_start().$default_form_data);
 7275:     if ( $env{'form.selectpage'} eq '' ||
 7276: 	 $env{'form.scantron_selectfile'} eq '' ||
 7277: 	 $env{'form.scantron_format'} eq '' ) {
 7278: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7279: 	if ( $env{'form.selectpage'} eq '') {
 7280: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7281: 	} 
 7282: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7283: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7284: 	}
 7285: 	if ( $env{'form.scantron_format'} eq '') {
 7286: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7287: 	}
 7288:     } else {
 7289: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7290:         my ($checksec,@possibles) = &gradable_sections();
 7291:         my $gradesections;
 7292:         if ($checksec) {
 7293:             my $file=$env{'form.scantron_selectfile'};
 7294:             if (&valid_file($file)) {
 7295:                 my %bysec = &scantron_get_sections();
 7296:                 my $table;
 7297:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7298:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7299:                     $table = &Apache::loncommon::start_data_table()."\n".
 7300:                              &Apache::loncommon::start_data_table_header_row().
 7301:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7302:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7303:                     if ($bysec{'none'}) {
 7304:                         $table .= &Apache::loncommon::start_data_table_row().
 7305:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7306:                                   &Apache::loncommon::end_data_table_row()."\n";
 7307:                     }
 7308:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7309:                         next if ($sec eq 'none');
 7310:                         $table .= &Apache::loncommon::start_data_table_row().
 7311:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7312:                                   &Apache::loncommon::end_data_table_row()."\n";
 7313:                     }
 7314:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7315:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7316:                                       '<p>'.$table.'</p>';
 7317:                     if (@possibles) {
 7318:                         $gradesections .= '<p>'.
 7319:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7320:                                               scalar(@possibles)).'<br />'.
 7321:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7322:                                               '<i>'.$checksec.'</i>').' ';
 7323:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7324:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7325:                         }
 7326:                         $gradesections .= '</p>';
 7327:                     }
 7328:                 }
 7329:             } else {
 7330:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7331:             }
 7332:         }
 7333:         my $bubbledbyhand=&hand_bubble_option();
 7334: 	$r->print('
 7335: '.$warning.$gradesections.$bubbledbyhand.'
 7336: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7337: <input type="hidden" name="command" value="scantron_validate" />
 7338: ');
 7339:     }
 7340:     $r->print("</form><br />");
 7341:     return '';
 7342: }
 7343: 
 7344: =pod
 7345: 
 7346: =item scantron_form_start
 7347: 
 7348:     html hidden input for remembering all selected grading options
 7349: 
 7350: =cut
 7351: 
 7352: sub scantron_form_start {
 7353:     my ($max_bubble)=@_;
 7354:     my $result= <<SCANTRONFORM;
 7355: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7356:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7357:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7358:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7359:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7360:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7361:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7362:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7363:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7364:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7365: SCANTRONFORM
 7366: 
 7367:   my $line = 0;
 7368:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7369:        my $chunk =
 7370: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7371:        $chunk .=
 7372: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7373:        $chunk .= 
 7374:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7375:        $chunk .=
 7376:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7377:        $chunk .=
 7378:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7379:        $result .= $chunk;
 7380:        $line++;
 7381:     }
 7382:     return $result;
 7383: }
 7384: 
 7385: =pod
 7386: 
 7387: =item scantron_validate_file
 7388: 
 7389:     Dispatch routine for doing validation of a bubblesheet data file.
 7390: 
 7391:     Also processes any necessary information resets that need to
 7392:     occur before validation begins (ignore previous corrections,
 7393:     restarting the skipped records processing)
 7394: 
 7395: =cut
 7396: 
 7397: sub scantron_validate_file {
 7398:     my ($r,$symb) = @_;
 7399:     if (!$symb) {return '';}
 7400:     my $default_form_data=&defaultFormData($symb);
 7401:     
 7402:     # do the detection of only doing skipped records first before we delete
 7403:     # them when doing the corrections reset
 7404:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7405: 	&reset_skipping_status();
 7406:     }
 7407:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7408: 	&remember_current_skipped();
 7409: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7410:     }
 7411: 
 7412:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7413: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7414: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7415: 	&check_for_error($r,&scantron_remove_scan_data());
 7416: 	$env{'form.scantron_options_ignore'}='done';
 7417:     }
 7418: 
 7419:     if ($env{'form.scantron_corrections'}) {
 7420: 	&scantron_process_corrections($r);
 7421:     }
 7422: 
 7423:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7424:     my ($checksec,@gradable);
 7425:     if ($env{'request.course.sec'}) {
 7426:         ($checksec,my @possibles) = &gradable_sections();
 7427:         if ($checksec) {
 7428:             if (@possibles) {
 7429:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7430:                 if (@chosensecs) {
 7431:                     foreach my $sec (@chosensecs) {
 7432:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7433:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7434:                                 push(@gradable,$sec);
 7435:                             }
 7436:                         }
 7437:                     }
 7438:                 }
 7439:             }
 7440:             $r->print('<p><table>');
 7441:             if (@gradable) {
 7442:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7443:                 $r->print(
 7444:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7445:             } else {
 7446:                 $r->print(
 7447:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7448:             }
 7449:             $r->print('</table></p>');
 7450:         }
 7451:     }
 7452:     $r->rflush();
 7453: 
 7454:     #get the student pick code ready
 7455:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7456:     my $nav_error;
 7457:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7458:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7459:     if ($nav_error) {
 7460:         $r->print(&navmap_errormsg());
 7461:         return '';
 7462:     }
 7463:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7464:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7465:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7466:     }
 7467:     $r->print($result);
 7468:     
 7469:     my @validate_phases=( 'sequence',
 7470: 			  'ID',
 7471: 			  'CODE',
 7472: 			  'doublebubble',
 7473: 			  'missingbubbles');
 7474:     if (!$env{'form.validatepass'}) {
 7475: 	$env{'form.validatepass'} = 0;
 7476:     }
 7477:     my $currentphase=$env{'form.validatepass'};
 7478:     my %skipbysec=();
 7479: 
 7480:     my $stop=0;
 7481:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7482: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7483: 	$r->rflush();
 7484:      
 7485: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7486: 	{
 7487: 	    no strict 'refs';
 7488:             my @extras=();
 7489:             if ($validate_phases[$currentphase] eq 'ID') {
 7490:                 @extras = (\%skipbysec,$checksec,@gradable);
 7491:             }
 7492: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7493: 	}
 7494:     }
 7495:     if (!$stop) {
 7496: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7497:         my $secinfo;
 7498:         if (keys(%skipbysec) > 0) {
 7499:             my $seclist = '<ul>';
 7500:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7501:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7502:             }
 7503:             $seclist .= '</ul>';
 7504:             $secinfo = '<p class="LC_info">'.
 7505:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7506:                            $seclist).
 7507:                        '</p>';
 7508:         }
 7509: 	$r->print(&mt('Validation process complete.').'<br />'.
 7510:                   $secinfo.$warning.
 7511:                   &mt('Perform verification for each student after storage of submissions?').
 7512:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7513:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7514:                   ('&nbsp;'x3).'<label>'.
 7515:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7516:                   '</label></span><br />'.
 7517:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7518:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7519:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7520:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7521:     } else {
 7522: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7523: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7524:     }
 7525:     if ($stop) {
 7526: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7527: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7528: 	    $r->print(' '.&mt('this error').' <br />');
 7529: 
 7530: 	    $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>');
 7531: 	} else {
 7532:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7533: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7534:             } else {
 7535:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7536:             }
 7537: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7538: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7539: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7540: 	}
 7541:     }
 7542:     $r->print(" </form><br />");
 7543:     return '';
 7544: }
 7545: 
 7546: 
 7547: =pod
 7548: 
 7549: =item scantron_remove_file
 7550: 
 7551:    Removes the requested bubblesheet data file, makes sure that
 7552:    scantron_original_<filename> is never removed
 7553: 
 7554: 
 7555: =cut
 7556: 
 7557: sub scantron_remove_file {
 7558:     my ($which)=@_;
 7559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7561:     my $file='scantron_';
 7562:     if ($which eq 'corrected' || $which eq 'skipped') {
 7563: 	$file.=$which.'_';
 7564:     } else {
 7565: 	return 'refused';
 7566:     }
 7567:     $file.=$env{'form.scantron_selectfile'};
 7568:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7569: }
 7570: 
 7571: 
 7572: =pod
 7573: 
 7574: =item scantron_remove_scan_data
 7575: 
 7576:    Removes all scan_data correction for the requested bubblesheet
 7577:    data file.  (In the case that both the are doing skipped records we need
 7578:    to remember the old skipped lines for the time being so that element
 7579:    persists for a while.)
 7580: 
 7581: =cut
 7582: 
 7583: sub scantron_remove_scan_data {
 7584:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7585:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7586:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7587:     my @todelete;
 7588:     my $filename=$env{'form.scantron_selectfile'};
 7589:     foreach my $key (@keys) {
 7590: 	if ($key=~/^\Q$filename\E_/) {
 7591: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7592: 		$key=~/remember_skipping/) {
 7593: 		next;
 7594: 	    }
 7595: 	    push(@todelete,$key);
 7596: 	}
 7597:     }
 7598:     my $result;
 7599:     if (@todelete) {
 7600: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7601: 				       \@todelete,$cdom,$cname);
 7602:     } else {
 7603: 	$result = 'ok';
 7604:     }
 7605:     return $result;
 7606: }
 7607: 
 7608: 
 7609: =pod
 7610: 
 7611: =item scantron_getfile
 7612: 
 7613:     Fetches the requested bubblesheet data file (all 3 versions), and
 7614:     the scan_data hash
 7615:   
 7616:   Arguments:
 7617:     None
 7618: 
 7619:   Returns:
 7620:     2 hash references
 7621: 
 7622:      - first one has 
 7623:          orig      -
 7624:          corrected -
 7625:          skipped   -  each of which points to an array ref of the specified
 7626:                       file broken up into individual lines
 7627:          count     - number of scanlines
 7628:  
 7629:      - second is the scan_data hash possible keys are
 7630:        ($number refers to scanline numbered $number and thus the key affects
 7631:         only that scanline
 7632:         $bubline refers to the specific bubble line element and the aspects
 7633:         refers to that specific bubble line element)
 7634: 
 7635:        $number.user - username:domain to use
 7636:        $number.CODE_ignore_dup 
 7637:                     - ignore the duplicate CODE error 
 7638:        $number.useCODE
 7639:                     - use the CODE in the scanline as is
 7640:        $number.no_bubble.$bubline
 7641:                     - it is valid that there is no bubbled in bubble
 7642:                       at $number $bubline
 7643:        remember_skipping
 7644:                     - a frozen hash containing keys of $number and values
 7645:                       of either 
 7646:                         1 - we are on a 'do skipped records pass' and plan
 7647:                             on processing this line
 7648:                         2 - we are on a 'do skipped records pass' and this
 7649:                             scanline has been marked to skip yet again
 7650: 
 7651: =cut
 7652: 
 7653: sub scantron_getfile {
 7654:     #FIXME really would prefer a scantron directory
 7655:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7656:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7657:     my $lines;
 7658:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7659: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7660:     my %scanlines;
 7661:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7662:     my $temp=$scanlines{'orig'};
 7663:     $scanlines{'count'}=$#$temp;
 7664: 
 7665:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7666: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7667:     if ($lines eq '-1') {
 7668: 	$scanlines{'corrected'}=[];
 7669:     } else {
 7670: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7671:     }
 7672:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7673: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7674:     if ($lines eq '-1') {
 7675: 	$scanlines{'skipped'}=[];
 7676:     } else {
 7677: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7678:     }
 7679:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7680:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7681:     my %scan_data = @tmp;
 7682:     return (\%scanlines,\%scan_data);
 7683: }
 7684: 
 7685: =pod
 7686: 
 7687: =item lonnet_putfile
 7688: 
 7689:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7690: 
 7691:  Arguments:
 7692:    $contents - data to store
 7693:    $filename - filename to store $contents into
 7694: 
 7695:  Returns:
 7696:    result value from &Apache::lonnet::finishuserfileupload
 7697: 
 7698: =cut
 7699: 
 7700: sub lonnet_putfile {
 7701:     my ($contents,$filename)=@_;
 7702:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7703:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7704:     $env{'form.sillywaytopassafilearound'}=$contents;
 7705:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7706: 
 7707: }
 7708: 
 7709: =pod
 7710: 
 7711: =item scantron_putfile
 7712: 
 7713:     Stores the current version of the bubblesheet data files, and the
 7714:     scan_data hash. (Does not modify the original version only the
 7715:     corrected and skipped versions.
 7716: 
 7717:  Arguments:
 7718:     $scanlines - hash ref that looks like the first return value from
 7719:                  &scantron_getfile()
 7720:     $scan_data - hash ref that looks like the second return value from
 7721:                  &scantron_getfile()
 7722: 
 7723: =cut
 7724: 
 7725: sub scantron_putfile {
 7726:     my ($scanlines,$scan_data) = @_;
 7727:     #FIXME really would prefer a scantron directory
 7728:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7729:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7730:     if ($scanlines) {
 7731: 	my $prefix='scantron_';
 7732: # no need to update orig, shouldn't change
 7733: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7734: #		    $env{'form.scantron_selectfile'});
 7735: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7736: 			$prefix.'corrected_'.
 7737: 			$env{'form.scantron_selectfile'});
 7738: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7739: 			$prefix.'skipped_'.
 7740: 			$env{'form.scantron_selectfile'});
 7741:     }
 7742:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7743: }
 7744: 
 7745: =pod
 7746: 
 7747: =item scantron_get_line
 7748: 
 7749:    Returns the correct version of the scanline
 7750: 
 7751:  Arguments:
 7752:     $scanlines - hash ref that looks like the first return value from
 7753:                  &scantron_getfile()
 7754:     $scan_data - hash ref that looks like the second return value from
 7755:                  &scantron_getfile()
 7756:     $i         - number of the requested line (starts at 0)
 7757: 
 7758:  Returns:
 7759:    A scanline, (either the original or the corrected one if it
 7760:    exists), or undef if the requested scanline should be
 7761:    skipped. (Either because it's an skipped scanline, or it's an
 7762:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7763:    pass.
 7764: 
 7765: =cut
 7766: 
 7767: sub scantron_get_line {
 7768:     my ($scanlines,$scan_data,$i)=@_;
 7769:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7770:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7771:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7772:     return $scanlines->{'orig'}[$i]; 
 7773: }
 7774: 
 7775: =pod
 7776: 
 7777: =item scantron_todo_count
 7778: 
 7779:     Counts the number of scanlines that need processing.
 7780: 
 7781:  Arguments:
 7782:     $scanlines - hash ref that looks like the first return value from
 7783:                  &scantron_getfile()
 7784:     $scan_data - hash ref that looks like the second return value from
 7785:                  &scantron_getfile()
 7786: 
 7787:  Returns:
 7788:     $count - number of scanlines to process
 7789: 
 7790: =cut
 7791: 
 7792: sub get_todo_count {
 7793:     my ($scanlines,$scan_data)=@_;
 7794:     my $count=0;
 7795:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7796: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7797: 	if ($line=~/^[\s\cz]*$/) { next; }
 7798: 	$count++;
 7799:     }
 7800:     return $count;
 7801: }
 7802: 
 7803: =pod
 7804: 
 7805: =item scantron_put_line
 7806: 
 7807:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7808:     data file.
 7809: 
 7810:  Arguments:
 7811:     $scanlines - hash ref that looks like the first return value from
 7812:                  &scantron_getfile()
 7813:     $scan_data - hash ref that looks like the second return value from
 7814:                  &scantron_getfile()
 7815:     $i         - line number to update
 7816:     $newline   - contents of the updated scanline
 7817:     $skip      - if true make the line for skipping and update the
 7818:                  'skipped' file
 7819: 
 7820: =cut
 7821: 
 7822: sub scantron_put_line {
 7823:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7824:     if ($skip) {
 7825: 	$scanlines->{'skipped'}[$i]=$newline;
 7826: 	&start_skipping($scan_data,$i);
 7827: 	return;
 7828:     }
 7829:     $scanlines->{'corrected'}[$i]=$newline;
 7830: }
 7831: 
 7832: =pod
 7833: 
 7834: =item scantron_clear_skip
 7835: 
 7836:    Remove a line from the 'skipped' file
 7837: 
 7838:  Arguments:
 7839:     $scanlines - hash ref that looks like the first return value from
 7840:                  &scantron_getfile()
 7841:     $scan_data - hash ref that looks like the second return value from
 7842:                  &scantron_getfile()
 7843:     $i         - line number to update
 7844: 
 7845: =cut
 7846: 
 7847: sub scantron_clear_skip {
 7848:     my ($scanlines,$scan_data,$i)=@_;
 7849:     if (exists($scanlines->{'skipped'}[$i])) {
 7850: 	undef($scanlines->{'skipped'}[$i]);
 7851: 	return 1;
 7852:     }
 7853:     return 0;
 7854: }
 7855: 
 7856: =pod
 7857: 
 7858: =item scantron_filter_not_exam
 7859: 
 7860:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7861:    filter out resources that are not marked as 'exam' mode
 7862: 
 7863: =cut
 7864: 
 7865: sub scantron_filter_not_exam {
 7866:     my ($curres)=@_;
 7867:     
 7868:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7869: 	# if the user has asked to not have either hidden
 7870: 	# or 'randomout' controlled resources to be graded
 7871: 	# don't include them
 7872: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7873: 	    && $curres->randomout) {
 7874: 	    return 0;
 7875: 	}
 7876: 	return 1;
 7877:     }
 7878:     return 0;
 7879: }
 7880: 
 7881: =pod
 7882: 
 7883: =item scantron_validate_sequence
 7884: 
 7885:     Validates the selected sequence, checking for resource that are
 7886:     not set to exam mode.
 7887: 
 7888: =cut
 7889: 
 7890: sub scantron_validate_sequence {
 7891:     my ($r,$currentphase) = @_;
 7892: 
 7893:     my $navmap=Apache::lonnavmaps::navmap->new();
 7894:     unless (ref($navmap)) {
 7895:         $r->print(&navmap_errormsg());
 7896:         return (1,$currentphase);
 7897:     }
 7898:     my (undef,undef,$sequence)=
 7899: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7900: 
 7901:     my $map=$navmap->getResourceByUrl($sequence);
 7902: 
 7903:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7904:                                     value="ignore" />');
 7905:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7906: 	my @resources=
 7907: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7908: 	if (@resources) {
 7909: 	    $r->print(
 7910:                 '<p class="LC_warning">'
 7911:                .&mt('Some resources in the sequence currently are not set to'
 7912:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7913:                    .' work correctly.')
 7914:                .'</p>'
 7915:             );
 7916: 	    return (1,$currentphase);
 7917: 	}
 7918:     }
 7919: 
 7920:     return (0,$currentphase+1);
 7921: }
 7922: 
 7923: 
 7924: 
 7925: sub scantron_validate_ID {
 7926:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7927:     
 7928:     #get student info
 7929:     my $classlist=&Apache::loncoursedata::get_classlist();
 7930:     my %idmap=&username_to_idmap($classlist);
 7931:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7932: 
 7933:     #get scantron line setup
 7934:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7935:     my ($scanlines,$scan_data)=&scantron_getfile();
 7936: 
 7937:     my $nav_error;
 7938:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7939:     if ($nav_error) {
 7940:         $r->print(&navmap_errormsg());
 7941:         return(1,$currentphase);
 7942:     }
 7943: 
 7944:     my %found=('ids'=>{},'usernames'=>{});
 7945:     my $unsavedskips = 0;
 7946:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7947: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7948: 	if ($line=~/^[\s\cz]*$/) { next; }
 7949: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7950: 						 $scan_data);
 7951: 	my $id=$$scan_record{'scantron.ID'};
 7952: 	my $found;
 7953: 	foreach my $checkid (keys(%idmap)) {
 7954: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7955: 	}
 7956: 	if ($found) {
 7957: 	    my $username=$idmap{$found};
 7958:             if ($checksec) {
 7959:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7960:                     my $stusec = $classlist->{$username}->[$secidx];
 7961:                     if ($stusec ne $checksec) {
 7962:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7963:                             my $skip=1;
 7964:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7965:                             if (ref($skipbysec) eq 'HASH') {
 7966:                                 if ($stusec eq '') {
 7967:                                     $skipbysec->{'none'} ++;
 7968:                                 } else {
 7969:                                     $skipbysec->{$stusec} ++;
 7970:                                 }
 7971:                             }
 7972:                             $unsavedskips ++;
 7973:                             next;
 7974:                         }
 7975:                     }
 7976:                 }
 7977:             }
 7978: 	    if ($found{'ids'}{$found}) {
 7979: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7980: 					 $line,'duplicateID',$found);
 7981:                 if ($unsavedskips) {
 7982:                     &scantron_putfile($scanlines,$scan_data);
 7983:                     $unsavedskips = 0;
 7984:                 }
 7985: 		return(1,$currentphase);
 7986: 	    } elsif ($found{'usernames'}{$username}) {
 7987: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7988: 					 $line,'duplicateID',$username);
 7989:                 if ($unsavedskips) {
 7990:                     &scantron_putfile($scanlines,$scan_data);
 7991:                     $unsavedskips = 0;
 7992:                 }
 7993: 		return(1,$currentphase);
 7994: 	    }
 7995: 	    #FIXME store away line we previously saw the ID on to use above
 7996: 	    $found{'ids'}{$found}++;
 7997: 	    $found{'usernames'}{$username}++;
 7998: 	} else {
 7999: 	    if ($id =~ /^\s*$/) {
 8000: 		my $username=&scan_data($scan_data,"$i.user");
 8001:                 if (($checksec && $username ne '')) {
 8002:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 8003:                         my $stusec = $classlist->{$username}->[$secidx];
 8004:                         if ($stusec ne $checksec) {
 8005:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 8006:                                 my $skip=1;
 8007:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 8008:                                 if (ref($skipbysec) eq 'HASH') {
 8009:                                     if ($stusec eq '') {
 8010:                                         $skipbysec->{'none'} ++;
 8011:                                     } else {
 8012:                                         $skipbysec->{$stusec} ++;
 8013:                                     }
 8014:                                 }
 8015:                                 $unsavedskips ++;
 8016:                                 next;
 8017:                             }
 8018:                         }
 8019:                     }
 8020: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 8021: 		    &scantron_get_correction($r,$i,$scan_record,
 8022: 					     \%scantron_config,
 8023: 					     $line,'duplicateID',$username);
 8024:                     if ($unsavedskips) {
 8025:                         &scantron_putfile($scanlines,$scan_data);
 8026:                         $unsavedskips = 0;
 8027:                     }
 8028: 		    return(1,$currentphase);
 8029: 		} elsif (!defined($username)) {
 8030: 		    &scantron_get_correction($r,$i,$scan_record,
 8031: 					     \%scantron_config,
 8032: 					     $line,'incorrectID');
 8033:                     if ($unsavedskips) {
 8034:                         &scantron_putfile($scanlines,$scan_data);
 8035:                         $unsavedskips = 0;
 8036:                     }
 8037: 		    return(1,$currentphase);
 8038: 		}
 8039: 		$found{'usernames'}{$username}++;
 8040: 	    } else {
 8041: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8042: 					 $line,'incorrectID');
 8043:                 if ($unsavedskips) {
 8044:                     &scantron_putfile($scanlines,$scan_data);
 8045:                     $unsavedskips = 0;
 8046:                 }
 8047: 		return(1,$currentphase);
 8048: 	    }
 8049: 	}
 8050:     }
 8051:     if ($unsavedskips) {
 8052:         &scantron_putfile($scanlines,$scan_data);
 8053:         $unsavedskips = 0;
 8054:     }
 8055:     return (0,$currentphase+1);
 8056: }
 8057: 
 8058: sub scantron_get_sections {
 8059:     my %bysec;
 8060:     if ($env{'form.scantron_format'} ne '') {
 8061:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8062:         my ($scanlines,$scan_data)=&scantron_getfile();
 8063:         my $classlist=&Apache::loncoursedata::get_classlist();
 8064:         my %idmap=&username_to_idmap($classlist);
 8065:         foreach my $key (keys(%idmap)) {
 8066:             my $lckey = lc($key);
 8067:             $idmap{$lckey} = $idmap{$key};
 8068:         }
 8069:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 8070:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8071:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8072:             if ($line=~/^[\s\cz]*$/) { next; }
 8073:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8074:                                                      $scan_data);
 8075:             my $id=lc($$scan_record{'scantron.ID'});
 8076:             if (exists($idmap{$id})) {
 8077:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 8078:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 8079:                     if ($stusec eq '') {
 8080:                         $bysec{'none'} ++;
 8081:                     } else {
 8082:                         $bysec{$stusec} ++;
 8083:                     }
 8084:                 }
 8085:             }
 8086:         }
 8087:     }
 8088:     return %bysec;
 8089: }
 8090: 
 8091: sub scantron_get_correction {
 8092:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 8093:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 8094: #FIXME in the case of a duplicated ID the previous line, probably need
 8095: #to show both the current line and the previous one and allow skipping
 8096: #the previous one or the current one
 8097: 
 8098:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8099:         $r->print(
 8100:             '<p class="LC_warning">'
 8101:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8102:                 "<b>$error</b>",
 8103:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8104:            ."</p> \n");
 8105:     } else {
 8106:         $r->print(
 8107:             '<p class="LC_warning">'
 8108:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8109:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8110:            ."</p> \n");
 8111:     }
 8112:     my $message =
 8113:         '<p>'
 8114:        .&mt('The ID on the form is [_1]',
 8115:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8116:        .'<br />'
 8117:        .&mt('The name on the paper is [_1], [_2]',
 8118:             $$scan_record{'scantron.LastName'},
 8119:             $$scan_record{'scantron.FirstName'})
 8120:        .'</p>';
 8121: 
 8122:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8123:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8124:                            # Array populated for doublebubble or
 8125:     my @lines_to_correct;  # missingbubble errors to build javascript
 8126:                            # to validate radio button checking   
 8127: 
 8128:     if ($error =~ /ID$/) {
 8129: 	if ($error eq 'incorrectID') {
 8130:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8131: 		      "</p>\n");
 8132: 	} elsif ($error eq 'duplicateID') {
 8133:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8134: 	}
 8135: 	$r->print($message);
 8136: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8137: 	$r->print("\n<ul><li> ");
 8138: 	#FIXME it would be nice if this sent back the user ID and
 8139: 	#could do partial userID matches
 8140: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8141: 				       'scantron_username','scantron_domain'));
 8142: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8143: 	$r->print("\n:\n".
 8144: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8145: 
 8146: 	$r->print('</li>');
 8147:     } elsif ($error =~ /CODE$/) {
 8148: 	if ($error eq 'incorrectCODE') {
 8149: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8150: 	} elsif ($error eq 'duplicateCODE') {
 8151: 	    $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");
 8152: 	}
 8153: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8154: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8155:                  ."</p>\n");
 8156: 	$r->print($message);
 8157: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8158: 	$r->print("\n<br /> ");
 8159: 	my $i=0;
 8160: 	if ($error eq 'incorrectCODE' 
 8161: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8162: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8163: 	    if ($closest > 0) {
 8164: 		foreach my $testcode (@{$closest}) {
 8165: 		    my $checked='';
 8166: 		    if (!$i) { $checked=' checked="checked"'; }
 8167: 		    $r->print("
 8168:    <label>
 8169:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8170:        ".&mt("Use the similar CODE [_1] instead.",
 8171: 	    "<b><tt>".$testcode."</tt></b>")."
 8172:     </label>
 8173:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8174: 		    $r->print("\n<br />");
 8175: 		    $i++;
 8176: 		}
 8177: 	    }
 8178: 	}
 8179: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8180: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8181: 	    $r->print("
 8182:     <label>
 8183:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8184:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8185: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8186:     </label>");
 8187: 	    $r->print("\n<br />");
 8188: 	}
 8189: 
 8190: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8191: function change_radio(field) {
 8192:     var slct=document.scantronupload.scantron_CODE_resolution;
 8193:     var i;
 8194:     for (i=0;i<slct.length;i++) {
 8195:         if (slct[i].value==field) { slct[i].checked=true; }
 8196:     }
 8197: }
 8198: ENDSCRIPT
 8199: 	my $href="/adm/pickcode?".
 8200: 	   "form=".&escape("scantronupload").
 8201: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8202: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8203: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8204: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8205: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8206: 	    $r->print("
 8207:     <label>
 8208:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8209:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8210: 	     "<a target='_blank' href='$href'>","</a>")."
 8211:     </label> 
 8212:     ".&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\')" />'));
 8213: 	    $r->print("\n<br />");
 8214: 	}
 8215: 	$r->print("
 8216:     <label>
 8217:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8218:        ".&mt("Use [_1] as the CODE.",
 8219: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8220: 	$r->print("\n<br /><br />");
 8221:     } elsif ($error eq 'doublebubble') {
 8222: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8223: 
 8224: 	# The form field scantron_questions is acutally a list of line numbers.
 8225: 	# represented by this form so:
 8226: 
 8227: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8228:                                                 $respnumlookup,$startline);
 8229: 
 8230: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8231: 		  $line_list.'" />');
 8232: 	$r->print($message);
 8233: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8234: 	foreach my $question (@{$arg}) {
 8235: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8236:                                                    $scan_record, $error,
 8237:                                                    $randomorder,$randompick,
 8238:                                                    $respnumlookup,$startline);
 8239:             push(@lines_to_correct,@linenums);
 8240: 	}
 8241:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8242:     } elsif ($error eq 'missingbubble') {
 8243: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8244: 	$r->print($message);
 8245: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8246: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8247: 
 8248: 	# The form field scantron_questions is actually a list of line numbers not
 8249: 	# a list of question numbers. Therefore:
 8250: 	#
 8251: 
 8252: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8253:                                                 $respnumlookup,$startline);
 8254: 
 8255: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8256: 		  $line_list.'" />');
 8257: 	foreach my $question (@{$arg}) {
 8258: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8259:                                                    $scan_record, $error,
 8260:                                                    $randomorder,$randompick,
 8261:                                                    $respnumlookup,$startline);
 8262:             push(@lines_to_correct,@linenums);
 8263: 	}
 8264:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8265:     } else {
 8266: 	$r->print("\n<ul>");
 8267:     }
 8268:     $r->print("\n</li></ul>");
 8269: }
 8270: 
 8271: sub verify_bubbles_checked {
 8272:     my (@ansnums) = @_;
 8273:     my $ansnumstr = join('","',@ansnums);
 8274:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8275:     &js_escape(\$warning);
 8276:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8277: function verify_bubble_radio(form) {
 8278:     var ansnumArray = new Array ("$ansnumstr");
 8279:     var need_bubble_count = 0;
 8280:     for (var i=0; i<ansnumArray.length; i++) {
 8281:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8282:             var bubble_picked = 0; 
 8283:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8284:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8285:                     bubble_picked = 1;
 8286:                 }
 8287:             }
 8288:             if (bubble_picked == 0) {
 8289:                 need_bubble_count ++;
 8290:             }
 8291:         }
 8292:     }
 8293:     if (need_bubble_count) {
 8294:         alert("$warning");
 8295:         return;
 8296:     }
 8297:     form.submit(); 
 8298: }
 8299: ENDSCRIPT
 8300:     return $output;
 8301: }
 8302: 
 8303: =pod
 8304: 
 8305: =item  questions_to_line_list
 8306: 
 8307: Converts a list of questions into a string of comma separated
 8308: line numbers in the answer sheet used by the questions.  This is
 8309: used to fill in the scantron_questions form field.
 8310: 
 8311:   Arguments:
 8312:      questions    - Reference to an array of questions.
 8313:      randomorder  - True if randomorder in use.
 8314:      randompick   - True if randompick in use.
 8315:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8316:                      for current line to question number used for same question
 8317:                      in "Master Seqence" (as seen by Course Coordinator).
 8318:      startline    - Reference to hash where key is question number (0 is first)
 8319:                     and key is number of first bubble line for current student
 8320:                     or code-based randompick and/or randomorder.
 8321: 
 8322: =cut
 8323: 
 8324: 
 8325: sub questions_to_line_list {
 8326:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8327:     my @lines;
 8328: 
 8329:     foreach my $item (@{$questions}) {
 8330:         my $question = $item;
 8331:         my ($first,$count,$last);
 8332:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8333:             $question = $1;
 8334:             my $subquestion = $2;
 8335:             my $responsenum = $question-1;
 8336:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8337:                 $responsenum = $respnumlookup->{$question-1};
 8338:                 if (ref($startline) eq 'HASH') {
 8339:                     $first = $startline->{$question-1} + 1;
 8340:                 }
 8341:             } else {
 8342:                 $first = $first_bubble_line{$responsenum} + 1;
 8343:             }
 8344:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8345:             my $subcount = 1;
 8346:             while ($subcount<$subquestion) {
 8347:                 $first += $subans[$subcount-1];
 8348:                 $subcount ++;
 8349:             }
 8350:             $count = $subans[$subquestion-1];
 8351:         } else {
 8352:             my $responsenum = $question-1;
 8353:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8354:                 $responsenum = $respnumlookup->{$question-1};
 8355:                 if (ref($startline) eq 'HASH') {
 8356:                     $first = $startline->{$question-1} + 1;
 8357:                 }
 8358:             } else {
 8359:                 $first = $first_bubble_line{$responsenum} + 1;
 8360:             }
 8361: 	    $count   = $bubble_lines_per_response{$responsenum};
 8362:         }
 8363:         $last = $first+$count-1;
 8364:         push(@lines, ($first..$last));
 8365:     }
 8366:     return join(',', @lines);
 8367: }
 8368: 
 8369: =pod 
 8370: 
 8371: =item prompt_for_corrections
 8372: 
 8373: Prompts for a potentially multiline correction to the
 8374: user's bubbling (factors out common code from scantron_get_correction
 8375: for multi and missing bubble cases).
 8376: 
 8377:  Arguments:
 8378:    $r           - Apache request object.
 8379:    $question    - The question number to prompt for.
 8380:    $scan_config - The scantron file configuration hash.
 8381:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8382:    $error       - Type of error
 8383:    $randomorder - True if randomorder in use.
 8384:    $randompick  - True if randompick in use.
 8385:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8386:                     for current line to question number used for same question
 8387:                     in "Master Seqence" (as seen by Course Coordinator).
 8388:    $startline   - Reference to hash where key is question number (0 is first)
 8389:                   and value is number of first bubble line for current student
 8390:                   or code-based randompick and/or randomorder.
 8391: 
 8392: 
 8393:  Implicit inputs:
 8394:    %bubble_lines_per_response   - Starting line numbers for each question.
 8395:                                   Numbered from 0 (but question numbers are from
 8396:                                   1.
 8397:    %first_bubble_line           - Starting bubble line for each question.
 8398:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8399:                                   type problems render as separate sub-questions, 
 8400:                                   in exam mode. This hash contains a 
 8401:                                   comma-separated list of the lines per 
 8402:                                   sub-question.
 8403:    %responsetype_per_response   - essayresponse, formularesponse,
 8404:                                   stringresponse, imageresponse, reactionresponse,
 8405:                                   and organicresponse type problem parts can have
 8406:                                   multiple lines per response if the weight
 8407:                                   assigned exceeds 10.  In this case, only
 8408:                                   one bubble per line is permitted, but more 
 8409:                                   than one line might contain bubbles, e.g.
 8410:                                   bubbling of: line 1 - J, line 2 - J, 
 8411:                                   line 3 - B would assign 22 points.  
 8412: 
 8413: =cut
 8414: 
 8415: sub prompt_for_corrections {
 8416:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8417:         $randompick, $respnumlookup, $startline) = @_;
 8418:     my ($current_line,$lines);
 8419:     my @linenums;
 8420:     my $questionnum = $question;
 8421:     my ($first,$responsenum);
 8422:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8423:         $question = $1;
 8424:         my $subquestion = $2;
 8425:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8426:             $responsenum = $respnumlookup->{$question-1};
 8427:             if (ref($startline) eq 'HASH') {
 8428:                 $first = $startline->{$question-1};
 8429:             }
 8430:         } else {
 8431:             $responsenum = $question-1;
 8432:             $first = $first_bubble_line{$responsenum};
 8433:         }
 8434:         $current_line = $first + 1 ;
 8435:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8436:         my $subcount = 1;
 8437:         while ($subcount<$subquestion) {
 8438:             $current_line += $subans[$subcount-1];
 8439:             $subcount ++;
 8440:         }
 8441:         $lines = $subans[$subquestion-1];
 8442:     } else {
 8443:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8444:             $responsenum = $respnumlookup->{$question-1};
 8445:             if (ref($startline) eq 'HASH') { 
 8446:                 $first = $startline->{$question-1};
 8447:             }
 8448:         } else {
 8449:             $responsenum = $question-1;
 8450:             $first = $first_bubble_line{$responsenum};
 8451:         }
 8452:         $current_line = $first + 1;
 8453:         $lines        = $bubble_lines_per_response{$responsenum};
 8454:     }
 8455:     if ($lines > 1) {
 8456:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8457:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8458:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8459:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8460:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8461:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8462:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8463:             $r->print(
 8464:                 &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)
 8465:                .'<br /><br />'
 8466:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8467:                .'<br />'
 8468:                .&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.')
 8469:                .'<br />'
 8470:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8471:                .'<br /><br />'
 8472:             );
 8473:         } else {
 8474:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8475:         }
 8476:     }
 8477:     for (my $i =0; $i < $lines; $i++) {
 8478:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8479: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8480: 	        		  $questionnum,$error,split('', $selected));
 8481:         push(@linenums,$current_line);
 8482: 	$current_line++;
 8483:     }
 8484:     if ($lines > 1) {
 8485: 	$r->print("<hr /><br />");
 8486:     }
 8487:     return @linenums;
 8488: }
 8489: 
 8490: =pod
 8491: 
 8492: =item scantron_bubble_selector
 8493:   
 8494:    Generates the html radiobuttons to correct a single bubble line
 8495:    possibly showing the existing the selected bubbles if known
 8496: 
 8497:  Arguments:
 8498:     $r           - Apache request object
 8499:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8500:     $line        - Number of the line being displayed.
 8501:     $questionnum - Question number (may include subquestion)
 8502:     $error       - Type of error.
 8503:     @selected    - Array of bubbles picked on this line.
 8504: 
 8505: =cut
 8506: 
 8507: sub scantron_bubble_selector {
 8508:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8509:     my $max=$$scan_config{'Qlength'};
 8510: 
 8511:     my $scmode=$$scan_config{'Qon'};
 8512:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8513:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8514:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8515:             $max=$$scan_config{'BubblesPerRow'};
 8516:             if (($scmode eq 'number') && ($max > 10)) {
 8517:                 $max = 10;
 8518:             } elsif (($scmode eq 'letter') && $max > 26) {
 8519:                 $max = 26;
 8520:             }
 8521:         } else {
 8522:             $max = 10;
 8523:         }
 8524:     }
 8525: 
 8526:     my @alphabet=('A'..'Z');
 8527:     $r->print(&Apache::loncommon::start_data_table().
 8528:               &Apache::loncommon::start_data_table_row());
 8529:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8530:     for (my $i=0;$i<$max+1;$i++) {
 8531: 	$r->print("\n".'<td align="center">');
 8532: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8533: 	else { $r->print('&nbsp;'); }
 8534: 	$r->print('</td>');
 8535:     }
 8536:     $r->print(&Apache::loncommon::end_data_table_row().
 8537:               &Apache::loncommon::start_data_table_row());
 8538:     for (my $i=0;$i<$max;$i++) {
 8539: 	$r->print("\n".
 8540: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8541: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8542:     }
 8543:     my $nobub_checked = ' ';
 8544:     if ($error eq 'missingbubble') {
 8545:         $nobub_checked = ' checked = "checked" ';
 8546:     }
 8547:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8548: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8549:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8550:               $line.'" value="'.$questionnum.'" /></td>');
 8551:     $r->print(&Apache::loncommon::end_data_table_row().
 8552:               &Apache::loncommon::end_data_table());
 8553: }
 8554: 
 8555: =pod
 8556: 
 8557: =item num_matches
 8558: 
 8559:    Counts the number of characters that are the same between the two arguments.
 8560: 
 8561:  Arguments:
 8562:    $orig - CODE from the scanline
 8563:    $code - CODE to match against
 8564: 
 8565:  Returns:
 8566:    $count - integer count of the number of same characters between the
 8567:             two arguments
 8568: 
 8569: =cut
 8570: 
 8571: sub num_matches {
 8572:     my ($orig,$code) = @_;
 8573:     my @code=split(//,$code);
 8574:     my @orig=split(//,$orig);
 8575:     my $same=0;
 8576:     for (my $i=0;$i<scalar(@code);$i++) {
 8577: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8578:     }
 8579:     return $same;
 8580: }
 8581: 
 8582: =pod
 8583: 
 8584: =item scantron_get_closely_matching_CODEs
 8585: 
 8586:    Cycles through all CODEs and finds the set that has the greatest
 8587:    number of same characters as the provided CODE
 8588: 
 8589:  Arguments:
 8590:    $allcodes - hash ref returned by &get_codes()
 8591:    $CODE     - CODE from the current scanline
 8592: 
 8593:  Returns:
 8594:    2 element list
 8595:     - first elements is number of how closely matching the best fit is 
 8596:       (5 means best set has 5 matching characters)
 8597:     - second element is an arrary ref containing the set of valid CODEs
 8598:       that best fit the passed in CODE
 8599: 
 8600: =cut
 8601: 
 8602: sub scantron_get_closely_matching_CODEs {
 8603:     my ($allcodes,$CODE)=@_;
 8604:     my @CODEs;
 8605:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8606: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8607:     }
 8608: 
 8609:     return ($#CODEs,$CODEs[-1]);
 8610: }
 8611: 
 8612: =pod
 8613: 
 8614: =item get_codes
 8615: 
 8616:    Builds a hash which has keys of all of the valid CODEs from the selected
 8617:    set of remembered CODEs.
 8618: 
 8619:  Arguments:
 8620:   $old_name - name of the set of remembered CODEs
 8621:   $cdom     - domain of the course
 8622:   $cnum     - internal course name
 8623: 
 8624:  Returns:
 8625:   %allcodes - keys are the valid CODEs, values are all 1
 8626: 
 8627: =cut
 8628: 
 8629: sub get_codes {
 8630:     my ($old_name, $cdom, $cnum) = @_;
 8631:     if (!$old_name) {
 8632: 	$old_name=$env{'form.scantron_CODElist'};
 8633:     }
 8634:     if (!$cdom) {
 8635: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8636:     }
 8637:     if (!$cnum) {
 8638: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8639:     }
 8640:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8641: 				    $cdom,$cnum);
 8642:     my %allcodes;
 8643:     if ($result{"type\0$old_name"} eq 'number') {
 8644: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8645:     } else {
 8646: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8647:     }
 8648:     return %allcodes;
 8649: }
 8650: 
 8651: =pod
 8652: 
 8653: =item scantron_validate_CODE
 8654: 
 8655:    Validates all scanlines in the selected file to not have any
 8656:    invalid or underspecified CODEs and that none of the codes are
 8657:    duplicated if this was requested.
 8658: 
 8659: =cut
 8660: 
 8661: sub scantron_validate_CODE {
 8662:     my ($r,$currentphase) = @_;
 8663:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8664:     if ($scantron_config{'CODElocation'} &&
 8665: 	$scantron_config{'CODEstart'} &&
 8666: 	$scantron_config{'CODElength'}) {
 8667: 	if (!defined($env{'form.scantron_CODElist'})) {
 8668: 	    &FIXME_blow_up()
 8669: 	}
 8670:     } else {
 8671: 	return (0,$currentphase+1);
 8672:     }
 8673:     
 8674:     my %usedCODEs;
 8675: 
 8676:     my %allcodes=&get_codes();
 8677: 
 8678:     my $nav_error;
 8679:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8680:     if ($nav_error) {
 8681:         $r->print(&navmap_errormsg());
 8682:         return(1,$currentphase);
 8683:     }
 8684: 
 8685:     my ($scanlines,$scan_data)=&scantron_getfile();
 8686:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8687: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8688: 	if ($line=~/^[\s\cz]*$/) { next; }
 8689: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8690: 						 $scan_data);
 8691: 	my $CODE=$$scan_record{'scantron.CODE'};
 8692: 	my $error=0;
 8693: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8694: 	    &scantron_get_correction($r,$i,$scan_record,
 8695: 				     \%scantron_config,
 8696: 				     $line,'incorrectCODE',\%allcodes);
 8697: 	    return(1,$currentphase);
 8698: 	}
 8699: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8700: 	    && !$$scan_record{'scantron.useCODE'}) {
 8701: 	    &scantron_get_correction($r,$i,$scan_record,
 8702: 				     \%scantron_config,
 8703: 				     $line,'incorrectCODE',\%allcodes);
 8704: 	    return(1,$currentphase);
 8705: 	}
 8706: 	if (exists($usedCODEs{$CODE}) 
 8707: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8708: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8709: 	    &scantron_get_correction($r,$i,$scan_record,
 8710: 				     \%scantron_config,
 8711: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8712: 	    return(1,$currentphase);
 8713: 	}
 8714: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8715:     }
 8716:     return (0,$currentphase+1);
 8717: }
 8718: 
 8719: =pod
 8720: 
 8721: =item scantron_validate_doublebubble
 8722: 
 8723:    Validates all scanlines in the selected file to not have any
 8724:    bubble lines with multiple bubbles marked.
 8725: 
 8726: =cut
 8727: 
 8728: sub scantron_validate_doublebubble {
 8729:     my ($r,$currentphase) = @_;
 8730:     #get student info
 8731:     my $classlist=&Apache::loncoursedata::get_classlist();
 8732:     my %idmap=&username_to_idmap($classlist);
 8733:     my (undef,undef,$sequence)=
 8734:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8735: 
 8736:     #get scantron line setup
 8737:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8738:     my ($scanlines,$scan_data)=&scantron_getfile();
 8739: 
 8740:     my $navmap = Apache::lonnavmaps::navmap->new();
 8741:     unless (ref($navmap)) {
 8742:         $r->print(&navmap_errormsg());
 8743:         return(1,$currentphase);
 8744:     }
 8745:     my $map=$navmap->getResourceByUrl($sequence);
 8746:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8747:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8748:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8749:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8750: 
 8751:     my $nav_error;
 8752:     if (ref($map)) {
 8753:         $randomorder = $map->randomorder();
 8754:         $randompick = $map->randompick();
 8755:         if ($randomorder || $randompick) {
 8756:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8757:             if ($nav_error) {
 8758:                 $r->print(&navmap_errormsg());
 8759:                 return(1,$currentphase);
 8760:             }
 8761:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8762:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8763:         }
 8764:     } else {
 8765:         $r->print(&navmap_errormsg());
 8766:         return(1,$currentphase);
 8767:     }
 8768: 
 8769:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8770:     if ($nav_error) {
 8771:         $r->print(&navmap_errormsg());
 8772:         return(1,$currentphase);
 8773:     }
 8774: 
 8775:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8776: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8777: 	if ($line=~/^[\s\cz]*$/) { next; }
 8778: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8779: 						 $scan_data,undef,\%idmap,$randomorder,
 8780:                                                  $randompick,$sequence,\@master_seq,
 8781:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8782:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8783: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8784: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8785: 				 'doublebubble',
 8786: 				 $$scan_record{'scantron.doubleerror'},
 8787:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8788:     	return (1,$currentphase);
 8789:     }
 8790:     return (0,$currentphase+1);
 8791: }
 8792: 
 8793: 
 8794: sub scantron_get_maxbubble {
 8795:     my ($nav_error,$scantron_config) = @_;
 8796:     if (defined($env{'form.scantron_maxbubble'}) &&
 8797: 	$env{'form.scantron_maxbubble'}) {
 8798: 	&restore_bubble_lines();
 8799: 	return $env{'form.scantron_maxbubble'};
 8800:     }
 8801: 
 8802:     my (undef, undef, $sequence) =
 8803: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8804: 
 8805:     my $navmap=Apache::lonnavmaps::navmap->new();
 8806:     unless (ref($navmap)) {
 8807:         if (ref($nav_error)) {
 8808:             $$nav_error = 1;
 8809:         }
 8810:         return;
 8811:     }
 8812:     my $map=$navmap->getResourceByUrl($sequence);
 8813:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8814:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8815: 
 8816:     &Apache::lonxml::clear_problem_counter();
 8817: 
 8818:     my $uname       = $env{'user.name'};
 8819:     my $udom        = $env{'user.domain'};
 8820:     my $cid         = $env{'request.course.id'};
 8821:     my $total_lines = 0;
 8822:     %bubble_lines_per_response = ();
 8823:     %first_bubble_line         = ();
 8824:     %subdivided_bubble_lines   = ();
 8825:     %responsetype_per_response = ();
 8826:     %masterseq_id_responsenum  = ();
 8827: 
 8828:     my $response_number = 0;
 8829:     my $bubble_line     = 0;
 8830:     foreach my $resource (@resources) {
 8831:         my $resid = $resource->id(); 
 8832:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8833:                                                           $udom,undef,$bubbles_per_row);
 8834:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8835: 	    foreach my $part_id (@{$parts}) {
 8836:                 my $lines;
 8837: 
 8838: 	        # TODO - make this a persistent hash not an array.
 8839: 
 8840:                 # optionresponse, matchresponse and rankresponse type items 
 8841:                 # render as separate sub-questions in exam mode.
 8842:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8843:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8844:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8845:                     my ($numbub,$numshown);
 8846:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8847:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8848:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8849:                         }
 8850:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8851:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8852:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8853:                         }
 8854:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8855:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8856:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8857:                         }
 8858:                     }
 8859:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8860:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8861:                     }
 8862:                     my $bubbles_per_row =
 8863:                         &bubblesheet_bubbles_per_row($scantron_config);
 8864:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8865:                     if (($numbub % $bubbles_per_row) != 0) {
 8866:                         $inner_bubble_lines++;
 8867:                     }
 8868:                     for (my $i=0; $i<$numshown; $i++) {
 8869:                         $subdivided_bubble_lines{$response_number} .= 
 8870:                             $inner_bubble_lines.',';
 8871:                     }
 8872:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8873:                     $lines = $numshown * $inner_bubble_lines;
 8874:                 } else {
 8875:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8876:                 }
 8877: 
 8878:                 $first_bubble_line{$response_number} = $bubble_line;
 8879: 	        $bubble_lines_per_response{$response_number} = $lines;
 8880:                 $responsetype_per_response{$response_number} = 
 8881:                     $analysis->{$part_id.'.type'};
 8882:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8883: 	        $response_number++;
 8884: 
 8885: 	        $bubble_line +=  $lines;
 8886: 	        $total_lines +=  $lines;
 8887: 	    }
 8888:         }
 8889:     }
 8890:     &Apache::lonnet::delenv('scantron.');
 8891: 
 8892:     &save_bubble_lines();
 8893:     $env{'form.scantron_maxbubble'} =
 8894: 	$total_lines;
 8895:     return $env{'form.scantron_maxbubble'};
 8896: }
 8897: 
 8898: sub bubblesheet_bubbles_per_row {
 8899:     my ($scantron_config) = @_;
 8900:     my $bubbles_per_row;
 8901:     if (ref($scantron_config) eq 'HASH') {
 8902:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8903:     }
 8904:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8905:         $bubbles_per_row = 10;
 8906:     }
 8907:     return $bubbles_per_row;
 8908: }
 8909: 
 8910: sub scantron_validate_missingbubbles {
 8911:     my ($r,$currentphase) = @_;
 8912:     #get student info
 8913:     my $classlist=&Apache::loncoursedata::get_classlist();
 8914:     my %idmap=&username_to_idmap($classlist);
 8915:     my (undef,undef,$sequence)=
 8916:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8917: 
 8918:     #get scantron line setup
 8919:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8920:     my ($scanlines,$scan_data)=&scantron_getfile();
 8921: 
 8922:     my $navmap = Apache::lonnavmaps::navmap->new();
 8923:     unless (ref($navmap)) {
 8924:         $r->print(&navmap_errormsg());
 8925:         return(1,$currentphase);
 8926:     }
 8927: 
 8928:     my $map=$navmap->getResourceByUrl($sequence);
 8929:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8930:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8931:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8932:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8933: 
 8934:     my $nav_error;
 8935:     if (ref($map)) {
 8936:         $randomorder = $map->randomorder();
 8937:         $randompick = $map->randompick();
 8938:         if ($randomorder || $randompick) {
 8939:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8940:             if ($nav_error) {
 8941:                 $r->print(&navmap_errormsg());
 8942:                 return(1,$currentphase);
 8943:             }
 8944:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8945:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8946:         }
 8947:     } else {
 8948:         $r->print(&navmap_errormsg());
 8949:         return(1,$currentphase);
 8950:     }
 8951: 
 8952: 
 8953:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8954:     if ($nav_error) {
 8955:         $r->print(&navmap_errormsg());
 8956:         return(1,$currentphase);
 8957:     }
 8958: 
 8959:     if (!$max_bubble) { $max_bubble=2**31; }
 8960:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8961: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8962: 	if ($line=~/^[\s\cz]*$/) { next; }
 8963: 	my $scan_record =
 8964:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8965: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8966:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8967:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8968: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8969: 	my @to_correct;
 8970: 	
 8971: 	# Probably here's where the error is...
 8972: 
 8973: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8974:             my $lastbubble;
 8975:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8976:                my $question = $1;
 8977:                my $subquestion = $2;
 8978:                my ($first,$responsenum);
 8979:                if ($randomorder || $randompick) {
 8980:                    $responsenum = $respnumlookup{$question-1};
 8981:                    $first = $startline{$question-1};
 8982:                } else {
 8983:                    $responsenum = $question-1; 
 8984:                    $first = $first_bubble_line{$responsenum};
 8985:                }
 8986:                if (!defined($first)) { next; }
 8987:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8988:                my $subcount = 1;
 8989:                while ($subcount<$subquestion) {
 8990:                    $first += $subans[$subcount-1];
 8991:                    $subcount ++;
 8992:                }
 8993:                my $count = $subans[$subquestion-1];
 8994:                $lastbubble = $first + $count;
 8995:             } else {
 8996:                my ($first,$responsenum);
 8997:                if ($randomorder || $randompick) {
 8998:                    $responsenum = $respnumlookup{$missing-1};
 8999:                    $first = $startline{$missing-1};
 9000:                } else {
 9001:                    $responsenum = $missing-1;
 9002:                    $first = $first_bubble_line{$responsenum};
 9003:                }
 9004:                if (!defined($first)) { next; }
 9005:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 9006:             }
 9007:             if ($lastbubble > $max_bubble) { next; }
 9008: 	    push(@to_correct,$missing);
 9009: 	}
 9010: 	if (@to_correct) {
 9011: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 9012: 				     $line,'missingbubble',\@to_correct,
 9013:                                      $randomorder,$randompick,\%respnumlookup,
 9014:                                      \%startline);
 9015: 	    return (1,$currentphase);
 9016: 	}
 9017: 
 9018:     }
 9019:     return (0,$currentphase+1);
 9020: }
 9021: 
 9022: sub hand_bubble_option {
 9023:     my (undef, undef, $sequence) =
 9024:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9025:     return if ($sequence eq '');
 9026:     my $navmap = Apache::lonnavmaps::navmap->new();
 9027:     unless (ref($navmap)) {
 9028:         return;
 9029:     }
 9030:     my $needs_hand_bubbles;
 9031:     my $map=$navmap->getResourceByUrl($sequence);
 9032:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9033:     foreach my $res (@resources) {
 9034:         if (ref($res)) {
 9035:             if ($res->is_problem()) {
 9036:                 my $partlist = $res->parts();
 9037:                 foreach my $part (@{ $partlist }) {
 9038:                     my @types = $res->responseType($part);
 9039:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 9040:                         $needs_hand_bubbles = 1;
 9041:                         last;
 9042:                     }
 9043:                 }
 9044:             }
 9045:         }
 9046:     }
 9047:     if ($needs_hand_bubbles) {
 9048:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9049:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9050:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 9051:                &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 />').
 9052:                '<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;'.
 9053:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 9054:     }
 9055:     return;
 9056: }
 9057: 
 9058: sub scantron_process_students {
 9059:     my ($r,$symb) = @_;
 9060: 
 9061:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 9062:     if (!$symb) {
 9063: 	return '';
 9064:     }
 9065:     my $default_form_data=&defaultFormData($symb);
 9066: 
 9067:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9068:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 9069:     my ($scanlines,$scan_data)=&scantron_getfile();
 9070:     my $classlist=&Apache::loncoursedata::get_classlist();
 9071:     my %idmap=&username_to_idmap($classlist);
 9072:     my $navmap=Apache::lonnavmaps::navmap->new();
 9073:     unless (ref($navmap)) {
 9074:         $r->print(&navmap_errormsg());
 9075:         return '';
 9076:     }
 9077:     my $map=$navmap->getResourceByUrl($sequence);
 9078:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9079:         %grader_randomlists_by_symb);
 9080:     if (ref($map)) {
 9081:         $randomorder = $map->randomorder();
 9082:         $randompick = $map->randompick();
 9083:     } else {
 9084:         $r->print(&navmap_errormsg());
 9085:         return '';
 9086:     }
 9087:     my $nav_error;
 9088:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9089:     if ($randomorder || $randompick) {
 9090:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9091:         if ($nav_error) {
 9092:             $r->print(&navmap_errormsg());
 9093:             return '';
 9094:         }
 9095:     }
 9096:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9097:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9098: 
 9099:     my ($uname,$udom);
 9100:     my $result= <<SCANTRONFORM;
 9101: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9102:   <input type="hidden" name="command" value="scantron_configphase" />
 9103:   $default_form_data
 9104: SCANTRONFORM
 9105:     $r->print($result);
 9106: 
 9107:     my ($checksec,@possibles)=&gradable_sections();
 9108:     my @delayqueue;
 9109:     my (%completedstudents,%scandata);
 9110: 
 9111:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9112:     my $count=&get_todo_count($scanlines,$scan_data);
 9113:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9114:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9115:     $r->print('<br />');
 9116:     my $start=&Time::HiRes::time();
 9117:     my $i=-1;
 9118:     my $started;
 9119: 
 9120:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9121:     if ($nav_error) {
 9122:         $r->print(&navmap_errormsg());
 9123:         return '';
 9124:     }
 9125: 
 9126:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9127:     # the user and return.
 9128: 
 9129:     if ($ssi_error) {
 9130: 	$r->print("</form>");
 9131: 	&ssi_print_error($r);
 9132:         &Apache::lonnet::remove_lock($lock);
 9133: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9134:     }
 9135: 
 9136:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9137:     my $numletts = scalar(keys(%lettdig));
 9138:     my %orderedforcode;
 9139: 
 9140:     while ($i<$scanlines->{'count'}) {
 9141:  	($uname,$udom)=('','');
 9142:  	$i++;
 9143:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9144:  	if ($line=~/^[\s\cz]*$/) { next; }
 9145: 	if ($started) {
 9146: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9147: 	}
 9148: 	$started=1;
 9149:         my %respnumlookup = ();
 9150:         my %startline = ();
 9151:         my $total;
 9152:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9153:                                                  $scan_data,undef,\%idmap,$randomorder,
 9154:                                                  $randompick,$sequence,\@master_seq,
 9155:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9156:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9157:                                                  \$total);
 9158:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9159:  					      \%idmap,$i)) {
 9160:   	    &scantron_add_delay(\@delayqueue,$line,
 9161:  				'Unable to find a student that matches',1);
 9162:  	    next;
 9163:   	}
 9164:  	if (exists $completedstudents{$uname}) {
 9165:  	    &scantron_add_delay(\@delayqueue,$line,
 9166:  				'Student '.$uname.' has multiple sheets',2);
 9167:  	    next;
 9168:  	}
 9169:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9170:         if (($checksec ne '') && ($checksec ne $usec)) {
 9171:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9172:                 &scantron_add_delay(\@delayqueue,$line,
 9173:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9174:                 next;
 9175:             }
 9176:         }
 9177:         my $user = $uname.':'.$usec;
 9178:   	($uname,$udom)=split(/:/,$uname);
 9179: 
 9180:         my $scancode;
 9181:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9182:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9183:             $scancode = $scan_record->{'scantron.CODE'};
 9184:         } else {
 9185:             $scancode = '';
 9186:         }
 9187: 
 9188:         my @mapresources = @resources;
 9189:         if ($randomorder || $randompick) {
 9190:             @mapresources = 
 9191:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9192:                              \%orderedforcode);
 9193:         }
 9194:         my (%partids_by_symb,$res_error);
 9195:         foreach my $resource (@mapresources) {
 9196:             my $ressymb;
 9197:             if (ref($resource)) {
 9198:                 $ressymb = $resource->symb();
 9199:             } else {
 9200:                 $res_error = 1;
 9201:                 last;
 9202:             }
 9203:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9204:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9205:                 my $currcode;
 9206:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9207:                     $currcode = $scancode;
 9208:                 }
 9209:                 my ($analysis,$parts) =
 9210:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9211:                                               $uname,$udom,undef,$bubbles_per_row,
 9212:                                               $currcode);
 9213:                 $partids_by_symb{$ressymb} = $parts;
 9214:             } else {
 9215:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9216:             }
 9217:         }
 9218: 
 9219:         if ($res_error) {
 9220:             &scantron_add_delay(\@delayqueue,$line,
 9221:                                 'An error occurred while grading student '.$uname,2);
 9222:             next;
 9223:         }
 9224: 
 9225: 	&Apache::lonxml::clear_problem_counter();
 9226:   	&Apache::lonnet::appenv($scan_record);
 9227: 
 9228: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9229: 	    &scantron_putfile($scanlines,$scan_data);
 9230: 	}
 9231: 	
 9232:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9233:                                    \@mapresources,\%partids_by_symb,
 9234:                                    $bubbles_per_row,$randomorder,$randompick,
 9235:                                    \%respnumlookup,\%startline) 
 9236:             eq 'ssi_error') {
 9237:             $ssi_error = 0; # So end of handler error message does not trigger.
 9238:             $r->print("</form>");
 9239:             &ssi_print_error($r);
 9240:             &Apache::lonnet::remove_lock($lock);
 9241:             return '';      # Why return ''?  Beats me.
 9242:         }
 9243: 
 9244:         if (($scancode) && ($randomorder || $randompick)) {
 9245:             my $parmresult =
 9246:                 &Apache::lonparmset::storeparm_by_symb($symb,
 9247:                                                        '0_examcode',2,$scancode,
 9248:                                                        'string_examcode',$uname,
 9249:                                                        $udom);
 9250:         }
 9251: 	$completedstudents{$uname}={'line'=>$line};
 9252:         if ($env{'form.verifyrecord'}) {
 9253:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9254:             if ($randompick) {
 9255:                 if ($total) {
 9256:                     $lastpos = $total*$scantron_config{'Qlength'};
 9257:                 }
 9258:             }
 9259: 
 9260:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9261:             chomp($studentdata);
 9262:             $studentdata =~ s/\r$//;
 9263:             my $studentrecord = '';
 9264:             my $counter = -1;
 9265:             foreach my $resource (@mapresources) {
 9266:                 my $ressymb = $resource->symb();
 9267:                 ($counter,my $recording) =
 9268:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9269:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9270:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9271:                                              $randompick,\%respnumlookup,\%startline);
 9272:                 $studentrecord .= $recording;
 9273:             }
 9274:             if ($studentrecord ne $studentdata) {
 9275:                 &Apache::lonxml::clear_problem_counter();
 9276:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9277:                                            \@mapresources,\%partids_by_symb,
 9278:                                            $bubbles_per_row,$randomorder,$randompick,
 9279:                                            \%respnumlookup,\%startline) 
 9280:                     eq 'ssi_error') {
 9281:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9282:                     $r->print("</form>");
 9283:                     &ssi_print_error($r);
 9284:                     &Apache::lonnet::remove_lock($lock);
 9285:                     delete($completedstudents{$uname});
 9286:                     return '';
 9287:                 }
 9288:                 $counter = -1;
 9289:                 $studentrecord = '';
 9290:                 foreach my $resource (@mapresources) {
 9291:                     my $ressymb = $resource->symb();
 9292:                     ($counter,my $recording) =
 9293:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9294:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9295:                                                  \%scantron_config,\%lettdig,$numletts,
 9296:                                                  $randomorder,$randompick,\%respnumlookup,
 9297:                                                  \%startline);
 9298:                     $studentrecord .= $recording;
 9299:                 }
 9300:                 if ($studentrecord ne $studentdata) {
 9301:                     $r->print('<p><span class="LC_warning">');
 9302:                     if ($scancode eq '') {
 9303:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9304:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9305:                     } else {
 9306:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9307:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9308:                     }
 9309:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9310:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9311:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9312:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9313:                               &Apache::loncommon::start_data_table_row().
 9314:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9315:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9316:                               &Apache::loncommon::end_data_table_row().
 9317:                               &Apache::loncommon::start_data_table_row().
 9318:                               '<td>'.&mt('Stored submissions').'</td>'.
 9319:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9320:                               &Apache::loncommon::end_data_table_row().
 9321:                               &Apache::loncommon::end_data_table().'</p>');
 9322:                 } else {
 9323:                     $r->print('<br /><span class="LC_warning">'.
 9324:                              &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 />'.
 9325:                              &mt("As a consequence, this user's submission history records two tries.").
 9326:                                  '</span><br />');
 9327:                 }
 9328:             }
 9329:         }
 9330:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9331:     } continue {
 9332: 	&Apache::lonxml::clear_problem_counter();
 9333: 	&Apache::lonnet::delenv('scantron.');
 9334:     }
 9335:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9336:     &Apache::lonnet::remove_lock($lock);
 9337: #    my $lasttime = &Time::HiRes::time()-$start;
 9338: #    $r->print("<p>took $lasttime</p>");
 9339: 
 9340:     $r->print("</form>");
 9341:     return '';
 9342: }
 9343: 
 9344: sub graders_resources_pass {
 9345:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9346:         $bubbles_per_row) = @_;
 9347:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9348:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9349:         foreach my $resource (@{$resources}) {
 9350:             my $ressymb = $resource->symb();
 9351:             my ($analysis,$parts) =
 9352:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9353:                                           $env{'user.name'},$env{'user.domain'},
 9354:                                           1,$bubbles_per_row);
 9355:             $grader_partids_by_symb->{$ressymb} = $parts;
 9356:             if (ref($analysis) eq 'HASH') {
 9357:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9358:                     $grader_randomlists_by_symb->{$ressymb} =
 9359:                         $analysis->{'parts_withrandomlist'};
 9360:                 }
 9361:             }
 9362:         }
 9363:     }
 9364:     return;
 9365: }
 9366: 
 9367: =pod
 9368: 
 9369: =item users_order
 9370: 
 9371:   Returns array of resources in current map, ordered based on either CODE,
 9372:   if this is a CODEd exam, or based on student's identity if this is a 
 9373:   "NAMEd" exam.
 9374: 
 9375:   Should be used when randomorder and/or randompick applied when the 
 9376:   corresponding exam was printed, prior to students completing bubblesheets 
 9377:   for the version of the exam the student received.
 9378: 
 9379: =cut
 9380: 
 9381: sub users_order  {
 9382:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9383:     my @mapresources;
 9384:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9385:         return @mapresources;
 9386:     }
 9387:     if ($scancode) {
 9388:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9389:             @mapresources = @{$orderedforcode->{$scancode}};
 9390:         } else {
 9391:             $env{'form.CODE'} = $scancode;
 9392:             my $actual_seq =
 9393:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9394:                                                                $master_seq,
 9395:                                                                $user,$scancode,1);
 9396:             if (ref($actual_seq) eq 'ARRAY') {
 9397:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9398:                 if (ref($orderedforcode) eq 'HASH') {
 9399:                     if (@mapresources > 0) { 
 9400:                         $orderedforcode->{$scancode} = \@mapresources;
 9401:                     }
 9402:                 }
 9403:             }
 9404:             delete($env{'form.CODE'});
 9405:         }
 9406:     } else {
 9407:         my $actual_seq =
 9408:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9409:                                                            $master_seq,
 9410:                                                            $user,undef,1);
 9411:         if (ref($actual_seq) eq 'ARRAY') {
 9412:             @mapresources = 
 9413:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9414:         }
 9415:     }
 9416:     return @mapresources;
 9417: }
 9418: 
 9419: sub grade_student_bubbles {
 9420:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9421:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9422:     my $uselookup = 0;
 9423:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9424:         (ref($startline) eq 'HASH')) {
 9425:         $uselookup = 1;
 9426:     }
 9427: 
 9428:     if (ref($resources) eq 'ARRAY') {
 9429:         my $count = 0;
 9430:         foreach my $resource (@{$resources}) {
 9431:             my $ressymb = $resource->symb();
 9432:             my %form = ('submitted'      => 'scantron',
 9433:                         'grade_target'   => 'grade',
 9434:                         'grade_username' => $uname,
 9435:                         'grade_domain'   => $udom,
 9436:                         'grade_courseid' => $env{'request.course.id'},
 9437:                         'grade_symb'     => $ressymb,
 9438:                         'CODE'           => $scancode
 9439:                        );
 9440:             if ($bubbles_per_row ne '') {
 9441:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9442:             }
 9443:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9444:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9445:             }
 9446:             if (ref($parts) eq 'HASH') {
 9447:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9448:                     foreach my $part (@{$parts->{$ressymb}}) {
 9449:                         if ($uselookup) {
 9450:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9451:                         } else {
 9452:                             $form{'scantron_questnum_start.'.$part} =
 9453:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9454:                         }
 9455:                         $count++;
 9456:                     }
 9457:                 }
 9458:             }
 9459:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9460:             return 'ssi_error' if ($ssi_error);
 9461:             last if (&Apache::loncommon::connection_aborted($r));
 9462:         }
 9463:     }
 9464:     return;
 9465: }
 9466: 
 9467: sub scantron_upload_scantron_data {
 9468:     my ($r,$symb) = @_;
 9469:     my $dom = $env{'request.role.domain'};
 9470:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9471:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9472:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9473:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9474: 							  'domainid',
 9475: 							  'coursename',$dom);
 9476:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9477:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9478:     my $default_form_data=&defaultFormData($symb);
 9479:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9480:     &js_escape(\$nofile_alert);
 9481:     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.");
 9482:     &js_escape(\$nocourseid_alert);
 9483:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9484:     function checkUpload(formname) {
 9485: 	if (formname.upfile.value == "") {
 9486: 	    alert("'.$nofile_alert.'");
 9487: 	    return false;
 9488: 	}
 9489:         if (formname.courseid.value == "") {
 9490:             alert("'.$nocourseid_alert.'");
 9491:             return false;
 9492:         }
 9493: 	formname.submit();
 9494:     }
 9495: 
 9496:     function ToSyllabus() {
 9497:         var cdom = '."'$dom'".';
 9498:         var cnum = document.rules.courseid.value;
 9499:         if (cdom == "" || cdom == null) {
 9500:             return;
 9501:         }
 9502:         if (cnum == "" || cnum == null) {
 9503:            return;
 9504:         }
 9505:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9506:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9507:         return;
 9508:     }
 9509: 
 9510:     '.$formatjs.'
 9511: '));
 9512:     $r->print('
 9513: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9514: 
 9515: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9516: '.$default_form_data.
 9517:   &Apache::lonhtmlcommon::start_pick_box().
 9518:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9519:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9520:   &Apache::lonhtmlcommon::row_closure().
 9521:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9522:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9523:   &Apache::lonhtmlcommon::row_closure().
 9524:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9525:   '<input name="domainid" type="hidden" />'.$domdesc.
 9526:   &Apache::lonhtmlcommon::row_closure());
 9527:     if ($formatoptions) {
 9528:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9529:                   &Apache::lonhtmlcommon::row_closure());
 9530:     }
 9531:     $r->print(
 9532:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9533:   '<input type="file" name="upfile" size="50" />'.
 9534:   &Apache::lonhtmlcommon::row_closure(1).
 9535:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9536: 
 9537: <input name="command" value="scantronupload_save" type="hidden" />
 9538: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9539: </form>
 9540: ');
 9541:     return '';
 9542: }
 9543: 
 9544: sub scantron_upload_dataformat {
 9545:     my ($dom) = @_;
 9546:     my ($formatoptions,$formattitle,$formatjs);
 9547:     $formatjs = <<'END';
 9548: function toggleScantab(form) {
 9549:    return;
 9550: }
 9551: END
 9552:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9553:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9554:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9555:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9556:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9557:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9558:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9559:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9560:                             my ($onclick,$formatextra,$singleline);
 9561:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9562:                             my $count = 0;
 9563:                             foreach my $line (@lines) {
 9564:                                 next if ($line =~ /^#/);
 9565:                                 $singleline = $line;
 9566:                                 $count ++;
 9567:                             }
 9568:                             if ($count > 1) {
 9569:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9570:                                                '<span class="LC_nobreak">'.
 9571:                                                &mt('Bubblesheet type').':&nbsp;'.
 9572:                                                &scantron_scantab().'</span></div>';
 9573:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9574:                                 $formatjs = <<"END";
 9575: function toggleScantab(form) {
 9576:     var divid = 'bubbletype';
 9577:     if (document.getElementById(divid)) {
 9578:         var radioname = 'fileformat';
 9579:         var num = form.elements[radioname].length;
 9580:         if (num) {
 9581:             for (var i=0; i<num; i++) {
 9582:                 if (form.elements[radioname][i].checked) {
 9583:                     var chosen = form.elements[radioname][i].value;
 9584:                     if (chosen == 'dat') {
 9585:                         document.getElementById(divid).style.display = 'none';
 9586:                     } else if (chosen == 'csv') {
 9587:                         document.getElementById(divid).style.display = 'block';
 9588:                     }
 9589:                 }
 9590:             }
 9591:         }
 9592:     }
 9593:     return;
 9594: }
 9595: 
 9596: END
 9597:                             } elsif ($count == 1) {
 9598:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9599:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9600:                             }
 9601:                             $formattitle = &mt('File format');
 9602:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9603:                                              &mt('Plain Text (no delimiters)').
 9604:                                              '</label>'.('&nbsp;'x2).
 9605:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9606:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9607:                         }
 9608:                     }
 9609:                 }
 9610:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9611:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9612:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9613:                         $formattitle = &mt('Bubblesheet type');
 9614:                         $formatoptions = &scantron_scantab();
 9615:                     }
 9616:                 }
 9617:             }
 9618:         }
 9619:     }
 9620:     return ($formatoptions,$formattitle,$formatjs);
 9621: }
 9622: 
 9623: sub scantron_upload_scantron_data_save {
 9624:     my ($r,$symb) = @_;
 9625:     my $doanotherupload=
 9626: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9627: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9628: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9629: 	'</form>'."\n";
 9630:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9631: 	!&Apache::lonnet::allowed('usc',
 9632: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9633:         !&Apache::lonnet::allowed('usc',
 9634:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9635: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9636: 	unless ($symb) {
 9637: 	    $r->print($doanotherupload);
 9638: 	}
 9639: 	return '';
 9640:     }
 9641:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9642:     my $uploadedfile;
 9643:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9644:     if (length($env{'form.upfile'}) < 2) {
 9645:         $r->print(
 9646:             &Apache::lonhtmlcommon::confirm_success(
 9647:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9648:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9649:     } else {
 9650:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9651:         my $parser;
 9652:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9653:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9654:                 my $is_csv;
 9655:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9656:                 if (@possibles > 1) {
 9657:                     if ($env{'form.fileformat'} eq 'csv') {
 9658:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9659:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9660:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9661:                                     $is_csv = 1;
 9662:                                 }
 9663:                             }
 9664:                         }
 9665:                     }
 9666:                 } elsif (@possibles == 1) {
 9667:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9668:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9669:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9670:                                 $is_csv = 1;
 9671:                             }
 9672:                         }
 9673:                     }
 9674:                 }
 9675:                 if ($is_csv) {
 9676:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9677:                 }
 9678:             }
 9679:         }
 9680:         my $result =
 9681:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9682:                                             $env{'form.courseid'},$env{'form.domainid'});
 9683:         if ($result =~ m{^/uploaded/}) {
 9684:             $r->print(
 9685:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9686:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9687:                         (length($env{'form.upfile'})-1),
 9688:                         '<span class="LC_filename">'.$result.'</span>'));
 9689:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9690:             if ($uploadedfile =~ /^scantron_orig_/) {
 9691:                 my $logname = $uploadedfile;
 9692:                 $logname =~ s/^scantron_orig_//;
 9693:                 if ($logname ne '') {
 9694:                     my $now = time;
 9695:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9696:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9697:                 }
 9698:             }
 9699:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9700:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9701:         } else {
 9702:             $r->print(
 9703:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9704:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9705:                           $result,
 9706: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9707: 	}
 9708:     }
 9709:     if ($symb) {
 9710: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9711:     } else {
 9712: 	$r->print($doanotherupload);
 9713:     }
 9714:     return '';
 9715: }
 9716: 
 9717: sub validate_uploaded_scantron_file {
 9718:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9719: 
 9720:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9721:     my @lines;
 9722:     if ($scanlines ne '-1') {
 9723:         @lines=split("\n",$scanlines,-1);
 9724:     }
 9725:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9726:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9727:     if ($context eq 'download') {
 9728:         $priv = 'mgr';
 9729:     } else {
 9730:         $priv = 'usc';
 9731:     }
 9732:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9733:             (($env{'request.course.id'}) &&
 9734:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9735:         if ($env{'request.course.sec'} ne '') {
 9736:             unless (&Apache::lonnet::allowed($priv,
 9737:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9738:                 unless ($context eq 'download') {
 9739:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9740:                 }
 9741:                 return $output;
 9742:             }
 9743:             ($checksec,@possibles)=&gradable_sections();
 9744:         }
 9745:     }
 9746:     if (@lines) {
 9747:         my (%counts,$max_match_format);
 9748:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9749:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9750:         my %idmap = &username_to_idmap($classlist);
 9751:         foreach my $key (keys(%idmap)) {
 9752:             my $lckey = lc($key);
 9753:             $idmap{$lckey} = $idmap{$key};
 9754:         }
 9755:         my %unique_formats;
 9756:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9757:         foreach my $line (@formatlines) {
 9758:             chomp($line);
 9759:             my @config = split(/:/,$line);
 9760:             my $idstart = $config[5];
 9761:             my $idlength = $config[6];
 9762:             if (($idstart ne '') && ($idlength > 0)) {
 9763:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9764:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9765:                 } else {
 9766:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9767:                 }
 9768:             }
 9769:         }
 9770:         foreach my $key (keys(%unique_formats)) {
 9771:             my ($idstart,$idlength) = split(':',$key);
 9772:             %{$counts{$key}} = (
 9773:                                'found'   => 0,
 9774:                                'total'   => 0,
 9775:                                'totalanysec' => 0,
 9776:                                'othersec' => 0,
 9777:                               );
 9778:             foreach my $line (@lines) {
 9779:                 next if ($line =~ /^#/);
 9780:                 next if ($line =~ /^[\s\cz]*$/);
 9781:                 my $id = substr($line,$idstart-1,$idlength);
 9782:                 $id = lc($id);
 9783:                 if (exists($idmap{$id})) {
 9784:                     if ($checksec ne '') {
 9785:                         $counts{$key}{'totalanysec'} ++;
 9786:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9787:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9788:                             if ($stusec ne $checksec) {
 9789:                                 if (@possibles) {
 9790:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9791:                                         $counts{$key}{'othersec'} ++;
 9792:                                         next;
 9793:                                     }
 9794:                                 } else {
 9795:                                     $counts{$key}{'othersec'} ++;
 9796:                                     next;
 9797:                                 }
 9798:                             }
 9799:                         }
 9800:                     }
 9801:                     $counts{$key}{'found'} ++;
 9802:                 }
 9803:                 $counts{$key}{'total'} ++;
 9804:             }
 9805:             if ($counts{$key}{'total'}) {
 9806:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9807:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9808:                     $max_match_pct = $percent_match;
 9809:                     $max_match_format = $key;
 9810:                     $found_match_count = $counts{$key}{'found'};
 9811:                     $max_match_count = $counts{$key}{'total'};
 9812:                 }
 9813:             }
 9814:         }
 9815:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9816:             my $format_descs;
 9817:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9818:             for (my $i=0; $i<$numwithformat; $i++) {
 9819:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9820:                 if ($i<$numwithformat-2) {
 9821:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9822:                 } elsif ($i==$numwithformat-2) {
 9823:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9824:                 } elsif ($i==$numwithformat-1) {
 9825:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9826:                 }
 9827:             }
 9828:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9829:             $output .= '<br />';
 9830:             if ($found_match_count == $max_match_count) {
 9831:                 # 100% matching entries
 9832:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9833:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9834:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9835:                 &mt('Comparison of student IDs in the uploaded file with'.
 9836:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9837:                     ' in the file (for the format defined for [_3]).',
 9838:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9839:             } else {
 9840:                 # Not all entries matching? -> Show warning and additional info
 9841:                 $output .=
 9842:                     &Apache::lonhtmlcommon::confirm_success(
 9843:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9844:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9845:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9846:                     &mt('Comparison of student IDs in the uploaded file with'.
 9847:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9848:                         ' in the file (for the format defined for [_3]).',
 9849:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9850:                     '<p class="LC_info">'.
 9851:                     &mt('A low percentage of matches results from one of the following:').
 9852:                     '</p><ul>'.
 9853:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9854:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9855:                                '<i>'.$cdom.'</i>').'</li>'.
 9856:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9857:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9858:                     '</ul>';
 9859:             }
 9860:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9861:                 if ($counts{$max_match_format}{'othersec'}) {
 9862:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9863:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9864:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9865:                     &js_escape(\$confirmdel);
 9866:                     $output .= '<p class="LC_warning">'.
 9867:                                &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',
 9868:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9869:                                '<br />'.
 9870:                                &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>').
 9871:                                '</p><p>'.
 9872:                                &mt('If you prefer to delete the file now, use: [_1]').
 9873:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9874:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9875:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9876:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9877:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9878:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9879:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9880:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9881:                                '</form></p>';
 9882:                 }
 9883:             }
 9884:         }
 9885:         if (($context eq 'download') && ($checksec ne '')) {
 9886:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9887:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9888:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9889:             }
 9890:         } 
 9891:     } elsif ($context ne 'download') {
 9892:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9893:     }
 9894:     return $output;
 9895: }
 9896: 
 9897: sub gradable_sections {
 9898:     my $checksec = $env{'request.course.sec'};
 9899:     my @oksecs;
 9900:     if ($checksec) {
 9901:         my %availablesecs = &sections_grade_privs();
 9902:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9903:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9904:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9905:                     push(@oksecs,$sec);
 9906:                 }
 9907:             }
 9908:             if (grep(/^all$/,@oksecs)) {
 9909:                 undef($checksec);
 9910:             }
 9911:         }
 9912:     }
 9913:     return($checksec,@oksecs);
 9914: }
 9915: 
 9916: sub sections_grade_privs {
 9917:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9918:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9919:     my %availablesecs = (
 9920:                           mgr => [],
 9921:                           vgr => [],
 9922:                           usc => [],
 9923:                         );
 9924:     my $ccrole = 'cc';
 9925:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9926:         $ccrole = 'co';
 9927:     }
 9928:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9929:                                                      'userroles',['active'],
 9930:                                                      [$ccrole,'in','cr'],$cdom,1);
 9931:     my $crsid = $cnum.':'.$cdom;
 9932:     foreach my $item (keys(%crsroleshash)) {
 9933:         next unless ($item =~ /^$crsid\:/);
 9934:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9935:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9936:         if ($sec ne '') {
 9937:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9938:         }
 9939:         if (($role eq $ccrole) || ($role eq 'in')) {
 9940:             foreach my $priv ('mgr','vgr','usc') { 
 9941:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9942:                     if ($sec eq '') {
 9943:                         $availablesecs{$priv} = ['all'];
 9944:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9945:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9946:                             push(@{$availablesecs{$priv}},$sec);
 9947:                         }
 9948:                     }
 9949:                 }
 9950:             }
 9951:         } elsif ($role =~ m{^cr/}) {
 9952:             foreach my $priv ('mgr','vgr','usc') {
 9953:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9954:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9955:                         if ($sec eq '') {
 9956:                             $availablesecs{$priv} = ['all'];
 9957:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9958:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9959:                                 push(@{$availablesecs{$priv}},$sec);
 9960:                             }
 9961:                         }
 9962:                     }
 9963:                 }
 9964:             }
 9965:         }
 9966:     }
 9967:     return %availablesecs;
 9968: }
 9969: 
 9970: sub scantron_upload_delete {
 9971:     my ($r,$symb) = @_;
 9972:     my $filename = $env{'form.uploadedfile'};
 9973:     if ($filename =~ /^scantron_orig_/) {
 9974:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9975:             &Apache::lonnet::allowed('usc',
 9976:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9977:             &Apache::lonnet::allowed('usc',
 9978:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9979:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9980:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9981:             if ($retrieval eq '-1') {
 9982:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9983:                           &mt('File requested for deletion not found.'));
 9984:             } else {
 9985:                 $filename =~ s/^scantron_orig_//;
 9986:                 if ($filename ne '') {
 9987:                     my ($is_valid,$numleft);
 9988:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9989:                     if (keys(%info)) {
 9990:                         if (ref($info{$filename}) eq 'HASH') {
 9991:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9992:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9993:                                     $is_valid = 1;
 9994:                                     delete($info{$filename}{$timestamp}); 
 9995:                                 }
 9996:                             }
 9997:                             $numleft = scalar(keys(%{$info{$filename}}));
 9998:                         }
 9999:                     }
10000:                     if ($is_valid) {
10001:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
10002:                         if ($result eq 'ok') {
10003:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
10004:                             if ($numleft) {
10005:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
10006:                             } else {
10007:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
10008:                             }
10009:                         } else {
10010:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10011:                                       &mt('Result was [_1]',$result));
10012:                         }
10013:                     } else {
10014:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10015:                                   &mt('File requested for deletion was uploaded by a different user.'));
10016:                     }
10017:                 } else {
10018:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10019:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10020:                 }
10021:             }
10022:         } else {
10023:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
10024:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
10025:         }
10026:     } else {
10027:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10028:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10029:     }
10030:     return;
10031: }
10032: 
10033: sub valid_file {
10034:     my ($requested_file)=@_;
10035:     foreach my $filename (sort(&scantron_filenames())) {
10036: 	if ($requested_file eq $filename) { return 1; }
10037:     }
10038:     return 0;
10039: }
10040: 
10041: sub scantron_download_scantron_data {
10042:     my ($r,$symb) = @_;
10043:     my $default_form_data=&defaultFormData($symb);
10044:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10045:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10046:     my $file=$env{'form.scantron_selectfile'};
10047:     if (! &valid_file($file)) {
10048: 	$r->print('
10049: 	<p>
10050: 	    '.&mt('The requested filename was invalid.').'
10051:         </p>
10052: ');
10053: 	return;
10054:     }
10055:     my (%uploader,$is_owner,%counts,$percent);
10056:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
10057:     if (ref($uploader{$file}) eq 'HASH') {
10058:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
10059:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10060:                 $is_owner = 1;
10061:                 last;
10062:             }
10063:         }
10064:     }
10065:     unless ($is_owner) {
10066:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
10067:         if ($counts{'totalanysec'}) {
10068:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
10069:             if ($percent_othersec >= 10) {
10070:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
10071:                 $r->print('<p class="LC_warning">'.
10072:                           &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).
10073:                           '</p>');
10074:                 return;
10075:             }
10076:         }
10077:     }
10078:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
10079:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
10080:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
10081:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
10082:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
10083:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
10084:     $r->print('
10085:     <p>
10086: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
10087: 	      '<a href="'.$orig.'">','</a>').'
10088:     </p>
10089:     <p>
10090: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
10091: 	      '<a href="'.$corrected.'">','</a>').'
10092:     </p>
10093:     <p>
10094: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
10095: 	      '<a href="'.$skipped.'">','</a>').'
10096:     </p>
10097: ');
10098:     return '';
10099: }
10100: 
10101: sub checkscantron_results {
10102:     my ($r,$symb) = @_;
10103:     if (!$symb) {return '';}
10104:     my $cid = $env{'request.course.id'};
10105:     my %lettdig = &Apache::lonnet::letter_to_digits();
10106:     my $numletts = scalar(keys(%lettdig));
10107:     my $cnum = $env{'course.'.$cid.'.num'};
10108:     my $cdom = $env{'course.'.$cid.'.domain'};
10109:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10110:     my %record;
10111:     my %scantron_config =
10112:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10113:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10114:     my ($scanlines,$scan_data)=&scantron_getfile();
10115:     my $classlist=&Apache::loncoursedata::get_classlist();
10116:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10117:     my $navmap=Apache::lonnavmaps::navmap->new();
10118:     unless (ref($navmap)) {
10119:         $r->print(&navmap_errormsg());
10120:         return '';
10121:     }
10122:     my $map=$navmap->getResourceByUrl($sequence);
10123:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10124:         %grader_randomlists_by_symb,%orderedforcode);
10125:     if (ref($map)) { 
10126:         $randomorder=$map->randomorder();
10127:         $randompick=$map->randompick();
10128:     }
10129:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10130:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10131:     if ($nav_error) {
10132:         $r->print(&navmap_errormsg());
10133:         return '';
10134:     }
10135:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10136:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10137:     my ($uname,$udom);
10138:     my (%scandata,%lastname,%bylast);
10139:     $r->print('
10140: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10141: 
10142:     my @delayqueue;
10143:     my %completedstudents;
10144: 
10145:     my $count=&get_todo_count($scanlines,$scan_data);
10146:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10147:     my ($username,$domain,$started);
10148:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10149:     if ($nav_error) {
10150:         $r->print(&navmap_errormsg());
10151:         return '';
10152:     }
10153: 
10154:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10155:     my $start=&Time::HiRes::time();
10156:     my $i=-1;
10157: 
10158:     while ($i<$scanlines->{'count'}) {
10159:         ($username,$domain,$uname)=('','','');
10160:         $i++;
10161:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10162:         if ($line=~/^[\s\cz]*$/) { next; }
10163:         if ($started) {
10164:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10165:         }
10166:         $started=1;
10167:         my $scan_record=
10168:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10169:                                                      $scan_data);
10170:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10171:                                               \%idmap,$i)) {
10172:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10173:                                 'Unable to find a student that matches',1);
10174:             next;
10175:         }
10176:         if (exists $completedstudents{$uname}) {
10177:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10178:                                 'Student '.$uname.' has multiple sheets',2);
10179:             next;
10180:         }
10181:         my $pid = $scan_record->{'scantron.ID'};
10182:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10183:         push(@{$bylast{$lastname{$pid}}},$pid);
10184:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10185:         my $user = $uname.':'.$usec;
10186:         ($username,$domain)=split(/:/,$uname);
10187: 
10188:         my $scancode;
10189:         if ((exists($scan_record->{'scantron.CODE'})) &&
10190:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10191:             $scancode = $scan_record->{'scantron.CODE'};
10192:         } else {
10193:             $scancode = '';
10194:         }
10195: 
10196:         my @mapresources = @resources;
10197:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10198:         my %respnumlookup=();
10199:         my %startline=();
10200:         if ($randomorder || $randompick) {
10201:             @mapresources =
10202:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10203:                              \%orderedforcode);
10204:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10205:                                              $scan_record,\@master_seq,\%symb_to_resource,
10206:                                              \%grader_partids_by_symb,\%orderedforcode,
10207:                                              \%respnumlookup,\%startline);
10208:             if ($randompick && $total) {
10209:                 $lastpos = $total*$scantron_config{'Qlength'};
10210:             }
10211:         }
10212:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10213:         chomp($scandata{$pid});
10214:         $scandata{$pid} =~ s/\r$//;
10215: 
10216:         my $counter = -1;
10217:         foreach my $resource (@mapresources) {
10218:             my $parts;
10219:             my $ressymb = $resource->symb();
10220:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10221:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10222:                 my $currcode;
10223:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10224:                     $currcode = $scancode;
10225:                 }
10226:                 (my $analysis,$parts) =
10227:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10228:                                               $username,$domain,undef,
10229:                                               $bubbles_per_row,$currcode);
10230:             } else {
10231:                 $parts = $grader_partids_by_symb{$ressymb};
10232:             }
10233:             ($counter,my $recording) =
10234:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10235:                                          $scandata{$pid},$parts,
10236:                                          \%scantron_config,\%lettdig,$numletts,
10237:                                          $randomorder,$randompick,
10238:                                          \%respnumlookup,\%startline);
10239:             $record{$pid} .= $recording;
10240:         }
10241:     }
10242:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10243:     $r->print('<br />');
10244:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10245:     $passed = 0;
10246:     $failed = 0;
10247:     $numstudents = 0;
10248:     foreach my $last (sort(keys(%bylast))) {
10249:         if (ref($bylast{$last}) eq 'ARRAY') {
10250:             foreach my $pid (sort(@{$bylast{$last}})) {
10251:                 my $showscandata = $scandata{$pid};
10252:                 my $showrecord = $record{$pid};
10253:                 $showscandata =~ s/\s/&nbsp;/g;
10254:                 $showrecord =~ s/\s/&nbsp;/g;
10255:                 if ($scandata{$pid} eq $record{$pid}) {
10256:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10257:                     $okstudents .= '<tr class="'.$css_class.'">'.
10258: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10259: '</tr>'."\n".
10260: '<tr class="'.$css_class.'">'."\n".
10261: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10262:                     $passed ++;
10263:                 } else {
10264:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10265:                     $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".
10266: '</tr>'."\n".
10267: '<tr class="'.$css_class.'">'."\n".
10268: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10269: '</tr>'."\n";
10270:                     $failed ++;
10271:                 }
10272:                 $numstudents ++;
10273:             }
10274:         }
10275:     }
10276:     $r->print(
10277:         '<p>'
10278:        .&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).',
10279:             '<b>',
10280:             $numstudents,
10281:             '</b>',
10282:             $env{'form.scantron_maxbubble'})
10283:        .'</p>'
10284:     );
10285:     $r->print('<p>'
10286:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10287:              .'<br />'
10288:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10289:              .'</p>'
10290:     );
10291:     if ($passed) {
10292:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10293:         $r->print(&Apache::loncommon::start_data_table()."\n".
10294:                  &Apache::loncommon::start_data_table_header_row()."\n".
10295:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10296:                  &Apache::loncommon::end_data_table_header_row()."\n".
10297:                  $okstudents."\n".
10298:                  &Apache::loncommon::end_data_table().'<br />');
10299:     }
10300:     if ($failed) {
10301:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10302:         $r->print(&Apache::loncommon::start_data_table()."\n".
10303:                  &Apache::loncommon::start_data_table_header_row()."\n".
10304:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10305:                  &Apache::loncommon::end_data_table_header_row()."\n".
10306:                  $badstudents."\n".
10307:                  &Apache::loncommon::end_data_table()).'<br />'.
10308:                  &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.');  
10309:     }
10310:     $r->print('</form><br />');
10311:     return;
10312: }
10313: 
10314: sub verify_scantron_grading {
10315:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10316:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10317:         $respnumlookup,$startline) = @_;
10318:     my ($record,%expected,%startpos);
10319:     return ($counter,$record) if (!ref($resource));
10320:     return ($counter,$record) if (!$resource->is_problem());
10321:     my $symb = $resource->symb();
10322:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10323:     foreach my $part_id (@{$partids}) {
10324:         $counter ++;
10325:         $expected{$part_id} = 0;
10326:         my $respnum = $counter;
10327:         if ($randomorder || $randompick) {
10328:             $respnum = $respnumlookup->{$counter};
10329:             $startpos{$part_id} = $startline->{$counter} + 1;
10330:         } else {
10331:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10332:         }
10333:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10334:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10335:             foreach my $item (@sub_lines) {
10336:                 $expected{$part_id} += $item;
10337:             }
10338:         } else {
10339:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10340:         }
10341:     }
10342:     if ($symb) {
10343:         my %recorded;
10344:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10345:         if ($returnhash{'version'}) {
10346:             my %lasthash=();
10347:             my $version;
10348:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10349:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10350:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10351:                 }
10352:             }
10353:             foreach my $key (keys(%lasthash)) {
10354:                 if ($key =~ /\.scantron$/) {
10355:                     my $value = &unescape($lasthash{$key});
10356:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10357:                     if ($value eq '') {
10358:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10359:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10360:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10361:                             }
10362:                         }
10363:                     } else {
10364:                         my @tocheck;
10365:                         my @items = split(//,$value);
10366:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10367:                             ($scantron_config->{'Qon'} eq 'number')) {
10368:                             if (@items < $expected{$part_id}) {
10369:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10370:                                 my @singles = split(//,$fragment);
10371:                                 foreach my $pos (@singles) {
10372:                                     if ($pos eq ' ') {
10373:                                         push(@tocheck,$pos);
10374:                                     } else {
10375:                                         my $next = shift(@items);
10376:                                         push(@tocheck,$next);
10377:                                     }
10378:                                 }
10379:                             } else {
10380:                                 @tocheck = @items;
10381:                             }
10382:                             foreach my $letter (@tocheck) {
10383:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10384:                                     if ($letter !~ /^[A-J]$/) {
10385:                                         $letter = $scantron_config->{'Qoff'};
10386:                                     }
10387:                                     $recorded{$part_id} .= $letter;
10388:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10389:                                     my $digit;
10390:                                     if ($letter !~ /^[A-J]$/) {
10391:                                         $digit = $scantron_config->{'Qoff'};
10392:                                     } else {
10393:                                         $digit = $lettdig->{$letter};
10394:                                     }
10395:                                     $recorded{$part_id} .= $digit;
10396:                                 }
10397:                             }
10398:                         } else {
10399:                             @tocheck = @items;
10400:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10401:                                 my $curr_sub = shift(@tocheck);
10402:                                 my $digit;
10403:                                 if ($curr_sub =~ /^[A-J]$/) {
10404:                                     $digit = $lettdig->{$curr_sub}-1;
10405:                                 }
10406:                                 if ($curr_sub eq 'J') {
10407:                                     $digit += scalar($numletts);
10408:                                 }
10409:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10410:                                     if ($j == $digit) {
10411:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10412:                                     } else {
10413:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10414:                                     }
10415:                                 }
10416:                             }
10417:                         }
10418:                     }
10419:                 }
10420:             }
10421:         }
10422:         foreach my $part_id (@{$partids}) {
10423:             if ($recorded{$part_id} eq '') {
10424:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10425:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10426:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10427:                     }
10428:                 }
10429:             }
10430:             $record .= $recorded{$part_id};
10431:         }
10432:     }
10433:     return ($counter,$record);
10434: }
10435: 
10436: #-------- end of section for handling grading scantron forms -------
10437: #
10438: #-------------------------------------------------------------------
10439: 
10440: #-------------------------- Menu interface -------------------------
10441: #
10442: #--- Href with symb and command ---
10443: 
10444: sub href_symb_cmd {
10445:     my ($symb,$cmd)=@_;
10446:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10447: }
10448: 
10449: sub grading_menu {
10450:     my ($request,$symb) = @_;
10451:     if (!$symb) {return '';}
10452: 
10453:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10454:                   'command'=>'individual');
10455:     
10456:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10457: 
10458:     $fields{'command'}='ungraded';
10459:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10460: 
10461:     $fields{'command'}='table';
10462:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10463: 
10464:     $fields{'command'}='all_for_one';
10465:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10466: 
10467:     $fields{'command'}='downloadfilesselect';
10468:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10469: 
10470:     $fields{'command'} = 'csvform';
10471:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10472:     
10473:     $fields{'command'} = 'processclicker';
10474:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10475:     
10476:     $fields{'command'} = 'scantron_selectphase';
10477:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10478: 
10479:     $fields{'command'} = 'initialverifyreceipt';
10480:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10481: 
10482:     my %permissions;
10483:     if ($perm{'mgr'}) {
10484:         $permissions{'either'} = 'F';
10485:         $permissions{'mgr'} = 'F';
10486:     }
10487:     if ($perm{'vgr'}) {
10488:         $permissions{'either'} = 'F';
10489:         $permissions{'vgr'} = 'F';
10490:     }
10491: 
10492:     my @menu = ({	categorytitle=>'Hand Grading',
10493:             items =>[
10494:                         {	linktext => 'Select individual students to grade',
10495:                     		url => $url1a,
10496:                     		permission => $permissions{'either'},
10497:                     		icon => 'grade_students.png',
10498:                     		linktitle => 'Grade current resource for a selection of students.'
10499:                         }, 
10500:                         {       linktext => 'Grade ungraded submissions',
10501:                                 url => $url1b,
10502:                                 permission => $permissions{'either'},
10503:                                 icon => 'ungrade_sub.png',
10504:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10505:                         },
10506: 
10507:                         {       linktext => 'Grading table',
10508:                                 url => $url1c,
10509:                                 permission => $permissions{'either'},
10510:                                 icon => 'grading_table.png',
10511:                                 linktitle => 'Grade current resource for all students.'
10512:                         },
10513:                         {       linktext => 'Grade page/folder for one student',
10514:                                 url => $url1d,
10515:                                 permission => $permissions{'either'},
10516:                                 icon => 'grade_PageFolder.png',
10517:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10518:                         },
10519:                         {       linktext => 'Download submissions',
10520:                                 url => $url1e,
10521:                                 permission => $permissions{'either'},
10522:                                 icon => 'download_sub.png',
10523:                                 linktitle => 'Download all students submissions.'
10524:                         }]},
10525:                          { categorytitle=>'Automated Grading',
10526:                items =>[
10527: 
10528:                 	    {	linktext => 'Upload Scores',
10529:                     		url => $url2,
10530:                     		permission => $permissions{'mgr'},
10531:                     		icon => 'uploadscores.png',
10532:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10533:                 	    },
10534:                 	    {	linktext => 'Process Clicker',
10535:                     		url => $url3,
10536:                     		permission => $permissions{'mgr'},
10537:                     		icon => 'addClickerInfoFile.png',
10538:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10539:                 	    },
10540:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10541:                     		url => $url4,
10542:                     		permission => $permissions{'mgr'},
10543:                     		icon => 'bubblesheet.png',
10544:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10545:                 	    },
10546:                             {   linktext => 'Verify Receipt Number',
10547:                                 url => $url5,
10548:                                 permission => $permissions{'either'},
10549:                                 icon => 'receipt_number.png',
10550:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10551:                             }
10552: 
10553:                     ]
10554:             });
10555: 
10556:     # Create the menu
10557:     my $Str;
10558:     $Str .= '<form method="post" action="" name="gradingMenu">';
10559:     $Str .= '<input type="hidden" name="command" value="" />'.
10560:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10561: 
10562:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10563:     return $Str;    
10564: }
10565: 
10566: sub ungraded {
10567:     my ($request)=@_;
10568:     &submit_options($request);
10569: }
10570: 
10571: sub submit_options_sequence {
10572:     my ($request,$symb) = @_;
10573:     if (!$symb) {return '';}
10574:     &commonJSfunctions($request);
10575:     my $result;
10576: 
10577:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10578:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10579:     $result.=&selectfield(0).
10580:             '<input type="hidden" name="command" value="pickStudentPage" />
10581:             <div>
10582:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10583:             </div>
10584:         </div>
10585:   </form>';
10586:     return $result;
10587: }
10588: 
10589: sub submit_options_table {
10590:     my ($request,$symb) = @_;
10591:     if (!$symb) {return '';}
10592:     &commonJSfunctions($request);
10593:     my $is_tool = ($symb =~ /ext\.tool$/);
10594:     my $result;
10595: 
10596:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10597:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10598: 
10599:     $result.=&selectfield(1,$is_tool).
10600:             '<input type="hidden" name="command" value="viewgrades" />
10601:             <div>
10602:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10603:             </div>
10604:         </div>
10605:   </form>';
10606:     return $result;
10607: }
10608: 
10609: sub submit_options_download {
10610:     my ($request,$symb) = @_;
10611:     if (!$symb) {return '';}
10612: 
10613:     my $res_error;
10614:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10615:         &response_type($symb,\$res_error);
10616:     if ($res_error) {
10617:         $request->print(&mt('An error occurred retrieving response types'));
10618:         return;
10619:     }
10620:     unless ($numessay) {
10621:         $request->print(&mt('No essayresponse items found'));
10622:         return;
10623:     }
10624:     my $table;
10625:     if (ref($partlist) eq 'ARRAY') {
10626:         if (scalar(@$partlist) > 1 ) {
10627:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10628:         }
10629:     }
10630: 
10631:     my $is_tool = ($symb =~ /ext\.tool$/);
10632:     &commonJSfunctions($request);
10633: 
10634:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10635:                $table."\n".
10636:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10637:     $result.='
10638: <h2>
10639:   '.&mt('Select Students for whom to Download Submissions').'
10640: </h2>'.&selectfield(1,$is_tool).'
10641:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10642:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10643:             </div>
10644:           </div>
10645: 
10646: 
10647:   </form>';
10648:     return $result;
10649: }
10650: 
10651: #--- Displays the submissions first page -------
10652: sub submit_options {
10653:     my ($request,$symb) = @_;
10654:     if (!$symb) {return '';}
10655: 
10656:     my $is_tool = ($symb =~ /ext\.tool$/);
10657:     &commonJSfunctions($request);
10658:     my $result;
10659: 
10660:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10661: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10662:     $result.=&selectfield(1,$is_tool).'
10663:                 <input type="hidden" name="command" value="submission" /> 
10664: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10665:             </div>
10666:           </div>
10667:   </form>';
10668:     return $result;
10669: }
10670: 
10671: sub selectfield {
10672:    my ($full,$is_tool)=@_;
10673:    my %options;
10674:    if ($is_tool) {
10675:        %options =
10676:            (&transtatus_options,
10677:             'select_form_order' => ['yes','incorrect','all']);
10678:    } else {
10679:        %options = 
10680:            (&substatus_options,
10681:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10682:    }
10683: 
10684:   #
10685:   # PrepareClasslist() needs to be called to avoid getting a sections list
10686:   # for a different course from the @Sections global in lonstatistics.pm, 
10687:   # populated by an earlier request.
10688:   #
10689:    &Apache::lonstatistics::PrepareClasslist();
10690: 
10691:    my $result='<div class="LC_columnSection">
10692:   
10693:     <fieldset>
10694:       <legend>
10695:        '.&mt('Sections').'
10696:       </legend>
10697:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10698:     </fieldset>
10699:   
10700:     <fieldset>
10701:       <legend>
10702:         '.&mt('Groups').'
10703:       </legend>
10704:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10705:     </fieldset>
10706:   
10707:     <fieldset>
10708:       <legend>
10709:         '.&mt('Access Status').'
10710:       </legend>
10711:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10712:     </fieldset>';
10713:     if ($full) {
10714:         my $heading = &mt('Submission Status');
10715:         if ($is_tool) {
10716:             $heading = &mt('Transaction Status');
10717:         }
10718:         $result.='
10719:     <fieldset>
10720:       <legend>
10721:         '.$heading.'
10722:       </legend>'.
10723:        &Apache::loncommon::select_form('all','submitonly',\%options).
10724:    '</fieldset>';
10725:     }
10726:     $result.='</div><br />';
10727:     return $result;
10728: }
10729: 
10730: sub substatus_options {
10731:     return &Apache::lonlocal::texthash(
10732:                                       'yes'       => 'with submissions',
10733:                                       'queued'    => 'in grading queue',
10734:                                       'graded'    => 'with ungraded submissions',
10735:                                       'incorrect' => 'with incorrect submissions',
10736:                                       'all'       => 'with any status',
10737:                                       );
10738: }
10739: 
10740: sub transtatus_options {
10741:     return &Apache::lonlocal::texthash(
10742:                                        'yes'       => 'with score transactions',
10743:                                        'incorrect' => 'with less than full credit',
10744:                                        'all'       => 'with any status',
10745:                                       );
10746: }
10747: 
10748: sub reset_perm {
10749:     undef(%perm);
10750: }
10751: 
10752: sub init_perm {
10753:     &reset_perm();
10754:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10755: 
10756: 	my $scope = $env{'request.course.id'};
10757: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10758: 
10759: 	    $scope .= '/'.$env{'request.course.sec'};
10760: 	    if ( $perm{$test_perm}=
10761: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10762: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10763: 	    } else {
10764: 		delete($perm{$test_perm});
10765: 	    }
10766: 	}
10767:     }
10768: }
10769: 
10770: sub init_old_essays {
10771:     my ($symb,$apath,$adom,$aname) = @_;
10772:     if ($symb ne '') {
10773:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10774:         if (keys(%essays) > 0) {
10775:             $old_essays{$symb} = \%essays;
10776:         }
10777:     }
10778:     return;
10779: }
10780: 
10781: sub reset_old_essays {
10782:     undef(%old_essays);
10783: }
10784: 
10785: sub gather_clicker_ids {
10786:     my %clicker_ids;
10787: 
10788:     my $classlist = &Apache::loncoursedata::get_classlist();
10789: 
10790:     # Set up a couple variables.
10791:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10792:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10793:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10794: 
10795:     foreach my $student (keys(%$classlist)) {
10796:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10797:         my $username = $classlist->{$student}->[$username_idx];
10798:         my $domain   = $classlist->{$student}->[$domain_idx];
10799:         my $clickers =
10800: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10801:         foreach my $id (split(/\,/,$clickers)) {
10802:             $id=~s/^[\#0]+//;
10803:             $id=~s/[\-\:]//g;
10804:             if (exists($clicker_ids{$id})) {
10805: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10806:             } else {
10807: 		$clicker_ids{$id}=$username.':'.$domain;
10808:             }
10809:         }
10810:     }
10811:     return %clicker_ids;
10812: }
10813: 
10814: sub gather_adv_clicker_ids {
10815:     my %clicker_ids;
10816:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10817:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10818:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10819:     foreach my $element (sort(keys(%coursepersonnel))) {
10820:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10821:             my ($puname,$pudom)=split(/\:/,$person);
10822:             my $clickers =
10823: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10824:             foreach my $id (split(/\,/,$clickers)) {
10825: 		$id=~s/^[\#0]+//;
10826:                 $id=~s/[\-\:]//g;
10827: 		if (exists($clicker_ids{$id})) {
10828: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10829: 		} else {
10830: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10831: 		}
10832:             }
10833:         }
10834:     }
10835:     return %clicker_ids;
10836: }
10837: 
10838: sub clicker_grading_parameters {
10839:     return ('gradingmechanism' => 'scalar',
10840:             'upfiletype' => 'scalar',
10841:             'specificid' => 'scalar',
10842:             'pcorrect' => 'scalar',
10843:             'pincorrect' => 'scalar');
10844: }
10845: 
10846: sub process_clicker {
10847:     my ($r,$symb)=@_;
10848:     if (!$symb) {return '';}
10849:     my $result=&checkforfile_js();
10850:     $result.=&Apache::loncommon::start_data_table().
10851:              &Apache::loncommon::start_data_table_header_row().
10852:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10853:              &Apache::loncommon::end_data_table_header_row().
10854:              &Apache::loncommon::start_data_table_row()."<td>\n";
10855: # Attempt to restore parameters from last session, set defaults if not present
10856:     my %Saveable_Parameters=&clicker_grading_parameters();
10857:     &Apache::loncommon::restore_course_settings('grades_clicker',
10858:                                                  \%Saveable_Parameters);
10859:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10860:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10861:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10862:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10863: 
10864:     my %checked;
10865:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10866:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10867:           $checked{$gradingmechanism}=' checked="checked"';
10868:        }
10869:     }
10870: 
10871:     my $upload=&mt("Evaluate File");
10872:     my $type=&mt("Type");
10873:     my $attendance=&mt("Award points just for participation");
10874:     my $personnel=&mt("Correctness determined from response by course personnel");
10875:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10876:     my $given=&mt("Correctness determined from given list of answers").' '.
10877:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10878:     my $pcorrect=&mt("Percentage points for correct solution");
10879:     my $pincorrect=&mt("Percentage points for incorrect solution");
10880:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10881: 						   {'iclicker' => 'i>clicker',
10882:                                                     'interwrite' => 'interwrite PRS',
10883:                                                     'turning' => 'Turning Technologies'});
10884:     $symb = &Apache::lonenc::check_encrypt($symb);
10885:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10886: function sanitycheck() {
10887: // Accept only integer percentages
10888:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10889:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10890: // Find out grading choice
10891:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10892:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10893:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10894:       }
10895:    }
10896: // By default, new choice equals user selection
10897:    newgradingchoice=gradingchoice;
10898: // Not good to give more points for false answers than correct ones
10899:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10900:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10901:    }
10902: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10903:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10904:       document.forms.gradesupload.pcorrect.value=100;
10905:       document.forms.gradesupload.pincorrect.value=100;
10906:    }
10907: // If the values are different, cannot be attendance only
10908:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10909:        (gradingchoice=='attendance')) {
10910:        newgradingchoice='personnel';
10911:    }
10912: // Change grading choice to new one
10913:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10914:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10915:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10916:       } else {
10917:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10918:       }
10919:    }
10920: // Remember the old state
10921:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10922: }
10923: ENDUPFORM
10924:     $result.= <<ENDUPFORM;
10925: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10926: <input type="hidden" name="symb" value="$symb" />
10927: <input type="hidden" name="command" value="processclickerfile" />
10928: <input type="file" name="upfile" size="50" />
10929: <br /><label>$type: $selectform</label>
10930: ENDUPFORM
10931:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10932:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10933:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10934: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10935: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10936: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10937: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10938: <br />&nbsp;&nbsp;&nbsp;
10939: <input type="text" name="givenanswer" size="50" />
10940: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10941: ENDGRADINGFORM
10942:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10943:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10944:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10945: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10946: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10947: </form>
10948: ENDPERCFORM
10949:     $result.='</td>'.
10950:              &Apache::loncommon::end_data_table_row().
10951:              &Apache::loncommon::end_data_table();
10952:     return $result;
10953: }
10954: 
10955: sub process_clicker_file {
10956:     my ($r,$symb) = @_;
10957:     if (!$symb) {return '';}
10958: 
10959:     my %Saveable_Parameters=&clicker_grading_parameters();
10960:     &Apache::loncommon::store_course_settings('grades_clicker',
10961:                                               \%Saveable_Parameters);
10962:     my $result='';
10963:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10964: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10965: 	return $result;
10966:     }
10967:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10968:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10969:         return $result;
10970:     }
10971:     my $foundgiven=0;
10972:     if ($env{'form.gradingmechanism'} eq 'given') {
10973:         $env{'form.givenanswer'}=~s/^\s*//gs;
10974:         $env{'form.givenanswer'}=~s/\s*$//gs;
10975:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10976:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10977:         my @answers=split(/\,/,$env{'form.givenanswer'});
10978:         $foundgiven=$#answers+1;
10979:     }
10980:     my %clicker_ids=&gather_clicker_ids();
10981:     my %correct_ids;
10982:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10983: 	%correct_ids=&gather_adv_clicker_ids();
10984:     }
10985:     if ($env{'form.gradingmechanism'} eq 'specific') {
10986: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10987: 	   $correct_id=~tr/a-z/A-Z/;
10988: 	   $correct_id=~s/\s//gs;
10989: 	   $correct_id=~s/^[\#0]+//;
10990:            $correct_id=~s/[\-\:]//g;
10991:            if ($correct_id) {
10992: 	      $correct_ids{$correct_id}='specified';
10993:            }
10994:         }
10995:     }
10996:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10997: 	$result.=&mt('Score based on attendance only');
10998:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10999:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
11000:     } else {
11001: 	my $number=0;
11002: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
11003: 	foreach my $id (sort(keys(%correct_ids))) {
11004: 	    $result.='<br /><tt>'.$id.'</tt> - ';
11005: 	    if ($correct_ids{$id} eq 'specified') {
11006: 		$result.=&mt('specified');
11007: 	    } else {
11008: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
11009: 		$result.=&Apache::loncommon::plainname($uname,$udom);
11010: 	    }
11011: 	    $number++;
11012: 	}
11013:         $result.="</p>\n";
11014:         if ($number==0) {
11015:             $result .=
11016:                  &Apache::lonhtmlcommon::confirm_success(
11017:                      &mt('No IDs found to determine correct answer'),1);
11018:             return $result;
11019:         }
11020:     }
11021:     if (length($env{'form.upfile'}) < 2) {
11022:         $result .=
11023:             &Apache::lonhtmlcommon::confirm_success(
11024:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
11025:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
11026:         return $result;
11027:     }
11028:     my $mimetype;
11029:     if ($env{'form.upfiletype'} eq 'iclicker') {
11030:         my $mm = new File::MMagic;
11031:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
11032:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
11033:             $result.= '<p>'.
11034:                 &Apache::lonhtmlcommon::confirm_success(
11035:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
11036:             return $result;
11037:         }
11038:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
11039:         $result .= '<p>'.
11040:             &Apache::lonhtmlcommon::confirm_success(
11041:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
11042:         return $result;
11043:     }
11044: 
11045: # Were able to get all the info needed, now analyze the file
11046: 
11047:     $result.=&Apache::loncommon::studentbrowser_javascript();
11048:     $symb = &Apache::lonenc::check_encrypt($symb);
11049:     $result.=&Apache::loncommon::start_data_table().
11050:              &Apache::loncommon::start_data_table_header_row().
11051:              '<th>'.&mt('Evaluate clicker file').'</th>'.
11052:              &Apache::loncommon::end_data_table_header_row().
11053:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
11054: <td>
11055: <form method="post" action="/adm/grades" name="clickeranalysis">
11056: <input type="hidden" name="symb" value="$symb" />
11057: <input type="hidden" name="command" value="assignclickergrades" />
11058: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
11059: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
11060: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
11061: ENDHEADER
11062:     if ($env{'form.gradingmechanism'} eq 'given') {
11063:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
11064:     } 
11065:     my %responses;
11066:     my @questiontitles;
11067:     my $errormsg='';
11068:     my $number=0;
11069:     if ($env{'form.upfiletype'} eq 'iclicker') {
11070:         if ($mimetype eq 'text/plain') {
11071:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
11072:         } elsif ($mimetype eq 'text/html') {
11073:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
11074:         }
11075:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
11076:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
11077:     } elsif ($env{'form.upfiletype'} eq 'turning') {
11078:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
11079:     }
11080:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
11081:              '<input type="hidden" name="number" value="'.$number.'" />'.
11082:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
11083:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
11084:              '<br />';
11085:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
11086:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
11087:        return $result;
11088:     } 
11089: # Remember Question Titles
11090: # FIXME: Possibly need delimiter other than ":"
11091:     for (my $i=0;$i<$number;$i++) {
11092:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
11093:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
11094:     }
11095:     my $correct_count=0;
11096:     my $student_count=0;
11097:     my $unknown_count=0;
11098: # Match answers with usernames
11099: # FIXME: Possibly need delimiter other than ":"
11100:     foreach my $id (keys(%responses)) {
11101:        if ($correct_ids{$id}) {
11102:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
11103:           $correct_count++;
11104:        } elsif ($clicker_ids{$id}) {
11105:           if ($clicker_ids{$id}=~/\,/) {
11106: # More than one user with the same clicker!
11107:              $result.="</td>".&Apache::loncommon::end_data_table_row().
11108:                            &Apache::loncommon::start_data_table_row()."<td>".
11109:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
11110:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11111:                            "<select name='multi".$id."'>";
11112:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
11113:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
11114:              }
11115:              $result.='</select>';
11116:              $unknown_count++;
11117:           } else {
11118: # Good: found one and only one user with the right clicker
11119:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
11120:              $student_count++;
11121:           }
11122:        } else {
11123:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11124:                            &Apache::loncommon::start_data_table_row()."<td>".
11125:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11126:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11127:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11128:                    "\n".&mt("Domain").": ".
11129:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11130:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11131:           $unknown_count++;
11132:        }
11133:     }
11134:     $result.='<hr />'.
11135:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11136:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11137:        if ($correct_count==0) {
11138:           $errormsg.="Found no correct answers for grading!";
11139:        } elsif ($correct_count>1) {
11140:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11141:        }
11142:     }
11143:     if ($number<1) {
11144:        $errormsg.="Found no questions.";
11145:     }
11146:     if ($errormsg) {
11147:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11148:     } else {
11149:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11150:     }
11151:     $result.='</form></td>'.
11152:              &Apache::loncommon::end_data_table_row().
11153:              &Apache::loncommon::end_data_table();
11154:     return $result;
11155: }
11156: 
11157: sub iclicker_eval {
11158:     my ($questiontitles,$responses)=@_;
11159:     my $number=0;
11160:     my $errormsg='';
11161:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11162:         my %components=&Apache::loncommon::record_sep($line);
11163:         my @entries=map {$components{$_}} (sort(keys(%components)));
11164: 	if ($entries[0] eq 'Question') {
11165: 	    for (my $i=3;$i<$#entries;$i+=6) {
11166: 		$$questiontitles[$number]=$entries[$i];
11167: 		$number++;
11168: 	    }
11169: 	}
11170: 	if ($entries[0]=~/^\#/) {
11171: 	    my $id=$entries[0];
11172: 	    my @idresponses;
11173: 	    $id=~s/^[\#0]+//;
11174: 	    for (my $i=0;$i<$number;$i++) {
11175: 		my $idx=3+$i*6;
11176:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11177: 		push(@idresponses,$entries[$idx]);
11178: 	    }
11179: 	    $$responses{$id}=join(',',@idresponses);
11180: 	}
11181:     }
11182:     return ($errormsg,$number);
11183: }
11184: 
11185: sub iclickerxml_eval {
11186:     my ($questiontitles,$responses)=@_;
11187:     my $number=0;
11188:     my $errormsg='';
11189:     my @state;
11190:     my %respbyid;
11191:     my $p = HTML::Parser->new
11192:     (
11193:         xml_mode => 1,
11194:         start_h =>
11195:             [sub {
11196:                  my ($tagname,$attr) = @_;
11197:                  push(@state,$tagname);
11198:                  if ("@state" eq "ssn p") {
11199:                      my $title = $attr->{qn};
11200:                      $title =~ s/(^\s+|\s+$)//g;
11201:                      $questiontitles->[$number]=$title;
11202:                  } elsif ("@state" eq "ssn p v") {
11203:                      my $id = $attr->{id};
11204:                      my $entry = $attr->{ans};
11205:                      $id=~s/^[\#0]+//;
11206:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11207:                      $respbyid{$id}[$number] = $entry;
11208:                  }
11209:             }, "tagname, attr"],
11210:          end_h =>
11211:                [sub {
11212:                    my ($tagname) = @_;
11213:                    if ("@state" eq "ssn p") {
11214:                        $number++;
11215:                    }
11216:                    pop(@state);
11217:                 }, "tagname"],
11218:     );
11219: 
11220:     $p->parse($env{'form.upfile'});
11221:     $p->eof;
11222:     foreach my $id (keys(%respbyid)) {
11223:         $responses->{$id}=join(',',@{$respbyid{$id}});
11224:     }
11225:     return ($errormsg,$number);
11226: }
11227: 
11228: sub interwrite_eval {
11229:     my ($questiontitles,$responses)=@_;
11230:     my $number=0;
11231:     my $errormsg='';
11232:     my $skipline=1;
11233:     my $questionnumber=0;
11234:     my %idresponses=();
11235:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11236:         my %components=&Apache::loncommon::record_sep($line);
11237:         my @entries=map {$components{$_}} (sort(keys(%components)));
11238:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11239:         if ($entries[1] eq 'Response') { $skipline=1; }
11240:         next if $skipline;
11241:         if ($entries[0]!=$questionnumber) {
11242:            $questionnumber=$entries[0];
11243:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11244:            $number++;
11245:         }
11246:         my $id=$entries[4];
11247:         $id=~s/^[\#0]+//;
11248:         $id=~s/^v\d*\://i;
11249:         $id=~s/[\-\:]//g;
11250:         $idresponses{$id}[$number]=$entries[6];
11251:     }
11252:     foreach my $id (keys(%idresponses)) {
11253:        $$responses{$id}=join(',',@{$idresponses{$id}});
11254:        $$responses{$id}=~s/^\s*\,//;
11255:     }
11256:     return ($errormsg,$number);
11257: }
11258: 
11259: sub turning_eval {
11260:     my ($questiontitles,$responses)=@_;
11261:     my $number=0;
11262:     my $errormsg='';
11263:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11264:         my %components=&Apache::loncommon::record_sep($line);
11265:         my @entries=map {$components{$_}} (sort(keys(%components)));
11266:         if ($#entries>$number) { $number=$#entries; }
11267:         my $id=$entries[0];
11268:         my @idresponses;
11269:         $id=~s/^[\#0]+//;
11270:         unless ($id) { next; }
11271:         for (my $idx=1;$idx<=$#entries;$idx++) {
11272:             $entries[$idx]=~s/\,/\;/g;
11273:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11274:             push(@idresponses,$entries[$idx]);
11275:         }
11276:         $$responses{$id}=join(',',@idresponses);
11277:     }
11278:     for (my $i=1; $i<=$number; $i++) {
11279:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11280:     }
11281:     return ($errormsg,$number);
11282: }
11283: 
11284: 
11285: sub assign_clicker_grades {
11286:     my ($r,$symb) = @_;
11287:     if (!$symb) {return '';}
11288: # See which part we are saving to
11289:     my $res_error;
11290:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11291:     if ($res_error) {
11292:         return &navmap_errormsg();
11293:     }
11294: # FIXME: This should probably look for the first handgradeable part
11295:     my $part=$$partlist[0];
11296: # Start screen output
11297:     my $result = &Apache::loncommon::start_data_table().
11298:                  &Apache::loncommon::start_data_table_header_row().
11299:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11300:                  &Apache::loncommon::end_data_table_header_row().
11301:                  &Apache::loncommon::start_data_table_row().'<td>';
11302: # Get correct result
11303: # FIXME: Possibly need delimiter other than ":"
11304:     my @correct=();
11305:     my $gradingmechanism=$env{'form.gradingmechanism'};
11306:     my $number=$env{'form.number'};
11307:     if ($gradingmechanism ne 'attendance') {
11308:        foreach my $key (keys(%env)) {
11309:           if ($key=~/^form\.correct\:/) {
11310:              my @input=split(/\,/,$env{$key});
11311:              for (my $i=0;$i<=$#input;$i++) {
11312:                  if (($correct[$i]) && ($input[$i]) &&
11313:                      ($correct[$i] ne $input[$i])) {
11314:                     $result.='<br /><span class="LC_warning">'.
11315:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11316:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11317:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11318:                     $correct[$i]=$input[$i];
11319:                  }
11320:              }
11321:           }
11322:        }
11323:        for (my $i=0;$i<$number;$i++) {
11324:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11325:              $result.='<br /><span class="LC_error">'.
11326:                       &mt('No correct result given for question "[_1]"!',
11327:                           $env{'form.question:'.$i}).'</span>';
11328:           }
11329:        }
11330:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11331:     }
11332: # Start grading
11333:     my $pcorrect=$env{'form.pcorrect'};
11334:     my $pincorrect=$env{'form.pincorrect'};
11335:     my $storecount=0;
11336:     my %users=();
11337:     foreach my $key (keys(%env)) {
11338:        my $user='';
11339:        if ($key=~/^form\.student\:(.*)$/) {
11340:           $user=$1;
11341:        }
11342:        if ($key=~/^form\.unknown\:(.*)$/) {
11343:           my $id=$1;
11344:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11345:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11346:           } elsif ($env{'form.multi'.$id}) {
11347:              $user=$env{'form.multi'.$id};
11348:           }
11349:        }
11350:        if ($user) {
11351:           if ($users{$user}) {
11352:              $result.='<br /><span class="LC_warning">'.
11353:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11354:                       '</span><br />';
11355:           }
11356:           $users{$user}=1; 
11357:           my @answer=split(/\,/,$env{$key});
11358:           my $sum=0;
11359:           my $realnumber=$number;
11360:           for (my $i=0;$i<$number;$i++) {
11361:              if  ($correct[$i] eq '-') {
11362:                 $realnumber--;
11363:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11364:                 if ($gradingmechanism eq 'attendance') {
11365:                    $sum+=$pcorrect;
11366:                 } elsif ($correct[$i] eq '*') {
11367:                    $sum+=$pcorrect;
11368:                 } else {
11369: # We actually grade if correct or not
11370:                    my $increment=$pincorrect;
11371: # Special case: numerical answer "0"
11372:                    if ($correct[$i] eq '0') {
11373:                       if ($answer[$i]=~/^[0\.]+$/) {
11374:                          $increment=$pcorrect;
11375:                       }
11376: # General numerical answer, both evaluate to something non-zero
11377:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11378:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11379:                          $increment=$pcorrect;
11380:                       }
11381: # Must be just alphanumeric
11382:                    } elsif ($answer[$i] eq $correct[$i]) {
11383:                       $increment=$pcorrect;
11384:                    }
11385:                    $sum+=$increment;
11386:                 }
11387:              }
11388:           }
11389:           my $ave=$sum/(100*$realnumber);
11390: # Store
11391:           my ($username,$domain)=split(/\:/,$user);
11392:           my %grades=();
11393:           $grades{"resource.$part.solved"}='correct_by_override';
11394:           $grades{"resource.$part.awarded"}=$ave;
11395:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11396:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11397:                                                  $env{'request.course.id'},
11398:                                                  $domain,$username);
11399:           if ($returncode ne 'ok') {
11400:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11401:           } else {
11402:              $storecount++;
11403:           }
11404:        }
11405:     }
11406: # We are done
11407:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11408:              '</td>'.
11409:              &Apache::loncommon::end_data_table_row().
11410:              &Apache::loncommon::end_data_table();
11411:     return $result;
11412: }
11413: 
11414: sub navmap_errormsg {
11415:     return '<div class="LC_error">'.
11416:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11417:            &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>').
11418:            '</div>';
11419: }
11420: 
11421: sub startpage {
11422:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11423:     my %args;
11424:     if ($onload) {
11425:          my %loaditems = (
11426:                         'onload' => $onload,
11427:                       );
11428:          $args{'add_entries'} = \%loaditems;
11429:     }
11430:     if ($nomenu) {
11431:         $args{'only_body'} = 1; 
11432:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11433:     } else {
11434:         if ($env{'request.course.id'}) { 
11435:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11436:         }
11437:         $args{'bread_crumbs'} = $crumbs;
11438:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11439:         if ($env{'request.course.id'}) {
11440:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11441:         }
11442:     }
11443:     unless ($nodisplayflag) {
11444:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11445:     }
11446: }
11447: 
11448: sub select_problem {
11449:     my ($r)=@_;
11450:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11451:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11452:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11453:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11454: }
11455: 
11456: sub handler {
11457:     my $request=$_[0];
11458:     &reset_caches();
11459:     if ($request->header_only) {
11460:         &Apache::loncommon::content_type($request,'text/html');
11461:         $request->send_http_header;
11462:         return OK;
11463:     }
11464:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11465: 
11466: # see what command we need to execute
11467: 
11468:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11469:     my $command=$commands[0];
11470: 
11471:     &init_perm();
11472:     if (!$env{'request.course.id'}) {
11473:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11474:                 ($command =~ /^scantronupload/)) {
11475:             # Not in a course.
11476:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11477:             return HTTP_NOT_ACCEPTABLE;
11478:         }
11479:     } elsif (!%perm) {
11480:         $request->internal_redirect('/adm/quickgrades');
11481:         return OK;
11482:     }
11483:     &Apache::loncommon::content_type($request,'text/html');
11484:     $request->send_http_header;
11485: 
11486:     if ($#commands > 0) {
11487: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11488:     }
11489: 
11490: # see what the symb is
11491: 
11492:     my $symb=$env{'form.symb'};
11493:     unless ($symb) {
11494:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11495:        $symb=&Apache::lonnet::symbread($url);
11496:     }
11497:     &Apache::lonenc::check_decrypt(\$symb);
11498: 
11499:     $ssi_error = 0;
11500:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11501: #
11502: # Not called from a resource, but inside a course
11503: #    
11504:         &startpage($request,undef,[],1,1);
11505:         &select_problem($request);
11506:     } else {
11507: 	if ($command eq 'submission' && $perm{'vgr'}) {
11508:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11509:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11510:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11511:                     &choose_task_version_form($symb,$env{'form.student'},
11512:                                               $env{'form.userdom'});
11513:             }
11514:             my $divforres;
11515:             if ($env{'form.student'} eq '') {
11516:                 $js .= &part_selector_js();
11517:                 $onload = "toggleParts('gradesub');";
11518:             } else {
11519:                 $divforres = 1;
11520:             }
11521:             my $head_extra = $js;
11522:             unless ($env{'form.vProb'} eq 'no') {
11523:                 my $csslinks = &Apache::loncommon::css_links($symb);
11524:                 if ($csslinks) {
11525:                     $head_extra .= "\n$csslinks";
11526:                 }
11527:             }
11528:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11529:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11530:             if ($versionform) {
11531:                 if ($divforres) {
11532:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11533:                 }
11534:                 $request->print($versionform);
11535:             }
11536: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11537:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11538:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11539:                 &choose_task_version_form($symb,$env{'form.student'},
11540:                                           $env{'form.userdom'},
11541:                                           $env{'form.inhibitmenu'});
11542:             my $head_extra = $js;
11543:             unless ($env{'form.vProb'} eq 'no') {
11544:                 my $csslinks = &Apache::loncommon::css_links($symb);
11545:                 if ($csslinks) {
11546:                     $head_extra .= "\n$csslinks";
11547:                 }
11548:             }
11549:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11550:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11551:             if ($versionform) {
11552:                 $request->print($versionform);
11553:             }
11554:             $request->print('<br clear="all" />');
11555:             $request->print(&show_previous_task_version($request,$symb));
11556: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11557:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11558:                                        {href=>'',text=>'Select student'}],1,1);
11559: 	    &pickStudentPage($request,$symb);
11560: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11561:             my $csslinks;
11562:             unless ($env{'form.vProb'} eq 'no') {
11563:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11564:             }
11565:             &startpage($request,$symb,
11566:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11567:                                        {href=>'',text=>'Select student'},
11568:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11569: 	    &displayPage($request,$symb);
11570: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11571:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11572:                                        {href=>'',text=>'Select student'},
11573:                                        {href=>'',text=>'Grade student'},
11574:                                        {href=>'',text=>'Store grades'}],1,1);
11575: 	    &updateGradeByPage($request,$symb);
11576: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11577:             my $csslinks;
11578:             unless ($env{'form.vProb'} eq 'no') {
11579:                 $csslinks = &Apache::loncommon::css_links($symb);
11580:             }
11581:             &startpage($request,$symb,[{href=>'',text=>'...'},
11582:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11583: 	    &processGroup($request,$symb);
11584: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11585:             &startpage($request,$symb);
11586: 	    $request->print(&grading_menu($request,$symb));
11587: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11588:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11589: 	    $request->print(&submit_options($request,$symb));
11590:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11591:             my $js = &part_selector_js();
11592:             my $onload = "toggleParts('gradesub');";
11593:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11594:                        undef,undef,undef,undef,undef,$js,$onload);
11595:             $request->print(&listStudents($request,$symb,'graded'));
11596:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11597:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11598:             $request->print(&submit_options_table($request,$symb));
11599:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11600:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11601:             $request->print(&submit_options_sequence($request,$symb));
11602: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11603:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11604: 	    $request->print(&viewgrades($request,$symb));
11605: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11606:             &startpage($request,$symb,[{href=>'',text=>'...'},
11607:                                        {href=>'',text=>'Store grades'}]);
11608: 	    $request->print(&processHandGrade($request,$symb));
11609: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11610:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11611:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11612:                                                                              text=>"Modify grades"},
11613:                                        {href=>'', text=>"Store grades"}]);
11614: 	    $request->print(&editgrades($request,$symb));
11615:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11616:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11617:             $request->print(&initialverifyreceipt($request,$symb));
11618: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11619:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11620:                                        {href=>'',text=>'Verification Result'}]);
11621: 	    $request->print(&verifyreceipt($request,$symb));
11622:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11623:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11624:             $request->print(&process_clicker($request,$symb));
11625:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11626:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11627:                                        {href=>'', text=>'Process clicker file'}]);
11628:             $request->print(&process_clicker_file($request,$symb));
11629:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11630:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11631:                                        {href=>'', text=>'Process clicker file'},
11632:                                        {href=>'', text=>'Store grades'}]);
11633:             $request->print(&assign_clicker_grades($request,$symb));
11634: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11635:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11636: 	    $request->print(&upcsvScores_form($request,$symb));
11637: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11638:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11639: 	    $request->print(&csvupload($request,$symb));
11640: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11641:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11642: 	    $request->print(&csvuploadmap($request,$symb));
11643: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11644: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11645:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11646: 		$request->print(&csvuploadoptions($request,$symb));
11647: 	    } else {
11648: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11649: 		    $env{'form.upfile_associate'} = 'reverse';
11650: 		} else {
11651: 		    $env{'form.upfile_associate'} = 'forward';
11652: 		}
11653:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11654: 		$request->print(&csvuploadmap($request,$symb));
11655: 	    }
11656: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11657:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11658: 	    $request->print(&csvuploadassign($request,$symb));
11659: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11660:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11661:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11662: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11663:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11664:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11665:  	    $request->print(&scantron_do_warning($request,$symb));
11666: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11667:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11668: 	    $request->print(&scantron_validate_file($request,$symb));
11669: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11670:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11671: 	    $request->print(&scantron_process_students($request,$symb));
11672:  	} elsif ($command eq 'scantronupload' && 
11673:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11674:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11675:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11676:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11677:  	} elsif ($command eq 'scantronupload_save' &&
11678:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11679:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11680:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11681:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11682:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11683:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11684:         } elsif ($command eq 'scantronupload_delete' &&
11685:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11686:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11687:             &scantron_upload_delete($request,$symb);
11688:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11689:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11690:             $request->print(&checkscantron_results($request,$symb));
11691:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11692:             my $js = &part_selector_js();
11693:             my $onload = "toggleParts('gradingMenu');";
11694:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11695:                        undef,undef,undef,undef,undef,$js,$onload);
11696:             $request->print(&submit_options_download($request,$symb));
11697:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11698:             &startpage($request,$symb,
11699:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11700:     {href=>'', text=>'Download submitted files'}],
11701:                undef,undef,undef,undef,undef,undef,undef,1);
11702:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11703:             &submit_download_link($request,$symb);
11704: 	} elsif ($command) {
11705:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11706: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11707: 	}
11708:     }
11709:     if ($ssi_error) {
11710: 	&ssi_print_error($request);
11711:     }
11712:     if ($env{'form.inhibitmenu'}) {
11713:         $request->print(&Apache::loncommon::end_page());
11714:     } elsif ($env{'request.course.id'}) {
11715:         &Apache::lonquickgrades::endGradeScreen($request);
11716:     }
11717:     &reset_caches();
11718:     return OK;
11719: }
11720: 
11721: 1;
11722: 
11723: __END__;
11724: 
11725: 
11726: =head1 NAME
11727: 
11728: Apache::grades
11729: 
11730: =head1 SYNOPSIS
11731: 
11732: Handles the viewing of grades.
11733: 
11734: This is part of the LearningOnline Network with CAPA project
11735: described at http://www.lon-capa.org.
11736: 
11737: =head1 OVERVIEW
11738: 
11739: Do an ssi with retries:
11740: While I'd love to factor out this with the version in lonprintout,
11741: 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
11742: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11743: 
11744: At least the logic that drives this has been pulled out into loncommon.
11745: 
11746: 
11747: 
11748: ssi_with_retries - Does the server side include of a resource.
11749:                      if the ssi call returns an error we'll retry it up to
11750:                      the number of times requested by the caller.
11751:                      If we still have a problem, no text is appended to the
11752:                      output and we set some global variables.
11753:                      to indicate to the caller an SSI error occurred.  
11754:                      All of this is supposed to deal with the issues described
11755:                      in LON-CAPA BZ 5631 see:
11756:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11757:                      by informing the user that this happened.
11758: 
11759: Parameters:
11760:   resource   - The resource to include.  This is passed directly, without
11761:                interpretation to lonnet::ssi.
11762:   form       - The form hash parameters that guide the interpretation of the resource
11763:                
11764:   retries    - Number of retries allowed before giving up completely.
11765: Returns:
11766:   On success, returns the rendered resource identified by the resource parameter.
11767: Side Effects:
11768:   The following global variables can be set:
11769:    ssi_error                - If an unrecoverable error occurred this becomes true.
11770:                               It is up to the caller to initialize this to false
11771:                               if desired.
11772:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11773:                               of the resource that could not be rendered by the ssi
11774:                               call.
11775:    ssi_error_message   - The error string fetched from the ssi response
11776:                               in the event of an error.
11777: 
11778: 
11779: =head1 HANDLER SUBROUTINE
11780: 
11781: ssi_with_retries()
11782: 
11783: =head1 SUBROUTINES
11784: 
11785: =over
11786: 
11787: =head1 Routines to display previous version of a Task for a specific student
11788: 
11789: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11790: can receive another opportunity. Access to tasks is slot-based. If a slot
11791: requires a proctor to check-in the student, a new version of the Task will
11792: be created when the student is checked in to the new opportunity.
11793: 
11794: If a particular student has tried two or more versions of a particular task,
11795: the submission screen provides a user with vgr privileges (e.g., a Course
11796: Coordinator) the ability to display a previous version worked on by the
11797: student.  By default, the current version is displayed. If a previous version
11798: has been selected for display, submission data are only shown that pertain
11799: to that particular version, and the interface to submit grades is not shown.
11800: 
11801: =over 4
11802: 
11803: =item show_previous_task_version()
11804: 
11805: Displays a specified version of a student's Task, as the student sees it.
11806: 
11807: Inputs: 2
11808:         request - request object
11809:         symb    - unique symb for current instance of resource
11810: 
11811: Output: None.
11812: 
11813: Side Effects: calls &show_problem() to print version of Task, with
11814:               version contained in form item: $env{'form.previousversion'}
11815: 
11816: =item choose_task_version_form()
11817: 
11818: Displays a web form used to select which version of a student's view of a
11819: Task should be displayed.  Either launches a pop-up window, or replaces
11820: content in existing pop-up, or replaces page in main window.
11821: 
11822: Inputs: 4
11823:         symb    - unique symb for current instance of resource
11824:         uname   - username of student
11825:         udom    - domain of student
11826:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11827:                   breadcrumbs etc., are displayed
11828: 
11829: Output: 4
11830:         current   - student's current version
11831:         displayed - student's version being displayed
11832:         result    - scalar containing HTML for web form used to switch to
11833:                     a different version (or a link to close window, if pop-up).
11834:         js        - javascript for processing selection in versions web form
11835: 
11836: Side Effects: None.
11837: 
11838: =item previous_display_javascript()
11839: 
11840: Inputs: 2
11841:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11842:                   breadcrumbs etc., are displayed.
11843:         current - student's current version number.
11844: 
11845: Output: 1
11846:         js      - javascript for processing selection in versions web form.
11847: 
11848: Side Effects: None.
11849: 
11850: =back
11851: 
11852: =head1 Routines to process bubblesheet data.
11853: 
11854: =over 4
11855: 
11856: =item scantron_get_correction() : 
11857: 
11858:    Builds the interface screen to interact with the operator to fix a
11859:    specific error condition in a specific scanline
11860: 
11861:  Arguments:
11862:     $r           - Apache request object
11863:     $i           - number of the current scanline
11864:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11865:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11866:     $line        - full contents of the current scanline
11867:     $error       - error condition, valid values are
11868:                    'incorrectCODE', 'duplicateCODE',
11869:                    'doublebubble', 'missingbubble',
11870:                    'duplicateID', 'incorrectID'
11871:     $arg         - extra information needed
11872:        For errors:
11873:          - duplicateID   - paper number that this studentID was seen before on
11874:          - duplicateCODE - array ref of the paper numbers this CODE was
11875:                            seen on before
11876:          - incorrectCODE - current incorrect CODE 
11877:          - doublebubble  - array ref of the bubble lines that have double
11878:                            bubble errors
11879:          - missingbubble - array ref of the bubble lines that have missing
11880:                            bubble errors
11881: 
11882:    $randomorder - True if exam folder has randomorder set
11883:    $randompick  - True if exam folder has randompick set
11884:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11885:                      for current line to question number used for same question
11886:                      in "Master Seqence" (as seen by Course Coordinator).
11887:    $startline   - Reference to hash where key is question number (0 is first)
11888:                   and value is number of first bubble line for current student
11889:                   or code-based randompick and/or randomorder.
11890: 
11891: 
11892: 
11893: =item  scantron_get_maxbubble() : 
11894: 
11895:    Arguments:
11896:        $nav_error  - Reference to scalar which is a flag to indicate a
11897:                       failure to retrieve a navmap object.
11898:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11899:        calling routine should trap the error condition and display the warning
11900:        found in &navmap_errormsg().
11901: 
11902:        $scantron_config - Reference to bubblesheet format configuration hash.
11903: 
11904:    Returns the maximum number of bubble lines that are expected to
11905:    occur. Does this by walking the selected sequence rendering the
11906:    resource and then checking &Apache::lonxml::get_problem_counter()
11907:    for what the current value of the problem counter is.
11908: 
11909:    Caches the results to $env{'form.scantron_maxbubble'},
11910:    $env{'form.scantron.bubble_lines.n'}, 
11911:    $env{'form.scantron.first_bubble_line.n'} and
11912:    $env{"form.scantron.sub_bubblelines.n"}
11913:    which are the total number of bubble lines, the number of bubble
11914:    lines for response n and number of the first bubble line for response n,
11915:    and a comma separated list of numbers of bubble lines for sub-questions
11916:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11917: 
11918: 
11919: =item  scantron_validate_missingbubbles() : 
11920: 
11921:    Validates all scanlines in the selected file to not have any
11922:     answers that don't have bubbles that have not been verified
11923:     to be bubble free.
11924: 
11925: =item  scantron_process_students() : 
11926: 
11927:    Routine that does the actual grading of the bubblesheet information.
11928: 
11929:    The parsed scanline hash is added to %env 
11930: 
11931:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11932:    foreach resource , with the form data of
11933: 
11934: 	'submitted'     =>'scantron' 
11935: 	'grade_target'  =>'grade',
11936: 	'grade_username'=> username of student
11937: 	'grade_domain'  => domain of student
11938: 	'grade_courseid'=> of course
11939: 	'grade_symb'    => symb of resource to grade
11940: 
11941:     This triggers a grading pass. The problem grading code takes care
11942:     of converting the bubbled letter information (now in %env) into a
11943:     valid submission.
11944: 
11945: =item  scantron_upload_scantron_data() :
11946: 
11947:     Creates the screen for adding a new bubblesheet data file to a course.
11948: 
11949: =item  scantron_upload_scantron_data_save() : 
11950: 
11951:    Adds a provided bubble information data file to the course if user
11952:    has the correct privileges to do so.
11953: 
11954: = item scantron_upload_delete() :
11955: 
11956:    Deletes a previously uploaded bubble information data file, if user
11957:    was the one who uploaded the file, and has the privileges to do so.
11958: 
11959: =item  valid_file() :
11960: 
11961:    Validates that the requested bubble data file exists in the course.
11962: 
11963: =item  scantron_download_scantron_data() : 
11964: 
11965:    Shows a list of the three internal files (original, corrected,
11966:    skipped) for a specific bubblesheet data file that exists in the
11967:    course.
11968: 
11969: =item  scantron_validate_ID() : 
11970: 
11971:    Validates all scanlines in the selected file to not have any
11972:    invalid or underspecified student/employee IDs
11973: 
11974: =item navmap_errormsg() :
11975: 
11976:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11977:    Should be called whenever the request to instantiate a navmap object fails.
11978: 
11979: =back
11980: 
11981: =back
11982: 
11983: =cut

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