File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.773: download - view: text, annotated - select for diffs
Sun Aug 30 20:30:21 2020 UTC (3 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Grading interface changes March-April 2010 (rev. 1.598-1.633) reviewed.
  - Complete the elimination of form.handgrade
  - Re-instate use of &showResourceInfo()
    - If problem has multiple parts, can select which to grade
    - If problem has file upload items (in essayresponse) in multiple parts
      can select which parts to include when downloading submitted files
  - Keywords list menu only shown if selected problem contains one or more
    essayresponse items.
  - Table of options for grading individual students:
    (a) Send Messages - include ability to send a message (default is "Yes"
        if selected problem contains an essayresponse item, "No" otherwise.
    (b) Check For Plagiarism - only shown if selected problem contains
        an essayresponse item

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.773 2020/08/30 20:30:21 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use Apache::lontexconvert();
   50: use String::Similarity;
   51: use HTML::Parser();
   52: use File::MMagic;
   53: use LONCAPA;
   54: 
   55: use POSIX qw(floor);
   56: 
   57: 
   58: 
   59: my %perm=();
   60: my %old_essays=();
   61: 
   62: #  These variables are used to recover from ssi errors
   63: 
   64: my $ssi_retries = 5;
   65: my $ssi_error;
   66: my $ssi_error_resource;
   67: my $ssi_error_message;
   68: 
   69: 
   70: sub ssi_with_retries {
   71:     my ($resource, $retries, %form) = @_;
   72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   73:     if ($response->is_error) {
   74: 	$ssi_error          = 1;
   75: 	$ssi_error_resource = $resource;
   76: 	$ssi_error_message  = $response->code . " " . $response->message;
   77:     }
   78: 
   79:     return $content;
   80: 
   81: }
   82: #
   83: #  Prodcuces an ssi retry failure error message to the user:
   84: #
   85: 
   86: sub ssi_print_error {
   87:     my ($r) = @_;
   88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   89:     $r->print('
   90: <br />
   91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   92: <p>
   93: '.&mt('Unable to retrieve a resource from a server:').'<br />
   94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   95: '.&mt('Error:').' '.$ssi_error_message.'
   96: </p>
   97: <p>'.
   98: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  100: '</p>');
  101:     return;
  102: }
  103: 
  104: #
  105: # --- Retrieve the parts from the metadata file.---
  106: # Returns an array of everything that the resources stores away
  107: #
  108: 
  109: sub getpartlist {
  110:     my ($symb,$errorref) = @_;
  111: 
  112:     my $navmap   = Apache::lonnavmaps::navmap->new();
  113:     unless (ref($navmap)) {
  114:         if (ref($errorref)) { 
  115:             $$errorref = 'navmap';
  116:             return;
  117:         }
  118:     }
  119:     my $res      = $navmap->getBySymb($symb);
  120:     my $partlist = $res->parts();
  121:     my $url      = $res->src();
  122:     my $toolsymb;
  123:     if ($url =~ /ext\.tool$/) {
  124:         $toolsymb = $symb;
  125:     }
  126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  127: 
  128:     my @stores;
  129:     foreach my $part (@{ $partlist }) {
  130: 	foreach my $key (@metakeys) {
  131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  132: 	}
  133:     }
  134:     return @stores;
  135: }
  136: 
  137: #--- Format fullname, username:domain if different for display
  138: #--- Use anywhere where the student names are listed
  139: sub nameUserString {
  140:     my ($type,$fullname,$uname,$udom) = @_;
  141:     if ($type eq 'header') {
  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  143:     } else {
  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  146:     }
  147: }
  148: 
  149: #--- Get the partlist and the response type for a given problem. ---
  150: #--- Count responseIDs, essayresponse items, and dropbox items ---
  151: #--- Sets response_error pointer to "1" if navmaps object broken ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  169:     my %vPart = 
  170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  171:     my (%response_types,%handgrade);
  172:     foreach my $part (@{ $partlist }) {
  173: 	next if (%vPart && !exists($vPart{$part}));
  174: 
  175: 	my @types = $res->responseType($part);
  176: 	my @ids = $res->responseIds($part);
  177: 	for (my $i=0; $i < scalar(@ids); $i++) {
  178:             $numresp ++;
  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  180:             if ($types[$i] eq 'essay') {
  181:                 $numessay ++;
  182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  183:                     $numdropbox ++;
  184:                 }
  185:             }
  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
  187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  188: 				     '.handgrade',$symb);
  189: 	}
  190:     }
  191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  192: }
  193: 
  194: sub flatten_responseType {
  195:     my ($responseType) = @_;
  196:     my @part_response_id =
  197: 	map { 
  198: 	    my $part = $_;
  199: 	    map {
  200: 		[$part,$_]
  201: 		} sort(keys(%{ $responseType->{$part} }));
  202: 	} sort(keys(%$responseType));
  203:     return @part_response_id;
  204: }
  205: 
  206: sub get_display_part {
  207:     my ($partID,$symb)=@_;
  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  209:     if (defined($display) and $display ne '') {
  210:         $display.= ' (<span class="LC_internal_info">'
  211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  212:     } else {
  213: 	$display=$partID;
  214:     }
  215:     return $display;
  216: }
  217: 
  218: #--- Show parts and response type
  219: sub showResourceInfo {
  220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  222:         return '<br clear="all">';
  223:     }
  224:     my $coltitle = &mt('Problem Part Shown');
  225:     if ($checkboxes) {
  226:         $coltitle = &mt('Problem Part');
  227:     } else {
  228:         my $checkedparts = 0;
  229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  231:                 $checkedparts ++;
  232:             }
  233:         }
  234:         if ($checkedparts == scalar(@{$partlist})) {
  235:             return '<br clear="all">';
  236:         }
  237:         if ($uploads) {
  238:             $coltitle = &mt('Problem Part Selected');
  239:         }
  240:     }
  241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  242:     if ($checkboxes) {
  243:         my $legend = &mt('Parts to display');
  244:         if ($uploads) {
  245:             $legend = &mt('Part(s) with dropbox');
  246:         }
  247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  248:                    '<span class="LC_nobreak">'.
  249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  252:                    &mt('Selected parts').'</label></span>'.
  253:                    '<div id="LC_partselector" style="display:none">';
  254:     }
  255:     $result .= &Apache::loncommon::start_data_table()
  256:               .&Apache::loncommon::start_data_table_header_row();
  257:     if ($checkboxes) {
  258:         $result .= '<th>'.&mt('Display?').'</th>';
  259:     }
  260:     $result .= '<th>'.$coltitle.'</th>'
  261:               .'<th>'.&mt('Res. ID').'</th>'
  262:               .'<th>'.&mt('Type').'</th>'
  263:               .&Apache::loncommon::end_data_table_header_row();
  264:     my %partsseen;
  265:     foreach my $partID (sort(keys(%$responseType))) {
  266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  267:             my $responsetype = $responseType->{$partID}->{$resID};
  268:             if ($uploads) {
  269:                 next unless ($responsetype eq 'essay');
  270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  271:             }
  272:             my $display_part=&get_display_part($partID,$symb);
  273:             if (exists($partsseen{$partID})) {
  274:                 $result.=&Apache::loncommon::continue_data_table_row();
  275:             } else {
  276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  277:                 $result.=&Apache::loncommon::start_data_table_row().
  278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  279:                 if ($checkboxes) {
  280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  282:                 } else {
  283:                     $result.=$display_part.'</td>';
  284:                 }
  285:             }
  286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  287:                     .'<td>'.&mt($responsetype).'</td>'
  288:                     .&Apache::loncommon::end_data_table_row();
  289:         }
  290:     }
  291:     $result.=&Apache::loncommon::end_data_table();
  292:     if ($checkboxes) {
  293:         $result .= '</div></fieldset>';
  294:     }
  295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  296:     return $result;
  297: }
  298: 
  299: sub part_selector_js {
  300:     my $js = <<"END";
  301: function toggleParts(formname) {
  302:     if (document.getElementById('LC_partselector')) {
  303:         var index = '';
  304:         if (document.forms.length) {
  305:             for (var i=0; i<document.forms.length; i++) {
  306:                 if (document.forms[i].name == formname) {
  307:                     index = i;
  308:                     break;
  309:                 }
  310:             }
  311:         }
  312:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  313:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  314:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  315:                    var val = document.forms[index].elements['chooseparts'][i].value;
  316:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  317:                         document.getElementById('LC_partselector').style.display = 'block';
  318:                     } else {
  319:                         document.getElementById('LC_partselector').style.display = 'none';
  320:                     }
  321:                 }
  322:             }
  323:         }
  324:     }
  325: }
  326: END
  327:     return &Apache::lonhtmlcommon::scripttag($js);
  328: }
  329: 
  330: sub reset_caches {
  331:     &reset_analyze_cache();
  332:     &reset_perm();
  333:     &reset_old_essays();
  334: }
  335: 
  336: {
  337:     my %analyze_cache;
  338:     my %analyze_cache_formkeys;
  339: 
  340:     sub reset_analyze_cache {
  341: 	undef(%analyze_cache);
  342:         undef(%analyze_cache_formkeys);
  343:     }
  344: 
  345:     sub get_analyze {
  346: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  347: 	my $key = "$symb\0$uname\0$udom";
  348:         if ($type eq 'randomizetry') {
  349:             if ($trial ne '') {
  350:                 $key .= "\0".$trial;
  351:             }
  352:         }
  353: 	if (exists($analyze_cache{$key})) {
  354:             my $getupdate = 0;
  355:             if (ref($add_to_hash) eq 'HASH') {
  356:                 foreach my $item (keys(%{$add_to_hash})) {
  357:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  358:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  359:                             $getupdate = 1;
  360:                             last;
  361:                         }
  362:                     } else {
  363:                         $getupdate = 1;
  364:                     }
  365:                 }
  366:             }
  367:             if (!$getupdate) {
  368:                 return $analyze_cache{$key};
  369:             }
  370:         }
  371: 
  372: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  373: 	$url=&Apache::lonnet::clutter($url);
  374:         my %form = ('grade_target'      => 'analyze',
  375:                     'grade_domain'      => $udom,
  376:                     'grade_symb'        => $symb,
  377:                     'grade_courseid'    =>  $env{'request.course.id'},
  378:                     'grade_username'    => $uname,
  379:                     'grade_noincrement' => $no_increment);
  380:         if ($bubbles_per_row ne '') {
  381:             $form{'bubbles_per_row'} = $bubbles_per_row;
  382:         }
  383:         if ($type eq 'randomizetry') {
  384:             $form{'grade_questiontype'} = $type;
  385:             if ($rndseed ne '') {
  386:                 $form{'grade_rndseed'} = $rndseed;
  387:             }
  388:         }
  389:         if (ref($add_to_hash)) {
  390:             %form = (%form,%{$add_to_hash});
  391:         }
  392: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  393: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  394: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  395:         if (ref($add_to_hash) eq 'HASH') {
  396:             $analyze_cache_formkeys{$key} = $add_to_hash;
  397:         } else {
  398:             $analyze_cache_formkeys{$key} = {};
  399:         }
  400: 	return $analyze_cache{$key} = \%analyze;
  401:     }
  402: 
  403:     sub get_order {
  404: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  405: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  406: 	return $analyze->{"$partid.$respid.shown"};
  407:     }
  408: 
  409:     sub get_radiobutton_correct_foil {
  410: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  411: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  412:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  413:         if (ref($foils) eq 'ARRAY') {
  414: 	    foreach my $foil (@{$foils}) {
  415: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  416: 		    return $foil;
  417: 	        }
  418: 	    }
  419: 	}
  420:     }
  421: 
  422:     sub scantron_partids_tograde {
  423:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  424:         my (%analysis,@parts);
  425:         if (ref($resource)) {
  426:             my $symb = $resource->symb();
  427:             my $add_to_form;
  428:             if ($check_for_randomlist) {
  429:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  430:             }
  431:             if ($scancode) {
  432:                 if (ref($add_to_form) eq 'HASH') {
  433:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  434:                 } else {
  435:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  436:                 }
  437:             }
  438:             my $analyze =
  439:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  440:                              undef,undef,undef,$bubbles_per_row);
  441:             if (ref($analyze) eq 'HASH') {
  442:                 %analysis = %{$analyze};
  443:             }
  444:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  445:                 foreach my $part (@{$analysis{'parts'}}) {
  446:                     my ($id,$respid) = split(/\./,$part);
  447:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  448:                         push(@parts,$part);
  449:                     }
  450:                 }
  451:             }
  452:         }
  453:         return (\%analysis,\@parts);
  454:     }
  455: 
  456: }
  457: 
  458: #--- Clean response type for display
  459: #--- Currently filters option/rank/radiobutton/match/essay/Task
  460: #        response types only.
  461: sub cleanRecord {
  462:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  463: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  464:     my $grayFont = '<span class="LC_internal_info">';
  465:     if ($response =~ /^(option|rank)$/) {
  466: 	my %answer=&Apache::lonnet::str2hash($answer);
  467:         my @answer = %answer;
  468:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  469: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  470: 	my ($toprow,$bottomrow);
  471: 	foreach my $foil (@$order) {
  472: 	    if ($grading{$foil} == 1) {
  473: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  474: 	    } else {
  475: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  476: 	    }
  477: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  478: 	}
  479: 	return '<blockquote><table border="1">'.
  480: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  481: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  482: 	    $bottomrow.'</tr></table></blockquote>';
  483:     } elsif ($response eq 'match') {
  484: 	my %answer=&Apache::lonnet::str2hash($answer);
  485:         my @answer = %answer;
  486:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  487: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  488: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  489: 	my ($toprow,$middlerow,$bottomrow);
  490: 	foreach my $foil (@$order) {
  491: 	    my $item=shift(@items);
  492: 	    if ($grading{$foil} == 1) {
  493: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  494: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  495: 	    } else {
  496: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  497: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  498: 	    }
  499: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  500: 	}
  501: 	return '<blockquote><table border="1">'.
  502: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  503: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  504: 	    $middlerow.'</tr>'.
  505: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  506: 	    $bottomrow.'</tr></table></blockquote>';
  507:     } elsif ($response eq 'radiobutton') {
  508: 	my %answer=&Apache::lonnet::str2hash($answer);
  509:         my @answer = %answer;
  510:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  511: 	my ($toprow,$bottomrow);
  512: 	my $correct = 
  513: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  514: 	foreach my $foil (@$order) {
  515: 	    if (exists($answer{$foil})) {
  516: 		if ($foil eq $correct) {
  517: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  518: 		} else {
  519: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  520: 		}
  521: 	    } else {
  522: 		$toprow.='<td>'.&mt('false').'</td>';
  523: 	    }
  524: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  525: 	}
  526: 	return '<blockquote><table border="1">'.
  527: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  528: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  529: 	    $bottomrow.'</tr></table></blockquote>';
  530:     } elsif ($response eq 'essay') {
  531: 	if (! exists ($env{'form.'.$symb})) {
  532: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  533: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  534: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  535: 
  536: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  537: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  538: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  539: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  540: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  541: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  542: 	}
  543:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  544: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  545:     } elsif ( $response eq 'organic') {
  546:         my $result=&mt('Smile representation: [_1]',
  547:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  548: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  549: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  550: 	return $result;
  551:     } elsif ( $response eq 'Task') {
  552: 	if ( $answer eq 'SUBMITTED') {
  553: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  554: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  555: 	    return $result;
  556: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  557: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  558: 			       keys(%{$record}));
  559: 	    return join('<br />',($version,@matches));
  560: 			       
  561: 			       
  562: 	} else {
  563: 	    my $result =
  564: 		'<p>'
  565: 		.&mt('Overall result: [_1]',
  566: 		     $record->{$version."resource.$respid.$partid.status"})
  567: 		.'</p>';
  568: 	    
  569: 	    $result .= '<ul>';
  570: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  571: 			     keys(%{$record}));
  572: 	    foreach my $grade (sort(@grade)) {
  573: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  574: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  575: 				     $dim, $record->{$grade}).
  576: 			  '</li>';
  577: 	    }
  578: 	    $result.='</ul>';
  579: 	    return $result;
  580: 	}
  581:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  582:         # Respect multiple input fields, see Bug #5409
  583: 	$answer = 
  584: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  585: 							      $answer);
  586: 	return $answer;
  587:     }
  588:     return &HTML::Entities::encode($answer, '"<>&');
  589: }
  590: 
  591: #-- A couple of common js functions
  592: sub commonJSfunctions {
  593:     my $request = shift;
  594:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  595:     function radioSelection(radioButton) {
  596: 	var selection=null;
  597: 	if (radioButton.length > 1) {
  598: 	    for (var i=0; i<radioButton.length; i++) {
  599: 		if (radioButton[i].checked) {
  600: 		    return radioButton[i].value;
  601: 		}
  602: 	    }
  603: 	} else {
  604: 	    if (radioButton.checked) return radioButton.value;
  605: 	}
  606: 	return selection;
  607:     }
  608: 
  609:     function pullDownSelection(selectOne) {
  610: 	var selection="";
  611: 	if (selectOne.length > 1) {
  612: 	    for (var i=0; i<selectOne.length; i++) {
  613: 		if (selectOne[i].selected) {
  614: 		    return selectOne[i].value;
  615: 		}
  616: 	    }
  617: 	} else {
  618:             // only one value it must be the selected one
  619: 	    return selectOne.value;
  620: 	}
  621:     }
  622: COMMONJSFUNCTIONS
  623: }
  624: 
  625: #--- Dumps the class list with usernames,list of sections,
  626: #--- section, ids and fullnames for each user.
  627: sub getclasslist {
  628:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  629:     my @getsec;
  630:     my @getgroup;
  631:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  632:     if (!ref($getsec)) {
  633: 	if ($getsec ne '' && $getsec ne 'all') {
  634: 	    @getsec=($getsec);
  635: 	}
  636:     } else {
  637: 	@getsec=@{$getsec};
  638:     }
  639:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  640:     if (!ref($getgroup)) {
  641: 	if ($getgroup ne '' && $getgroup ne 'all') {
  642: 	    @getgroup=($getgroup);
  643: 	}
  644:     } else {
  645: 	@getgroup=@{$getgroup};
  646:     }
  647:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  648: 
  649:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  650:     # Bail out if we were unable to get the classlist
  651:     return if (! defined($classlist));
  652:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  653:     #
  654:     my %sections;
  655:     my %fullnames;
  656:     my ($cdom,$cnum,$partlist);
  657:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  658:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  659:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  660:         my $res_error;
  661:         ($partlist) = &response_type($symb,\$res_error);
  662:     }
  663:     foreach my $student (keys(%$classlist)) {
  664:         my $end      = 
  665:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  666:         my $start    = 
  667:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  668:         my $id       = 
  669:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  670:         my $section  = 
  671:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  672:         my $fullname = 
  673:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  674:         my $status   = 
  675:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  676:         my $group   = 
  677:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  678: 	# filter students according to status selected
  679: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  680: 	    if (!($stu_status =~ $status)) {
  681: 		delete($classlist->{$student});
  682: 		next;
  683: 	    }
  684: 	}
  685: 	# filter students according to groups selected
  686: 	my @stu_groups = split(/,/,$group);
  687: 	if (@getgroup) {
  688: 	    my $exclude = 1;
  689: 	    foreach my $grp (@getgroup) {
  690: 	        foreach my $stu_group (@stu_groups) {
  691: 	            if ($stu_group eq $grp) {
  692: 	                $exclude = 0;
  693:     	            } 
  694: 	        }
  695:     	        if (($grp eq 'none') && !$group) {
  696:         	    $exclude = 0;
  697:         	}
  698: 	    }
  699: 	    if ($exclude) {
  700: 	        delete($classlist->{$student});
  701: 		next;
  702: 	    }
  703: 	}
  704:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  705:             my $udom =
  706:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  707:             my $uname =
  708:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  709:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  710:                 if ($submitonly eq 'queued') {
  711:                     my %queue_status =
  712:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  713:                                                                 $udom,$uname);
  714:                     if (!defined($queue_status{'gradingqueue'})) {
  715:                         delete($classlist->{$student});
  716:                         next;
  717:                     }
  718:                 } else {
  719:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  720:                     my $submitted = 0;
  721:                     my $graded = 0;
  722:                     my $incorrect = 0;
  723:                     foreach (keys(%status)) {
  724:                         $submitted = 1 if ($status{$_} ne 'nothing');
  725:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  726:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  727: 
  728:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  729:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  730:                             $submitted = 0;
  731:                         }
  732:                     }
  733:                     if (!$submitted && ($submitonly eq 'yes' ||
  734:                                         $submitonly eq 'incorrect' ||
  735:                                         $submitonly eq 'graded')) {
  736:                         delete($classlist->{$student});
  737:                         next;
  738:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  739:                         delete($classlist->{$student});
  740:                         next;
  741:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  742:                         delete($classlist->{$student});
  743:                         next;
  744:                     }
  745:                 }
  746:             }
  747:         }
  748: 	$section = ($section ne '' ? $section : 'none');
  749: 	if (&canview($section)) {
  750: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  751: 		$sections{$section}++;
  752: 		if ($classlist->{$student}) {
  753: 		    $fullnames{$student}=$fullname;
  754: 		}
  755: 	    } else {
  756: 		delete($classlist->{$student});
  757: 	    }
  758: 	} else {
  759: 	    delete($classlist->{$student});
  760: 	}
  761:     }
  762:     my @sections = sort(keys(%sections));
  763:     return ($classlist,\@sections,\%fullnames);
  764: }
  765: 
  766: sub canmodify {
  767:     my ($sec)=@_;
  768:     if ($perm{'mgr'}) {
  769: 	if (!defined($perm{'mgr_section'})) {
  770: 	    # can modify whole class
  771: 	    return 1;
  772: 	} else {
  773: 	    if ($sec eq $perm{'mgr_section'}) {
  774: 		#can modify the requested section
  775: 		return 1;
  776: 	    } else {
  777: 		# can't modify the requested section
  778: 		return 0;
  779: 	    }
  780: 	}
  781:     }
  782:     #can't modify
  783:     return 0;
  784: }
  785: 
  786: sub canview {
  787:     my ($sec)=@_;
  788:     if ($perm{'vgr'}) {
  789: 	if (!defined($perm{'vgr_section'})) {
  790: 	    # can view whole class
  791: 	    return 1;
  792: 	} else {
  793: 	    if ($sec eq $perm{'vgr_section'}) {
  794: 		#can view the requested section
  795: 		return 1;
  796: 	    } else {
  797: 		# can't view the requested section
  798: 		return 0;
  799: 	    }
  800: 	}
  801:     }
  802:     #can't view
  803:     return 0;
  804: }
  805: 
  806: #--- Retrieve the grade status of a student for all the parts
  807: sub student_gradeStatus {
  808:     my ($symb,$udom,$uname,$partlist) = @_;
  809:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  810:     my %partstatus = ();
  811:     foreach (@$partlist) {
  812: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  813: 	$status              = 'nothing' if ($status eq '');
  814: 	$partstatus{$_}      = $status;
  815: 	my $subkey           = "resource.$_.submitted_by";
  816: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  817:     }
  818:     return %partstatus;
  819: }
  820: 
  821: # hidden form and javascript that calls the form
  822: # Use by verifyscript and viewgrades
  823: # Shows a student's view of problem and submission
  824: sub jscriptNform {
  825:     my ($symb) = @_;
  826:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  827:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  828: 	'    function viewOneStudent(user,domain) {'."\n".
  829: 	'	document.onestudent.student.value = user;'."\n".
  830: 	'	document.onestudent.userdom.value = domain;'."\n".
  831: 	'	document.onestudent.submit();'."\n".
  832: 	'    }'."\n".
  833: 	"\n");
  834:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  835: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  836: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  837: 	'<input type="hidden" name="command" value="submission" />'."\n".
  838: 	'<input type="hidden" name="student" value="" />'."\n".
  839: 	'<input type="hidden" name="userdom" value="" />'."\n".
  840: 	'</form>'."\n";
  841:     return $jscript;
  842: }
  843: 
  844: 
  845: 
  846: # Given the score (as a number [0-1] and the weight) what is the final
  847: # point value? This function will round to the nearest tenth, third,
  848: # or quarter if one of those is within the tolerance of .00001.
  849: sub compute_points {
  850:     my ($score, $weight) = @_;
  851:     
  852:     my $tolerance = .00001;
  853:     my $points = $score * $weight;
  854: 
  855:     # Check for nearness to 1/x.
  856:     my $check_for_nearness = sub {
  857:         my ($factor) = @_;
  858:         my $num = ($points * $factor) + $tolerance;
  859:         my $floored_num = floor($num);
  860:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  861:             return $floored_num / $factor;
  862:         }
  863:         return $points;
  864:     };
  865: 
  866:     $points = $check_for_nearness->(10);
  867:     $points = $check_for_nearness->(3);
  868:     $points = $check_for_nearness->(4);
  869:     
  870:     return $points;
  871: }
  872: 
  873: #------------------ End of general use routines --------------------
  874: 
  875: #
  876: # Find most similar essay
  877: #
  878: 
  879: sub most_similar {
  880:     my ($uname,$udom,$symb,$uessay)=@_;
  881: 
  882:     unless ($symb) { return ''; }
  883: 
  884:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  885: 
  886: # ignore spaces and punctuation
  887: 
  888:     $uessay=~s/\W+/ /gs;
  889: 
  890: # ignore empty submissions (occuring when only files are sent)
  891: 
  892:     unless ($uessay=~/\w+/s) { return ''; }
  893: 
  894: # these will be returned. Do not care if not at least 50 percent similar
  895:     my $limit=0.6;
  896:     my $sname='';
  897:     my $sdom='';
  898:     my $scrsid='';
  899:     my $sessay='';
  900: # go through all essays ...
  901:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  902: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  903: # ... except the same student
  904:         next if (($tname eq $uname) && ($tdom eq $udom));
  905: 	my $tessay=$old_essays{$symb}{$tkey};
  906: 	$tessay=~s/\W+/ /gs;
  907: # String similarity gives up if not even limit
  908: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  909: # Found one
  910: 	if ($tsimilar>$limit) {
  911: 	    $limit=$tsimilar;
  912: 	    $sname=$tname;
  913: 	    $sdom=$tdom;
  914: 	    $scrsid=$tcrsid;
  915: 	    $sessay=$old_essays{$symb}{$tkey};
  916: 	}
  917:     }
  918:     if ($limit>0.6) {
  919:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  920:     } else {
  921:        return ('','','','',0);
  922:     }
  923: }
  924: 
  925: #-------------------------------------------------------------------
  926: 
  927: #------------------------------------ Receipt Verification Routines
  928: #
  929: 
  930: sub initialverifyreceipt {
  931:    my ($request,$symb) = @_;
  932:    &commonJSfunctions($request);
  933:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  934:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  935:         '-<input type="text" name="receipt" size="4" />'.
  936:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  937:         '<input type="hidden" name="command" value="verify" />'.
  938:         "</form>\n";
  939: }
  940: 
  941: #--- Check whether a receipt number is valid.---
  942: sub verifyreceipt {
  943:     my ($request,$symb) = @_;
  944: 
  945:     my $courseid = $env{'request.course.id'};
  946:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  947: 	$env{'form.receipt'};
  948:     $receipt     =~ s/[^\-\d]//g;
  949: 
  950:     my $title =
  951: 	'<h3><span class="LC_info">'.
  952: 	&mt('Verifying Receipt Number [_1]',$receipt).
  953: 	'</span></h3>'."\n";
  954: 
  955:     my ($string,$contents,$matches) = ('','',0);
  956:     my (undef,undef,$fullname) = &getclasslist('all','0');
  957:     
  958:     my $receiptparts=0;
  959:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  960: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  961:     my $parts=['0'];
  962:     if ($receiptparts) {
  963:         my $res_error; 
  964:         ($parts)=&response_type($symb,\$res_error);
  965:         if ($res_error) {
  966:             return &navmap_errormsg();
  967:         } 
  968:     }
  969:     
  970:     my $header = 
  971: 	&Apache::loncommon::start_data_table().
  972: 	&Apache::loncommon::start_data_table_header_row().
  973: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  974: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  975: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  976:     if ($receiptparts) {
  977: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  978:     }
  979:     $header.=
  980: 	&Apache::loncommon::end_data_table_header_row();
  981: 
  982:     foreach (sort 
  983: 	     {
  984: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  985: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  986: 		 }
  987: 		 return $a cmp $b;
  988: 	     } (keys(%$fullname))) {
  989: 	my ($uname,$udom)=split(/\:/);
  990: 	foreach my $part (@$parts) {
  991: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  992: 		$contents.=
  993: 		    &Apache::loncommon::start_data_table_row().
  994: 		    '<td>&nbsp;'."\n".
  995: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  996: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  997: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  998: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  999: 		if ($receiptparts) {
 1000: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1001: 		}
 1002: 		$contents.= 
 1003: 		    &Apache::loncommon::end_data_table_row()."\n";
 1004: 		
 1005: 		$matches++;
 1006: 	    }
 1007: 	}
 1008:     }
 1009:     if ($matches == 0) {
 1010:         $string = $title
 1011:                  .'<p class="LC_warning">'
 1012:                  .&mt('No match found for the above receipt number.')
 1013:                  .'</p>';
 1014:     } else {
 1015: 	$string = &jscriptNform($symb).$title.
 1016: 	    '<p>'.
 1017: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1018: 	    '</p>'.
 1019: 	    $header.
 1020: 	    $contents.
 1021: 	    &Apache::loncommon::end_data_table()."\n";
 1022:     }
 1023:     return $string;
 1024: }
 1025: 
 1026: #--- This is called by a number of programs.
 1027: #--- Called from the Grading Menu - View/Grade an individual student
 1028: #--- Also called directly when one clicks on the subm button 
 1029: #    on the problem page.
 1030: sub listStudents {
 1031:     my ($request,$symb,$submitonly,$divforres) = @_;
 1032: 
 1033:     my $is_tool   = ($symb =~ /ext\.tool$/);
 1034:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1035:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1036:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1037:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1038:     unless ($submitonly) {
 1039:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1040:     }
 1041: 
 1042:     my $result='';
 1043:     my $res_error;
 1044:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1045: 
 1046:     my $table;
 1047:     if (ref($partlist) eq 'ARRAY') {
 1048:         if (scalar(@$partlist) > 1 ) {
 1049:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1050:         } elsif ($divforres) {
 1051:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1052:         } else {
 1053:             $table = '<br clear="all" />';
 1054:         }
 1055:     }
 1056: 
 1057:     my %js_lt = &Apache::lonlocal::texthash (
 1058: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1059: 		'single'   => 'Please select the student before clicking on the Next button.',
 1060: 	     );
 1061:     &js_escape(\%js_lt);
 1062:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1063:     function checkSelect(checkBox) {
 1064: 	var ctr=0;
 1065: 	var sense="";
 1066: 	if (checkBox.length > 1) {
 1067: 	    for (var i=0; i<checkBox.length; i++) {
 1068: 		if (checkBox[i].checked) {
 1069: 		    ctr++;
 1070: 		}
 1071: 	    }
 1072: 	    sense = '$js_lt{'multiple'}';
 1073: 	} else {
 1074: 	    if (checkBox.checked) {
 1075: 		ctr = 1;
 1076: 	    }
 1077: 	    sense = '$js_lt{'single'}';
 1078: 	}
 1079: 	if (ctr == 0) {
 1080: 	    alert(sense);
 1081: 	    return false;
 1082: 	}
 1083: 	document.gradesub.submit();
 1084:     }
 1085: 
 1086:     function reLoadList(formname) {
 1087: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1088: 	formname.command.value = 'submission';
 1089: 	formname.submit();
 1090:     }
 1091: LISTJAVASCRIPT
 1092: 
 1093:     &commonJSfunctions($request);
 1094:     $request->print($result);
 1095: 
 1096:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1097: 	"\n".$table;
 1098: 
 1099:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1100:     unless ($is_tool) {
 1101:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1102:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1103:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1104:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1105:                       .&Apache::lonhtmlcommon::row_closure();
 1106:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1107:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1108:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1109:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1110:                       .&Apache::lonhtmlcommon::row_closure();
 1111:     }
 1112: 
 1113:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1114:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1115:     $env{'form.Status'} = $saveStatus;
 1116:     my %optiontext;
 1117:     if ($is_tool) {
 1118:         %optiontext = &Apache::lonlocal::texthash (
 1119:                           lastonly => 'last transaction',
 1120:                           last     => 'last transaction with details',
 1121:                           datesub  => 'all transactions',
 1122:                           all      => 'all transactions with details',
 1123:                       );
 1124:     } else {
 1125:         %optiontext = &Apache::lonlocal::texthash (
 1126:                           lastonly => 'last submission',
 1127:                           last     => 'last submission with details',
 1128:                           datesub  => 'all submissions',
 1129:                           all      => 'all submissions with details',
 1130:                       );
 1131:     }
 1132:     my $submission_options =
 1133:         '<span class="LC_nobreak">'.
 1134:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1135:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1136:         '<span class="LC_nobreak">'.
 1137:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1138:         $optiontext{'last'}.' </label></span>'."\n".
 1139:         '<span class="LC_nobreak">'.
 1140:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1141:         $optiontext{'datesub'}.'</label></span>'."\n".
 1142:         '<span class="LC_nobreak">'.
 1143:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1144:         $optiontext{'all'}.'</label></span>';
 1145:     my $viewtitle;
 1146:     if ($is_tool) {
 1147:         $viewtitle = &mt('View Transactions');
 1148:     } else {
 1149:         $viewtitle = &mt('View Submissions');
 1150:     }
 1151:     my ($compmsg,$nocompmsg);
 1152:     $nocompmsg = ' checked="checked"';
 1153:     if ($numessay) {
 1154:         $compmsg = $nocompmsg;
 1155:         $nocompmsg = '';
 1156:     }
 1157:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1158:                   .$submission_options
 1159:                   .&Apache::lonhtmlcommon::row_closure()
 1160:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1161:                   .'<span class="LC_nobreak">'
 1162:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1163:                   .&mt('No').('&nbsp;'x2).'</label>'
 1164:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1165:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1166:                   .&Apache::lonhtmlcommon::row_closure();
 1167: 
 1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1169:                   .'<select name="increment">'
 1170:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1171:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1172:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1173:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1174:                   .'</select>';
 1175:     $gradeTable .= 
 1176:         &build_section_inputs().
 1177: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1178: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1179: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1180:     if (exists($env{'form.Status'})) {
 1181: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1182:     } else {
 1183:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1184:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1185:                       .&Apache::lonhtmlcommon::StatusOptions(
 1186:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1187:     }
 1188:     if ($numessay) {
 1189:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1190:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1191:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1192:     }
 1193:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1194:                   .&Apache::lonhtmlcommon::end_pick_box();
 1195:     my $regrademsg;
 1196:     if ($is_tool) {
 1197:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1198:     } else {
 1199:         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1200:     }
 1201:     $gradeTable .= '<p>'
 1202:                   .$regrademsg."\n"
 1203:                   .'<input type="hidden" name="command" value="processGroup" />'
 1204:                   .'</p>';
 1205: 
 1206: # checkall buttons
 1207:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1208:     $gradeTable.='<input type="button" '."\n".
 1209:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1210:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1211:     $gradeTable.=&check_buttons();
 1212:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1213:     $gradeTable.= &Apache::loncommon::start_data_table().
 1214: 	&Apache::loncommon::start_data_table_header_row();
 1215:     my $loop = 0;
 1216:     while ($loop < 2) {
 1217: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1218: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1219: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1220: 	    foreach my $part (sort(@$partlist)) {
 1221: 		my $display_part=
 1222: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1223: 		$gradeTable.=
 1224: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1225: 	    }
 1226: 	} elsif ($submitonly eq 'queued') {
 1227: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1228: 	}
 1229: 	$loop++;
 1230: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1231:     }
 1232:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1233: 
 1234:     my $ctr = 0;
 1235:     foreach my $student (sort 
 1236: 			 {
 1237: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1238: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1239: 			     }
 1240: 			     return $a cmp $b;
 1241: 			 }
 1242: 			 (keys(%$fullname))) {
 1243: 	my ($uname,$udom) = split(/:/,$student);
 1244: 
 1245: 	my %status = ();
 1246: 
 1247: 	if ($submitonly eq 'queued') {
 1248: 	    my %queue_status = 
 1249: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1250: 							$udom,$uname);
 1251: 	    next if (!defined($queue_status{'gradingqueue'}));
 1252: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1253: 	}
 1254: 
 1255: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1256: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1257: 	    my $submitted = 0;
 1258: 	    my $graded = 0;
 1259: 	    my $incorrect = 0;
 1260: 	    foreach (keys(%status)) {
 1261: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1262: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1263: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1264: 		
 1265: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1266: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1267: 		    $submitted = 0;
 1268: 		    my ($part)=split(/\./,$partid);
 1269: 		    $gradeTable.='<input type="hidden" name="'.
 1270: 			$student.':'.$part.':submitted_by" value="'.
 1271: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1272: 		}
 1273: 	    }
 1274: 	    
 1275: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1276: 				     $submitonly eq 'incorrect' ||
 1277: 				     $submitonly eq 'graded'));
 1278: 	    next if (!$graded && ($submitonly eq 'graded'));
 1279: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1280: 	}
 1281: 
 1282: 	$ctr++;
 1283: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1284:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1285: 	if ( $perm{'vgr'} eq 'F' ) {
 1286: 	    if ($ctr%2 ==1) {
 1287: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1288: 	    }
 1289: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1290:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1291:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1292: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1293: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1294: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1295: 
 1296: 	    if ($submitonly ne 'all') {
 1297: 		foreach (sort(keys(%status))) {
 1298: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1299: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1300: 		}
 1301: 	    }
 1302: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1303: 	    if ($ctr%2 ==0) {
 1304: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1305: 	    }
 1306: 	}
 1307:     }
 1308:     if ($ctr%2 ==1) {
 1309: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1310: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1311: 		foreach (@$partlist) {
 1312: 		    $gradeTable.='<td>&nbsp;</td>';
 1313: 		}
 1314: 	    } elsif ($submitonly eq 'queued') {
 1315: 		$gradeTable.='<td>&nbsp;</td>';
 1316: 	    }
 1317: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1318:     }
 1319: 
 1320:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1321:         '<input type="button" '.
 1322:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1323:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1324:     if ($ctr == 0) {
 1325: 	my $num_students=(scalar(keys(%$fullname)));
 1326: 	if ($num_students eq 0) {
 1327: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1328: 	} else {
 1329: 	    my $submissions='submissions';
 1330: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1331: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1332: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1333: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1334: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1335: 		    $num_students).
 1336: 		'</span><br />';
 1337: 	}
 1338:     } elsif ($ctr == 1) {
 1339: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1340:     }
 1341:     $request->print($gradeTable);
 1342:     return '';
 1343: }
 1344: 
 1345: #---- Called from the listStudents routine
 1346: 
 1347: sub check_script {
 1348:     my ($form,$type) = @_;
 1349:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1350:     function checkall() {
 1351:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1352:             ele = document.forms.'.$form.'.elements[i];
 1353:             if (ele.name == "'.$type.'") {
 1354:             document.forms.'.$form.'.elements[i].checked=true;
 1355:                                        }
 1356:         }
 1357:     }
 1358: 
 1359:     function checksec() {
 1360:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1361:             ele = document.forms.'.$form.'.elements[i];
 1362:            string = document.forms.'.$form.'.chksec.value;
 1363:            if
 1364:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1365:               document.forms.'.$form.'.elements[i].checked=true;
 1366:             }
 1367:         }
 1368:     }
 1369: 
 1370: 
 1371:     function uncheckall() {
 1372:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1373:             ele = document.forms.'.$form.'.elements[i];
 1374:             if (ele.name == "'.$type.'") {
 1375:             document.forms.'.$form.'.elements[i].checked=false;
 1376:                                        }
 1377:         }
 1378:     }
 1379: 
 1380: '."\n");
 1381:     return $chkallscript;
 1382: }
 1383: 
 1384: sub check_buttons {
 1385:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1386:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1387:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1388:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1389:     return $buttons;
 1390: }
 1391: 
 1392: #     Displays the submissions for one student or a group of students
 1393: sub processGroup {
 1394:     my ($request,$symb) = @_;
 1395:     my $ctr        = 0;
 1396:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1397:     my $total      = scalar(@stuchecked)-1;
 1398: 
 1399:     foreach my $student (@stuchecked) {
 1400: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1401: 	$env{'form.student'}        = $uname;
 1402: 	$env{'form.userdom'}        = $udom;
 1403: 	$env{'form.fullname'}       = $fullname;
 1404: 	&submission($request,$ctr,$total,$symb);
 1405: 	$ctr++;
 1406:     }
 1407:     return '';
 1408: }
 1409: 
 1410: #------------------------------------------------------------------------------------
 1411: #
 1412: #-------------------------- Next few routines handles grading by student, essentially
 1413: #                           handles essay response type problem/part
 1414: #
 1415: #--- Javascript to handle the submission page functionality ---
 1416: sub sub_page_js {
 1417:     my $request = shift;
 1418:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1419:     &js_escape(\$alertmsg);
 1420:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1421:     function updateRadio(formname,id,weight) {
 1422: 	var gradeBox = formname["GD_BOX"+id];
 1423: 	var radioButton = formname["RADVAL"+id];
 1424: 	var oldpts = formname["oldpts"+id].value;
 1425: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1426: 	gradeBox.value = pts;
 1427: 	var resetbox = false;
 1428: 	if (isNaN(pts) || pts < 0) {
 1429: 	    alert("$alertmsg"+pts);
 1430: 	    for (var i=0; i<radioButton.length; i++) {
 1431: 		if (radioButton[i].checked) {
 1432: 		    gradeBox.value = i;
 1433: 		    resetbox = true;
 1434: 		}
 1435: 	    }
 1436: 	    if (!resetbox) {
 1437: 		formtextbox.value = "";
 1438: 	    }
 1439: 	    return;
 1440: 	}
 1441: 
 1442: 	if (pts > weight) {
 1443: 	    var resp = confirm("You entered a value ("+pts+
 1444: 			       ") greater than the weight for the part. Accept?");
 1445: 	    if (resp == false) {
 1446: 		gradeBox.value = oldpts;
 1447: 		return;
 1448: 	    }
 1449: 	}
 1450: 
 1451: 	for (var i=0; i<radioButton.length; i++) {
 1452: 	    radioButton[i].checked=false;
 1453: 	    if (pts == i && pts != "") {
 1454: 		radioButton[i].checked=true;
 1455: 	    }
 1456: 	}
 1457: 	updateSelect(formname,id);
 1458: 	formname["stores"+id].value = "0";
 1459:     }
 1460: 
 1461:     function writeBox(formname,id,pts) {
 1462: 	var gradeBox = formname["GD_BOX"+id];
 1463: 	if (checkSolved(formname,id) == 'update') {
 1464: 	    gradeBox.value = pts;
 1465: 	} else {
 1466: 	    var oldpts = formname["oldpts"+id].value;
 1467: 	    gradeBox.value = oldpts;
 1468: 	    var radioButton = formname["RADVAL"+id];
 1469: 	    for (var i=0; i<radioButton.length; i++) {
 1470: 		radioButton[i].checked=false;
 1471: 		if (i == oldpts) {
 1472: 		    radioButton[i].checked=true;
 1473: 		}
 1474: 	    }
 1475: 	}
 1476: 	formname["stores"+id].value = "0";
 1477: 	updateSelect(formname,id);
 1478: 	return;
 1479:     }
 1480: 
 1481:     function clearRadBox(formname,id) {
 1482: 	if (checkSolved(formname,id) == 'noupdate') {
 1483: 	    updateSelect(formname,id);
 1484: 	    return;
 1485: 	}
 1486: 	gradeSelect = formname["GD_SEL"+id];
 1487: 	for (var i=0; i<gradeSelect.length; i++) {
 1488: 	    if (gradeSelect[i].selected) {
 1489: 		var selectx=i;
 1490: 	    }
 1491: 	}
 1492: 	var stores = formname["stores"+id];
 1493: 	if (selectx == stores.value) { return };
 1494: 	var gradeBox = formname["GD_BOX"+id];
 1495: 	gradeBox.value = "";
 1496: 	var radioButton = formname["RADVAL"+id];
 1497: 	for (var i=0; i<radioButton.length; i++) {
 1498: 	    radioButton[i].checked=false;
 1499: 	}
 1500: 	stores.value = selectx;
 1501:     }
 1502: 
 1503:     function checkSolved(formname,id) {
 1504: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1505: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1506: 	    if (!reply) {return "noupdate";}
 1507: 	    formname.overRideScore.value = 'yes';
 1508: 	}
 1509: 	return "update";
 1510:     }
 1511: 
 1512:     function updateSelect(formname,id) {
 1513: 	formname["GD_SEL"+id][0].selected = true;
 1514: 	return;
 1515:     }
 1516: 
 1517: //=========== Check that a point is assigned for all the parts  ============
 1518:     function checksubmit(formname,val,total,parttot) {
 1519: 	formname.gradeOpt.value = val;
 1520: 	if (val == "Save & Next") {
 1521: 	    for (i=0;i<=total;i++) {
 1522: 		for (j=0;j<parttot;j++) {
 1523: 		    var partid = formname["partid"+i+"_"+j].value;
 1524: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1525: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1526: 			if (points == "") {
 1527: 			    var name = formname["name"+i].value;
 1528: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1529: 			    var resp = confirm("You did not assign a score for "+studentID+
 1530: 					       ", part "+partid+". Continue?");
 1531: 			    if (resp == false) {
 1532: 				formname["GD_BOX"+i+"_"+partid].focus();
 1533: 				return false;
 1534: 			    }
 1535: 			}
 1536: 		    }
 1537: 		}
 1538: 	    }
 1539: 	}
 1540: 	formname.submit();
 1541:     }
 1542: 
 1543: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1544:     function checkSubmitPage(formname,total) {
 1545: 	noscore = new Array(100);
 1546: 	var ptr = 0;
 1547: 	for (i=1;i<total;i++) {
 1548: 	    var partid = formname["q_"+i].value;
 1549: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1550: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1551: 		var status = formname["solved"+i+"_"+partid].value;
 1552: 		if (points == "" && status != "correct_by_student") {
 1553: 		    noscore[ptr] = i;
 1554: 		    ptr++;
 1555: 		}
 1556: 	    }
 1557: 	}
 1558: 	if (ptr != 0) {
 1559: 	    var sense = ptr == 1 ? ": " : "s: ";
 1560: 	    var prolist = "";
 1561: 	    if (ptr == 1) {
 1562: 		prolist = noscore[0];
 1563: 	    } else {
 1564: 		var i = 0;
 1565: 		while (i < ptr-1) {
 1566: 		    prolist += noscore[i]+", ";
 1567: 		    i++;
 1568: 		}
 1569: 		prolist += "and "+noscore[i];
 1570: 	    }
 1571: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1572: 	    if (resp == false) {
 1573: 		return false;
 1574: 	    }
 1575: 	}
 1576: 
 1577: 	formname.submit();
 1578:     }
 1579: SUBJAVASCRIPT
 1580: }
 1581: 
 1582: #--- javascript for grading message center
 1583: sub sub_grademessage_js {
 1584:     my $request = shift;
 1585:     my $iconpath = $request->dir_config('lonIconsURL');
 1586:     &commonJSfunctions($request);
 1587: 
 1588:     my $inner_js_msg_central= (<<INNERJS);
 1589: <script type="text/javascript">
 1590:     function checkInput() {
 1591:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1592:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1593:       var usrctr = document.msgcenter.usrctr.value;
 1594:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1595:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1596: 
 1597:       var msgchk = "";
 1598:       if (document.msgcenter.subchk.checked) {
 1599:          msgchk = "msgsub,";
 1600:       }
 1601:       var includemsg = 0;
 1602:       for (var i=1; i<=nmsg; i++) {
 1603:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1604:           var frmmsg = document.msgcenter["msg"+i];
 1605:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1606:           var showflg = opener.document.SCORE["shownOnce"+i];
 1607:           showflg.value = "1";
 1608:           var chkbox = document.msgcenter["msgn"+i];
 1609:           if (chkbox.checked) {
 1610:              msgchk += "savemsg"+i+",";
 1611:              includemsg = 1;
 1612:           }
 1613:       }
 1614:       if (document.msgcenter.newmsgchk.checked) {
 1615:          msgchk += "newmsg"+usrctr;
 1616:          includemsg = 1;
 1617:       }
 1618:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1619:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1620:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1621:       includemsg.value = msgchk;
 1622: 
 1623:       self.close()
 1624: 
 1625:     }
 1626: </script>
 1627: INNERJS
 1628: 
 1629:     my $start_page_msg_central =
 1630:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1631: 				       {'js_ready'  => 1,
 1632: 					'only_body' => 1,
 1633: 					'bgcolor'   =>'#FFFFFF',});
 1634:     my $end_page_msg_central =
 1635: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1636: 
 1637:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1638:     $docopen=~s/^document\.//;
 1639: 
 1640:     my %html_js_lt = &Apache::lonlocal::texthash(
 1641:                 comp => 'Compose Message for: ',
 1642:                 incl => 'Include',
 1643:                 type => 'Type',
 1644:                 subj => 'Subject',
 1645:                 mesa => 'Message',
 1646:                 new  => 'New',
 1647:                 save => 'Save',
 1648:                 canc => 'Cancel',
 1649:              );
 1650:     &html_escape(\%html_js_lt);
 1651:     &js_escape(\%html_js_lt);
 1652:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1653: 
 1654: //===================== Script to view submitted by ==================
 1655:   function viewSubmitter(submitter) {
 1656:     document.SCORE.refresh.value = "on";
 1657:     document.SCORE.NCT.value = "1";
 1658:     document.SCORE.unamedom0.value = submitter;
 1659:     document.SCORE.submit();
 1660:     return;
 1661:   }
 1662: 
 1663: //====================== Script for composing message ==============
 1664:    // preload images
 1665:    img1 = new Image();
 1666:    img1.src = "$iconpath/mailbkgrd.gif";
 1667:    img2 = new Image();
 1668:    img2.src = "$iconpath/mailto.gif";
 1669: 
 1670:   function msgCenter(msgform,usrctr,fullname) {
 1671:     var Nmsg  = msgform.savemsgN.value;
 1672:     savedMsgHeader(Nmsg,usrctr,fullname);
 1673:     var subject = msgform.msgsub.value;
 1674:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1675:     re = /msgsub/;
 1676:     var shwsel = "";
 1677:     if (re.test(msgchk)) { shwsel = "checked" }
 1678:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1679:     displaySubject(checkEntities(subject),shwsel);
 1680:     for (var i=1; i<=Nmsg; i++) {
 1681: 	var testmsg = "savemsg"+i+",";
 1682: 	re = new RegExp(testmsg,"g");
 1683: 	shwsel = "";
 1684: 	if (re.test(msgchk)) { shwsel = "checked" }
 1685: 	var message = document.SCORE["savemsg"+i].value;
 1686: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1687: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1688: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1689:     }
 1690:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1691:     shwsel = "";
 1692:     re = /newmsg/;
 1693:     if (re.test(msgchk)) { shwsel = "checked" }
 1694:     newMsg(newmsg,shwsel);
 1695:     msgTail(); 
 1696:     return;
 1697:   }
 1698: 
 1699:   function checkEntities(strx) {
 1700:     if (strx.length == 0) return strx;
 1701:     var orgStr = ["&", "<", ">", '"']; 
 1702:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1703:     var counter = 0;
 1704:     while (counter < 4) {
 1705: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1706: 	counter++;
 1707:     }
 1708:     return strx;
 1709:   }
 1710: 
 1711:   function strReplace(strx, orgStr, newStr) {
 1712:     return strx.split(orgStr).join(newStr);
 1713:   }
 1714: 
 1715:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1716:     var height = 70*Nmsg+250;
 1717:     if (height > 600) {
 1718: 	height = 600;
 1719:     }
 1720:     var xpos = (screen.width-600)/2;
 1721:     xpos = (xpos < 0) ? '0' : xpos;
 1722:     var ypos = (screen.height-height)/2-30;
 1723:     ypos = (ypos < 0) ? '0' : ypos;
 1724: 
 1725:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1726:     pWin.focus();
 1727:     pDoc = pWin.document;
 1728:     pDoc.$docopen;
 1729:     pDoc.write('$start_page_msg_central');
 1730: 
 1731:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1732:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1733:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1734: 
 1735:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1736:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1737: }
 1738:     function displaySubject(msg,shwsel) {
 1739:     pDoc = pWin.document;
 1740:     pDoc.write("<tr>");
 1741:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1742:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1743:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1744: }
 1745: 
 1746:   function displaySavedMsg(ctr,msg,shwsel) {
 1747:     pDoc = pWin.document;
 1748:     pDoc.write("<tr>");
 1749:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1750:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1751:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1752: }
 1753: 
 1754:   function newMsg(newmsg,shwsel) {
 1755:     pDoc = pWin.document;
 1756:     pDoc.write("<tr>");
 1757:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1758:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1759:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1760: }
 1761: 
 1762:   function msgTail() {
 1763:     pDoc = pWin.document;
 1764:     //pDoc.write("<\\/table>");
 1765:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1766:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1767:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1768:     pDoc.write("<\\/form>");
 1769:     pDoc.write('$end_page_msg_central');
 1770:     pDoc.close();
 1771: }
 1772: 
 1773: SUBJAVASCRIPT
 1774: }
 1775: 
 1776: #--- javascript for essay type problem --
 1777: sub sub_page_kw_js {
 1778:     my $request = shift;
 1779: 
 1780:     unless ($env{'form.compmsg'}) {
 1781:         &commonJSfunctions($request);
 1782:     }
 1783: 
 1784:     my $inner_js_highlight_central= (<<INNERJS);
 1785: <script type="text/javascript">
 1786:     function updateChoice(flag) {
 1787:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1788:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1789:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1790:       opener.document.SCORE.refresh.value = "on";
 1791:       if (opener.document.SCORE.keywords.value!=""){
 1792:          opener.document.SCORE.submit();
 1793:       }
 1794:       self.close()
 1795:     }
 1796: </script>
 1797: INNERJS
 1798: 
 1799:     my $start_page_highlight_central =
 1800:         &Apache::loncommon::start_page('Highlight Central',
 1801:                                        $inner_js_highlight_central,
 1802:                                        {'js_ready'  => 1,
 1803:                                         'only_body' => 1,
 1804:                                         'bgcolor'   =>'#FFFFFF',});
 1805:     my $end_page_highlight_central =
 1806:         &Apache::loncommon::end_page({'js_ready' => 1});
 1807: 
 1808:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1809:     $docopen=~s/^document\.//;
 1810: 
 1811:     my %js_lt = &Apache::lonlocal::texthash(
 1812:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1813:                 plse => 'Please select a word or group of words from document and then click this link.',
 1814:                 adds => 'Add selection to keyword list? Edit if desired.',
 1815:                 col1 => 'red',
 1816:                 col2 => 'green',
 1817:                 col3 => 'blue',
 1818:                 siz1 => 'normal',
 1819:                 siz2 => '+1',
 1820:                 siz3 => '+2',
 1821:                 sty1 => 'normal',
 1822:                 sty2 => 'italic',
 1823:                 sty3 => 'bold',
 1824:              );
 1825:     my %html_js_lt = &Apache::lonlocal::texthash(
 1826:                 save => 'Save',
 1827:                 canc => 'Cancel',
 1828:                 kehi => 'Keyword Highlight Options',
 1829:                 txtc => 'Text Color',
 1830:                 font => 'Font Size',
 1831:                 fnst => 'Font Style',
 1832:              );
 1833:     &js_escape(\%js_lt);
 1834:     &html_escape(\%html_js_lt);
 1835:     &js_escape(\%html_js_lt);
 1836:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1837: 
 1838: //===================== Show list of keywords ====================
 1839:   function keywords(formname) {
 1840:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1841:     if (nret==null) return;
 1842:     formname.keywords.value = nret;
 1843: 
 1844:     if (formname.keywords.value != "") {
 1845:         formname.refresh.value = "on";
 1846:         formname.submit();
 1847:     }
 1848:     return;
 1849:   }
 1850: 
 1851: //===================== Script to add keyword(s) ==================
 1852:   function getSel() {
 1853:     if (document.getSelection) txt = document.getSelection();
 1854:     else if (document.selection) txt = document.selection.createRange().text;
 1855:     else return;
 1856:     if (typeof(txt) != 'string') {
 1857:         txt = String(txt);
 1858:     }
 1859:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1860:     if (cleantxt=="") {
 1861:         alert("$js_lt{'plse'}");
 1862:         return;
 1863:     }
 1864:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1865:     if (nret==null) return;
 1866:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1867:     if (document.SCORE.keywords.value != "") {
 1868:         document.SCORE.refresh.value = "on";
 1869:         document.SCORE.submit();
 1870:     }
 1871:     return;
 1872:   }
 1873: 
 1874: //====================== Script for keyword highlight options ==============
 1875:   function kwhighlight() {
 1876:     var kwclr    = document.SCORE.kwclr.value;
 1877:     var kwsize   = document.SCORE.kwsize.value;
 1878:     var kwstyle  = document.SCORE.kwstyle.value;
 1879:     var redsel = "";
 1880:     var grnsel = "";
 1881:     var blusel = "";
 1882:     var txtcol1 = "$js_lt{'col1'}";
 1883:     var txtcol2 = "$js_lt{'col2'}";
 1884:     var txtcol3 = "$js_lt{'col3'}";
 1885:     var txtsiz1 = "$js_lt{'siz1'}";
 1886:     var txtsiz2 = "$js_lt{'siz2'}";
 1887:     var txtsiz3 = "$js_lt{'siz3'}";
 1888:     var txtsty1 = "$js_lt{'sty1'}";
 1889:     var txtsty2 = "$js_lt{'sty2'}";
 1890:     var txtsty3 = "$js_lt{'sty3'}";
 1891:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1892:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1893:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1894:     var sznsel = "";
 1895:     var sz1sel = "";
 1896:     var sz2sel = "";
 1897:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1898:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1899:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1900:     var synsel = "";
 1901:     var syisel = "";
 1902:     var sybsel = "";
 1903:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1904:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1905:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1906:     highlightCentral();
 1907:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1908:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1909:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1910:     highlightend();
 1911:     return;
 1912:   }
 1913: 
 1914:   function highlightCentral() {
 1915: //    if (window.hwdWin) window.hwdWin.close();
 1916:     var xpos = (screen.width-400)/2;
 1917:     xpos = (xpos < 0) ? '0' : xpos;
 1918:     var ypos = (screen.height-330)/2-30;
 1919:     ypos = (ypos < 0) ? '0' : ypos;
 1920: 
 1921:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1922:     hwdWin.focus();
 1923:     var hDoc = hwdWin.document;
 1924:     hDoc.$docopen;
 1925:     hDoc.write('$start_page_highlight_central');
 1926:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1927:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1928: 
 1929:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1930:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1931:   }
 1932: 
 1933:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1934:     var hDoc = hwdWin.document;
 1935:     hDoc.write("<tr>");
 1936:     hDoc.write("<td align=\\"left\\">");
 1937:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1938:     hDoc.write("<td align=\\"left\\">");
 1939:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1940:     hDoc.write("<td align=\\"left\\">");
 1941:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1942:     hDoc.write("<\\/tr>");
 1943:   }
 1944: 
 1945:   function highlightend() { 
 1946:     var hDoc = hwdWin.document;
 1947:     hDoc.write("<\\/table><br \\/>");
 1948:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1949:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1950:     hDoc.write("<\\/form>");
 1951:     hDoc.write('$end_page_highlight_central');
 1952:     hDoc.close();
 1953:   }
 1954: 
 1955: SUBJAVASCRIPT
 1956: }
 1957: 
 1958: sub get_increment {
 1959:     my $increment = $env{'form.increment'};
 1960:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1961:         $increment != .1) {
 1962:         $increment = 1;
 1963:     }
 1964:     return $increment;
 1965: }
 1966: 
 1967: sub gradeBox_start {
 1968:     return (
 1969:         &Apache::loncommon::start_data_table()
 1970:        .&Apache::loncommon::start_data_table_header_row()
 1971:        .'<th>'.&mt('Part').'</th>'
 1972:        .'<th>'.&mt('Points').'</th>'
 1973:        .'<th>&nbsp;</th>'
 1974:        .'<th>'.&mt('Assign Grade').'</th>'
 1975:        .'<th>'.&mt('Weight').'</th>'
 1976:        .'<th>'.&mt('Grade Status').'</th>'
 1977:        .&Apache::loncommon::end_data_table_header_row()
 1978:     );
 1979: }
 1980: 
 1981: sub gradeBox_end {
 1982:     return (
 1983:         &Apache::loncommon::end_data_table()
 1984:     );
 1985: }
 1986: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1987: sub gradeBox {
 1988:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1989:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1990: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1991:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1992:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1993:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1994:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1995:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1996: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1997:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1998:     my $display_part= &get_display_part($partid,$symb);
 1999:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2000: 				       [$partid]);
 2001:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2002:     if ($last_resets{$partid}) {
 2003:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2004:     }
 2005:     my $result=&Apache::loncommon::start_data_table_row();
 2006:     my $ctr = 0;
 2007:     my $thisweight = 0;
 2008:     my $increment = &get_increment();
 2009: 
 2010:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2011:     while ($thisweight<=$wgt) {
 2012: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2013:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2014: 	    $thisweight.')" value="'.$thisweight.'" '.
 2015: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2016: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2017:         $thisweight += $increment;
 2018: 	$ctr++;
 2019:     }
 2020:     $radio.='</tr></table>';
 2021: 
 2022:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2023: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2024: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2025: 	$wgt.')" /></td>'."\n";
 2026:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2027: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2028: 	' </td>'."\n";
 2029:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2030: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2031:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2032: 	$line.='<option></option>'.
 2033: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2034:     } else {
 2035: 	$line.='<option selected="selected"></option>'.
 2036: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2037:     }
 2038:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2039: 
 2040: 
 2041:     $result .= 
 2042: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2043:     $result.=&Apache::loncommon::end_data_table_row();
 2044:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2045:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2046: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2047: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2048: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2049:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2050:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2051:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2052:         $aggtries.'" />'."\n";
 2053:     my $res_error;
 2054:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2055:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2056:     if ($res_error) {
 2057:         return &navmap_errormsg();
 2058:     }
 2059:     return $result;
 2060: }
 2061: 
 2062: sub handback_box {
 2063:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2064:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2065:     return unless ($numessay);
 2066:     my (@respids);
 2067:     my @part_response_id = &flatten_responseType($responseType);
 2068:     foreach my $part_response_id (@part_response_id) {
 2069:     	my ($part,$resp) = @{ $part_response_id };
 2070:         if ($part eq $partid) {
 2071:             push(@respids,$resp);
 2072:         }
 2073:     }
 2074:     my $result;
 2075:     foreach my $respid (@respids) {
 2076: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2077: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2078: 	next if (!@$files);
 2079: 	my $file_counter = 0;
 2080: 	foreach my $file (@$files) {
 2081: 	    if ($file =~ /\/portfolio\//) {
 2082:                 $file_counter++;
 2083:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2084:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2085:     	        $file_disp = "$name.$ext";
 2086:     	        $file = $file_path.$file_disp;
 2087:     	        $result.=&mt('Return commented version of [_1] to student.',
 2088:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2089:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2090:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2091: 	    }
 2092: 	}
 2093:         if ($file_counter) {
 2094:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2095:                        '<span class="LC_info">'.
 2096:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2097:         }
 2098:     }
 2099:     return $result;    
 2100: }
 2101: 
 2102: sub show_problem {
 2103:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2104:     my $rendered;
 2105:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2106:     &Apache::lonxml::remember_problem_counter();
 2107:     if ($mode eq 'both' or $mode eq 'text') {
 2108: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2109: 						       $env{'request.course.id'},
 2110: 						       undef,\%form);
 2111:     }
 2112:     if ($removeform) {
 2113: 	$rendered=~s|<form(.*?)>||g;
 2114: 	$rendered=~s|</form>||g;
 2115: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2116:     }
 2117:     my $companswer;
 2118:     if ($mode eq 'both' or $mode eq 'answer') {
 2119: 	&Apache::lonxml::restore_problem_counter();
 2120: 	$companswer=
 2121: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2122: 						    $env{'request.course.id'},
 2123: 						    %form);
 2124:     }
 2125:     if ($removeform) {
 2126: 	$companswer=~s|<form(.*?)>||g;
 2127: 	$companswer=~s|</form>||g;
 2128: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2129:     }
 2130:     my $renderheading = &mt('View of the problem');
 2131:     my $answerheading = &mt('Correct answer');
 2132:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2133:         my $stu_fullname = $env{'form.fullname'};
 2134:         if ($stu_fullname eq '') {
 2135:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2136:         }
 2137:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2138:         if ($forwhom ne '') {
 2139:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2140:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2141:         }
 2142:     }
 2143:     $rendered=
 2144:         '<div class="LC_Box">'
 2145:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2146:        .$rendered
 2147:        .'</div>';
 2148:     $companswer=
 2149:         '<div class="LC_Box">'
 2150:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2151:        .$companswer
 2152:        .'</div>';
 2153:     my $result;
 2154:     if ($mode eq 'both') {
 2155:         $result=$rendered.$companswer;
 2156:     } elsif ($mode eq 'text') {
 2157:         $result=$rendered;
 2158:     } elsif ($mode eq 'answer') {
 2159:         $result=$companswer;
 2160:     }
 2161:     return $result;
 2162: }
 2163: 
 2164: sub files_exist {
 2165:     my ($r, $symb) = @_;
 2166:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2167:     foreach my $student (@students) {
 2168:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2169:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2170: 					      $udom,$uname);
 2171:         my ($string,$timestamp)= &get_last_submission(\%record);
 2172:         foreach my $submission (@$string) {
 2173:             my ($partid,$respid) =
 2174: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2175:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2176: 					   \%record);
 2177:             return 1 if (@$files);
 2178:         }
 2179:     }
 2180:     return 0;
 2181: }
 2182: 
 2183: sub download_all_link {
 2184:     my ($r,$symb) = @_;
 2185:     unless (&files_exist($r, $symb)) {
 2186:         $r->print(&mt('There are currently no submitted documents.'));
 2187:         return;
 2188:     }
 2189:     my $all_students = 
 2190: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2191: 
 2192:     my $parts =
 2193: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2194: 
 2195:     my $identifier = &Apache::loncommon::get_cgi_id();
 2196:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2197:                              'cgi.'.$identifier.'.symb' => $symb,
 2198:                              'cgi.'.$identifier.'.parts' => $parts,});
 2199:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2200: 	      &mt('Download All Submitted Documents').'</a>');
 2201:     return;
 2202: }
 2203: 
 2204: sub submit_download_link {
 2205:     my ($request,$symb) = @_;
 2206:     if (!$symb) { return ''; }
 2207:     my $res_error;
 2208:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2209:         &response_type($symb,\$res_error);
 2210:     if ($res_error) {
 2211:         $request->print(&mt('An error occurred retrieving response types'));
 2212:         return;
 2213:     }
 2214:     unless ($numessay) {
 2215:         $request->print(&mt('No essayresponse items found'));
 2216:         return;
 2217:     }
 2218:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2219:     if (@chosenparts) {
 2220:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2221:                                           undef,undef,1));
 2222:     }
 2223:     if ($numessay) {
 2224:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2225:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2226:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2227:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2228:         if (ref($fullname) eq 'HASH') {
 2229:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2230:             if (@students) {
 2231:                 @{$env{'form.stuinfo'}} = @students;
 2232:                 if ($numdropbox) {
 2233:                     &download_all_link($request,$symb);
 2234:                 } else {
 2235:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2236:                 }
 2237: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2238: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2239:             } else {
 2240:                 $request->print(&mt('No students match the criteria you selected'));
 2241:             }
 2242:         } else {
 2243:             $request->print(&mt('Could not retrieve student information'));
 2244:         }
 2245:     } else {
 2246:         $request->print(&mt('No essayresponse items found'));
 2247:     }
 2248:     return;
 2249: }
 2250: 
 2251: sub build_section_inputs {
 2252:     my $section_inputs;
 2253:     if ($env{'form.section'} eq '') {
 2254:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2255:     } else {
 2256:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2257:         foreach my $section (@sections) {
 2258:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2259:         }
 2260:     }
 2261:     return $section_inputs;
 2262: }
 2263: 
 2264: # --------------------------- show submissions of a student, option to grade 
 2265: sub submission {
 2266:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2267:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2268:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2269:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2270:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2271: 
 2272:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2273:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2274:     my $is_tool = ($symb =~ /ext\.tool$/);
 2275:     my ($essayurl,%coursedesc_by_cid);
 2276: 
 2277:     if (!&canview($usec)) {
 2278:         $request->print(
 2279:             '<span class="LC_warning">'.
 2280:             &mt('Unable to view requested student.').
 2281:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2282:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2283:             '</span>');
 2284: 	return;
 2285:     }
 2286: 
 2287:     my $res_error;
 2288:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2289:         &response_type($symb,\$res_error);
 2290:     if ($res_error) {
 2291:         $request->print(&navmap_errormsg());
 2292:         return;
 2293:     }
 2294: 
 2295:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2296:     unless ($is_tool) { 
 2297:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2298:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2299:     }
 2300:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2301:         $env{'form.compmsg'} = 1;
 2302:     }
 2303:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2304:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2305: 	'" src="'.$request->dir_config('lonIconsURL').
 2306: 	'/check.gif" height="16" border="0" />';
 2307: 
 2308:     # header info
 2309:     if ($counter == 0) {
 2310:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2311:         if (@chosenparts) {
 2312:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2313:         } elsif ($divforres) {
 2314:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2315:         } else {
 2316:             $request->print('<br clear="all" />');
 2317:         }
 2318: 	&sub_page_js($request);
 2319:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2320: 	&sub_page_kw_js($request) if ($numessay);
 2321: 
 2322: 	# option to display problem, only once else it cause problems 
 2323:         # with the form later since the problem has a form.
 2324: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2325: 	    my $mode;
 2326: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2327: 		$mode='both';
 2328: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2329: 		$mode='text';
 2330: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2331: 		$mode='answer';
 2332: 	    }
 2333: 	    &Apache::lonxml::clear_problem_counter();
 2334: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2335: 	}
 2336: 
 2337: 	my %keyhash = ();
 2338: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2339: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2340: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2341: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2342: 	}
 2343: 	# kwclr is the only variable that is guaranteed not to be blank
 2344: 	# if this subroutine has been called once.
 2345: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2346: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2347: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2348: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2349: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2350: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2351: 	}
 2352: 	if ($env{'form.compmsg'}) {
 2353: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2354: 		$keyhash{$symb.'_subject'} : $probtitle;
 2355: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2356: 	}
 2357: 
 2358: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2359: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2360: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2361: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2362: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2363: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2364: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2365: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2366: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2367: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2368: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2369: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2370: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2371: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2372: 			&build_section_inputs().
 2373: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2374: 			'<input type="hidden" name="NCT"'.
 2375: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2376: 	if ($env{'form.compmsg'}) {
 2377: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2378: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2379: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2380: 	}
 2381: 	if ($numessay) {
 2382: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2383: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2384: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2385: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2386: 	}
 2387: 
 2388: 	my ($cts,$prnmsg) = (1,'');
 2389: 	while ($cts <= $env{'form.savemsgN'}) {
 2390: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2391: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2392: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2393: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2394: 		'" />'."\n".
 2395: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2396: 	    $cts++;
 2397: 	}
 2398: 	$request->print($prnmsg);
 2399: 
 2400: 	if ($numessay) {
 2401: 
 2402:             my %lt = &Apache::lonlocal::texthash(
 2403:                           keyh => 'Keyword Highlighting for Essays',
 2404:                           keyw => 'Keyword Options',
 2405:                           list => 'List',
 2406:                           past => 'Paste Selection to List',
 2407:                           high => 'Highlight Attribute',
 2408:                      );
 2409: #
 2410: # Print out the keyword options line
 2411: #
 2412: 	    $request->print(
 2413:                 '<div class="LC_columnSection">'
 2414:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2415:                .&Apache::lonhtmlcommon::funclist_from_array(
 2416:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2417:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2418:  class="page">'.$lt{'past'}.'</a>',
 2419:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2420:                     {legend => $lt{'keyw'}})
 2421:                .'</fieldset></div>'
 2422:             );
 2423: 
 2424: #
 2425: # Load the other essays for similarity check
 2426: #
 2427:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2428:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2429:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2430:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2431:                 if ($cdom ne '' && $cnum ne '') {
 2432:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2433:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2434:                         my $apath = $1.'_'.$id;
 2435:                         $apath=~s/\W/\_/gs;
 2436:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2437:                     }
 2438:                 }
 2439:             } else {
 2440: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2441: 	        $apath=&escape($apath);
 2442: 	        $apath=~s/\W/\_/gs;
 2443:                 &init_old_essays($symb,$apath,$adom,$aname);
 2444:             }
 2445:         }
 2446:     }
 2447: 
 2448: # This is where output for one specific student would start
 2449:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2450:     $request->print(
 2451:         "\n\n"
 2452:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2453:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2454:        ."\n"
 2455:     );
 2456: 
 2457:     # Show additional functions if allowed
 2458:     if ($perm{'vgr'}) {
 2459:         $request->print(
 2460:             &Apache::loncommon::track_student_link(
 2461:                 'View recent activity',
 2462:                 $uname,$udom,'check')
 2463:            .' '
 2464:         );
 2465:     }
 2466:     if ($perm{'opa'}) {
 2467:         $request->print(
 2468:             &Apache::loncommon::pprmlink(
 2469:                 &mt('Set/Change parameters'),
 2470:                 $uname,$udom,$symb,'check'));
 2471:     }
 2472: 
 2473:     # Show Problem
 2474:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2475: 	my $mode;
 2476: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2477: 	    $mode='both';
 2478: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2479: 	    $mode='text';
 2480: 	} elsif ($env{'form.vAns'} eq 'all') {
 2481: 	    $mode='answer';
 2482: 	}
 2483: 	&Apache::lonxml::clear_problem_counter();
 2484: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2485:     }
 2486: 
 2487:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2488: 
 2489:     # Display student info
 2490:     $request->print(($counter == 0 ? '' : '<br />'));
 2491: 
 2492:     my $boxtitle = &mt('Submissions');
 2493:     if ($is_tool) {
 2494:         $boxtitle = &mt('Transactions')
 2495:     }
 2496:     my $result='<div class="LC_Box">'
 2497:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2498:     $result.='<input type="hidden" name="name'.$counter.
 2499:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2500:     if (($numresp > $numessay) && !$is_tool) {
 2501:         $result.='<p class="LC_info">'
 2502:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2503:                 ."</p>\n";
 2504:     }
 2505: 
 2506:     # If any part of the problem is an essayresponse, then check for collaborators
 2507:     my $fullname;
 2508:     my $col_fullnames = [];
 2509:     if ($numessay) {
 2510: 	(my $sub_result,$fullname,$col_fullnames)=
 2511: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2512: 				 $counter);
 2513: 	$result.=$sub_result;
 2514:     }
 2515:     $request->print($result."\n");
 2516: 
 2517:     # print student answer/submission
 2518:     # Options are (1) Last submission only
 2519:     #             (2) Last submission (with detailed information for that submission)
 2520:     #             (3) All transactions (by date)
 2521:     #             (4) The whole record (with detailed information for all transactions)
 2522: 
 2523:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2524: 
 2525:     my $lastsubonly;
 2526: 
 2527:     if ($$timestamp eq '') {
 2528:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2529:     } elsif ($is_tool) {
 2530:         $lastsubonly =
 2531:             '<div class="LC_grade_submissions_body">'
 2532:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2533:     } else {
 2534:         $lastsubonly =
 2535:             '<div class="LC_grade_submissions_body">'
 2536:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2537: 
 2538: 	my %seenparts;
 2539: 	my @part_response_id = &flatten_responseType($responseType);
 2540: 	foreach my $part (@part_response_id) {
 2541: 	    my ($partid,$respid) = @{ $part };
 2542: 	    my $display_part=&get_display_part($partid,$symb);
 2543: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2544: 		if (exists($seenparts{$partid})) { next; }
 2545: 		$seenparts{$partid}=1;
 2546:                 $request->print(
 2547:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2548:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2549:                                '<a href="javascript:viewSubmitter(\''.
 2550:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2551:                                '\');" target="_self">'.
 2552:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2553:                     '<br />');
 2554: 		next;
 2555: 	    }
 2556: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2557: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2558:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2559:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2560:                     ' <span class="LC_internal_info">'.
 2561:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2562:                     '</span>&nbsp; &nbsp;'.
 2563: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2564: 		next;
 2565: 	    }
 2566: 	    foreach my $submission (@$string) {
 2567: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2568: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2569: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2570: 		# Similarity check
 2571:                 my $similar='';
 2572:                 my ($type,$trial,$rndseed);
 2573:                 if ($hide eq 'rand') {
 2574:                     $type = 'randomizetry';
 2575:                     $trial = $record{"resource.$partid.tries"};
 2576:                     $rndseed = $record{"resource.$partid.rndseed"};
 2577:                 }
 2578: 	        if ($env{'form.checkPlag'}) {
 2579:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2580: 		        &most_similar($uname,$udom,$symb,$subval);
 2581: 		    if ($osim) {
 2582: 			$osim=int($osim*100.0);
 2583:                         if ($hide eq 'anon') {
 2584:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2585:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2586:                         } else {
 2587: 			    $similar='<hr />';
 2588:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2589:                                 $similar .= '<h3><span class="LC_warning">'.
 2590:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2591:                                                 $osim,
 2592:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2593:                                             '</span></h3>';
 2594:                             } else {
 2595:                                 my %old_course_desc;
 2596:                                 if ($ocrsid ne '') {
 2597:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2598:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2599:                                     } else {
 2600:                                         my $args;
 2601:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2602:                                             $args = {'one_time' => 1};
 2603:                                         }
 2604:                                         %old_course_desc =
 2605:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2606:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2607:                                     }
 2608:                                     $similar .=
 2609:                                         '<h3><span class="LC_warning">'.
 2610:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2611:                                             $osim,
 2612:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2613:                                             $old_course_desc{'description'},
 2614:                                             $old_course_desc{'num'},
 2615:                                             $old_course_desc{'domain'}).
 2616:                                         '</span></h3>';
 2617:                                 } else {
 2618:                                     $similar .=
 2619:                                         '<h3><span class="LC_warning">'.
 2620:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2621:                                             $osim,
 2622:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2623:                                         '</span></h3>';
 2624:                                 }
 2625:                             }
 2626:                             $similar .= '<blockquote><i>'.
 2627:                                         &keywords_highlight($oessay).
 2628:                                         '</i></blockquote><hr />';
 2629:                         }
 2630: 	            }
 2631: 		}
 2632: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2633:                                      undef,$type,$trial,$rndseed);
 2634:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2635:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2636:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2637: 		    my $display_part=&get_display_part($partid,$symb);
 2638:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2639:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2640:                         ' <span class="LC_internal_info">'.
 2641:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2642:                         '</span>&nbsp; &nbsp;';
 2643: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2644:                         
 2645: 		    if (@$files) {
 2646:                         if ($hide eq 'anon') {
 2647:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2648:                         } else {
 2649:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2650:                                         .'<br /><span class="LC_warning">';
 2651:                             if(@$files == 1) {
 2652:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2653:                             } else {
 2654:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2655:                             }
 2656:                             $lastsubonly .= '</span>';                         
 2657:                             foreach my $file (@$files) {
 2658:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2659:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2660:                             }
 2661:                         }
 2662: 			$lastsubonly.='<br />';
 2663:                     }
 2664:                     if ($hide eq 'anon') {
 2665:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2666:                     } else {
 2667:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2668:                         if ($draft) {
 2669:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2670:                         }
 2671:                         $subval =
 2672: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2673: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2674:                         if ($responsetype eq 'essay') {
 2675:                             $subval =~ s{\n}{<br />}g;
 2676:                         }
 2677:                         $lastsubonly.=$subval."\n";
 2678:                     }
 2679: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2680: 		    $lastsubonly.='</div>';
 2681: 		}
 2682:             }
 2683: 	}
 2684: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2685:     }
 2686:     $request->print($lastsubonly);
 2687:     if ($env{'form.lastSub'} eq 'datesub') {
 2688:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2689: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2690:     }
 2691:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2692:         my $identifier = (&canmodify($usec)? $counter : '');
 2693:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2694: 								 $env{'request.course.id'},
 2695: 								 $last,'.submission',
 2696: 								 'Apache::grades::keywords_highlight',
 2697:                                                                  $usec,$identifier));
 2698:     }
 2699:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2700: 	.$udom.'" />'."\n");
 2701:     # return if view submission with no grading option
 2702:     if (!&canmodify($usec)) {
 2703: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2704: 	return;
 2705:     } else {
 2706: 	$request->print('</div>'."\n");
 2707:     }
 2708: 
 2709:     # grading message center
 2710: 
 2711:     if ($env{'form.compmsg'}) {
 2712:         my $result='<div class="LC_Box">'.
 2713:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2714:                    '<div class="LC_grade_message_center_body">';
 2715:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2716:         my $msgfor = $givenn.' '.$lastname;
 2717:         if (scalar(@$col_fullnames) > 0) {
 2718:             my $lastone = pop(@$col_fullnames);
 2719:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2720:         }
 2721:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2722:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2723:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2724:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2725:                  ',\''.$msgfor.'\');" target="_self">'.
 2726:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2727:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2728:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2729:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2730:                  '<br />&nbsp;('.
 2731:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2732:                  '</div></div>';
 2733:         $request->print($result);
 2734:     }
 2735: 
 2736:     my %seen = ();
 2737:     my @partlist;
 2738:     my @gradePartRespid;
 2739:     my @part_response_id;
 2740:     if ($is_tool) {
 2741:         @part_response_id = ([0,'']);
 2742:     } else {
 2743:         @part_response_id = &flatten_responseType($responseType);
 2744:     }
 2745:     $request->print(
 2746:         '<div class="LC_Box">'
 2747:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2748:     );
 2749:     $request->print(&gradeBox_start());
 2750:     foreach my $part_response_id (@part_response_id) {
 2751:     	my ($partid,$respid) = @{ $part_response_id };
 2752: 	my $part_resp = join('_',@{ $part_response_id });
 2753: 	next if ($seen{$partid} > 0);
 2754: 	$seen{$partid}++;
 2755: 	push(@partlist,$partid);
 2756: 	push(@gradePartRespid,$partid.'.'.$respid);
 2757: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2758:     }
 2759:     $request->print(&gradeBox_end()); # </div>
 2760:     $request->print('</div>');
 2761: 
 2762:     $request->print('<div class="LC_grade_info_links">');
 2763:     $request->print('</div>');
 2764: 
 2765:     $result='<input type="hidden" name="partlist'.$counter.
 2766: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2767:     $result.='<input type="hidden" name="gradePartRespid'.
 2768: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2769:     my $ctr = 0;
 2770:     while ($ctr < scalar(@partlist)) {
 2771: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2772: 	    $partlist[$ctr].'" />'."\n";
 2773: 	$ctr++;
 2774:     }
 2775:     $request->print($result.''."\n");
 2776: 
 2777: # Done with printing info for one student
 2778: 
 2779:     $request->print('</div>');#LC_grade_show_user
 2780: 
 2781: 
 2782:     # print end of form
 2783:     if ($counter == $total) {
 2784:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2785: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2786: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2787: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2788: 	my $ntstu ='<select name="NTSTU">'.
 2789: 	    '<option>1</option><option>2</option>'.
 2790: 	    '<option>3</option><option>5</option>'.
 2791: 	    '<option>7</option><option>10</option></select>'."\n";
 2792: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2793: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2794:         $endform.=&mt('[_1]student(s)',$ntstu);
 2795: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2796: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2797: 	    '<input type="button" value="'.&mt('Next').'" '.
 2798: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2799:         $endform.='<span class="LC_warning">'.
 2800:                   &mt('(Next and Previous (student) do not save the scores.)').
 2801:                   '</span>'."\n" ;
 2802:         $endform.="<input type='hidden' value='".&get_increment().
 2803:             "' name='increment' />";
 2804: 	$endform.='</td></tr></table></form>';
 2805: 	$request->print($endform);
 2806:     }
 2807:     return '';
 2808: }
 2809: 
 2810: sub check_collaborators {
 2811:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2812:     my ($result,@col_fullnames);
 2813:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2814:     foreach my $part (keys(%$handgrade)) {
 2815: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2816: 					'.maxcollaborators',
 2817: 					$symb,$udom,$uname);
 2818: 	next if ($ncol <= 0);
 2819: 	$part =~ s/\_/\./g;
 2820: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2821: 	my (@good_collaborators, @bad_collaborators);
 2822: 	foreach my $possible_collaborator
 2823: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2824: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2825: 	    next if ($possible_collaborator eq '');
 2826: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2827: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2828: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2829: 	    # Doing this grep allows 'fuzzy' specification
 2830: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2831: 			       keys(%$classlist));
 2832: 	    if (! scalar(@matches)) {
 2833: 		push(@bad_collaborators, $possible_collaborator);
 2834: 	    } else {
 2835: 		push(@good_collaborators, @matches);
 2836: 	    }
 2837: 	}
 2838: 	if (scalar(@good_collaborators) != 0) {
 2839: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2840: 	    foreach my $name (@good_collaborators) {
 2841: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2842: 		push(@col_fullnames, $givenn.' '.$lastname);
 2843: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2844: 	    }
 2845: 	    $result.='</ol><br />'."\n";
 2846: 	    my ($part)=split(/\./,$part);
 2847: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2848: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2849: 		"\n";
 2850: 	}
 2851: 	if (scalar(@bad_collaborators) > 0) {
 2852: 	    $result.='<div class="LC_warning">';
 2853: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2854: 	    $result .= '</div>';
 2855: 	}         
 2856: 	if (scalar(@bad_collaborators > $ncol)) {
 2857: 	    $result .= '<div class="LC_warning">';
 2858: 	    $result .= &mt('This student has submitted too many '.
 2859: 		'collaborators.  Maximum is [_1].',$ncol);
 2860: 	    $result .= '</div>';
 2861: 	}
 2862:     }
 2863:     return ($result,$fullname,\@col_fullnames);
 2864: }
 2865: 
 2866: #--- Retrieve the last submission for all the parts
 2867: sub get_last_submission {
 2868:     my ($returnhash,$is_tool)=@_;
 2869:     my (@string,$timestamp,%lasthidden);
 2870:     if ($$returnhash{'version'}) {
 2871: 	my %lasthash=();
 2872: 	my ($version);
 2873: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2874: 	    foreach my $key (sort(split(/\:/,
 2875: 					$$returnhash{$version.':keys'}))) {
 2876: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2877: 		$timestamp = 
 2878: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2879: 	    }
 2880: 	}
 2881:         my (%typeparts,%randombytry);
 2882:         my $showsurv = 
 2883:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2884:         foreach my $key (sort(keys(%lasthash))) {
 2885:             if ($key =~ /\.type$/) {
 2886:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2887:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2888:                     ($lasthash{$key} eq 'randomizetry')) {
 2889:                     my ($ign,@parts) = split(/\./,$key);
 2890:                     pop(@parts);
 2891:                     my $id = join('.',@parts);
 2892:                     if ($lasthash{$key} eq 'randomizetry') {
 2893:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2894:                     } else {
 2895:                         unless ($showsurv) {
 2896:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2897:                         }
 2898:                     }
 2899:                     delete($lasthash{$key});
 2900:                 }
 2901:             }
 2902:         }
 2903:         my @hidden = keys(%typeparts);
 2904:         my @randomize = keys(%randombytry);
 2905: 	foreach my $key (keys(%lasthash)) {
 2906: 	    next if ($key !~ /\.submission$/);
 2907:             my $hide;
 2908:             if (@hidden) {
 2909:                 foreach my $id (@hidden) {
 2910:                     if ($key =~ /^\Q$id\E/) {
 2911:                         $hide = 'anon';
 2912:                         last;
 2913:                     }
 2914:                 }
 2915:             }
 2916:             unless ($hide) {
 2917:                 if (@randomize) {
 2918:                     foreach my $id (@randomize) {
 2919:                         if ($key =~ /^\Q$id\E/) {
 2920:                             $hide = 'rand';
 2921:                             last;
 2922:                         }
 2923:                     }
 2924:                 }
 2925:             }
 2926: 	    my ($partid,$foo) = split(/submission$/,$key);
 2927: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2928:             push(@string, join(':', $key, $hide, $draft, (
 2929:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2930:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2931: 	}
 2932:     }
 2933:     if (!@string) {
 2934:         my $msg;
 2935:         if ($is_tool) {
 2936:             $msg = &mt('No grade passed back.');
 2937:         } else {
 2938:             $msg = &mt('Nothing submitted - no attempts.');
 2939:         }
 2940: 	$string[0] =
 2941: 	    '<span class="LC_warning">'.$msg.'</span>';
 2942:     }
 2943:     return (\@string,\$timestamp);
 2944: }
 2945: 
 2946: #--- High light keywords, with style choosen by user.
 2947: sub keywords_highlight {
 2948:     my $string    = shift;
 2949:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2950:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2951:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2952:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2953:     foreach my $keyword (@keylist) {
 2954: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2955:     }
 2956:     return $string;
 2957: }
 2958: 
 2959: # For Tasks provide a mechanism to display previous version for one specific student
 2960: 
 2961: sub show_previous_task_version {
 2962:     my ($request,$symb) = @_;
 2963:     if ($symb eq '') {
 2964:         $request->print(
 2965:             '<span class="LC_error">'.
 2966:             &mt('Unable to handle ambiguous references.').
 2967:             '</span>');
 2968:         return '';
 2969:     }
 2970:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2971:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2972:     if (!&canview($usec)) {
 2973:         $request->print(
 2974:             '<span class="LC_warning">'.
 2975:             &mt('Unable to view previous version for requested student.').
 2976:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2977:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2978:             '</span>');
 2979:         return;
 2980:     }
 2981:     my $mode = 'both';
 2982:     my $isTask = ($symb =~/\.task$/);
 2983:     if ($isTask) {
 2984:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2985:             if ($env{'form.fullname'} eq '') {
 2986:                 $env{'form.fullname'} =
 2987:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2988:             }
 2989:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2990:             $request->print("\n\n".
 2991:                             '<div class="LC_grade_show_user">'.
 2992:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2993:                             '</h2>'."\n");
 2994:             &Apache::lonxml::clear_problem_counter();
 2995:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2996:                             {'previousversion' => $env{'form.previousversion'} }));
 2997:             $request->print("\n</div>");
 2998:         }
 2999:     }
 3000:     return;
 3001: }
 3002: 
 3003: sub choose_task_version_form {
 3004:     my ($symb,$uname,$udom,$nomenu) = @_;
 3005:     my $isTask = ($symb =~/\.task$/);
 3006:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3007:     if ($isTask) {
 3008:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3009:                                               $udom,$uname);
 3010:         if (($record{'resource.0.version'} eq '') ||
 3011:             ($record{'resource.0.version'} < 2)) {
 3012:             return ($record{'resource.0.version'},
 3013:                     $record{'resource.0.version'},$result,$js);
 3014:         } else {
 3015:             $current = $record{'resource.0.version'};
 3016:         }
 3017:         if ($env{'form.previousversion'}) {
 3018:             $displayed = $env{'form.previousversion'};
 3019:             $rowtitle = &mt('Choose another version:')
 3020:         } else {
 3021:             $displayed = $current;
 3022:             $rowtitle = &mt('Show earlier version:');
 3023:         }
 3024:         $result = '<div class="LC_left_float">';
 3025:         my $list;
 3026:         my $numversions = 0;
 3027:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3028:             if ($i == $current) {
 3029:                 if (!$env{'form.previousversion'} || $nomenu) {
 3030:                     next;
 3031:                 } else {
 3032:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3033:                     $numversions ++;
 3034:                 }
 3035:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3036:                 unless ($i == $env{'form.previousversion'}) {
 3037:                     $numversions ++;
 3038:                 }
 3039:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3040:             }
 3041:         }
 3042:         if ($numversions) {
 3043:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3044:             $result .=
 3045:                 '<form name="getprev" method="post" action=""'.
 3046:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3047:                 &Apache::loncommon::start_data_table().
 3048:                 &Apache::loncommon::start_data_table_row().
 3049:                 '<th align="left">'.$rowtitle.'</th>'.
 3050:                 '<td><select name="version">'.
 3051:                 '<option>'.&mt('Select').'</option>'.
 3052:                 $list.
 3053:                 '</select></td>'.
 3054:                 &Apache::loncommon::end_data_table_row();
 3055:             unless ($nomenu) {
 3056:                 $result .= &Apache::loncommon::start_data_table_row().
 3057:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3058:                 '<td><span class="LC_nobreak">'.
 3059:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3060:                 &mt('Yes').'</label>'.
 3061:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3062:                 '</span></td>'.
 3063:                 &Apache::loncommon::end_data_table_row();
 3064:             }
 3065:             $result .=
 3066:                 &Apache::loncommon::start_data_table_row().
 3067:                 '<th align="left">&nbsp;</th>'.
 3068:                 '<td>'.
 3069:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3070:                 '</td>'.
 3071:                 &Apache::loncommon::end_data_table_row().
 3072:                 &Apache::loncommon::end_data_table().
 3073:                 '</form>';
 3074:             $js = &previous_display_javascript($nomenu,$current);
 3075:         } elsif ($displayed && $nomenu) {
 3076:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3077:         } else {
 3078:             $result .= &mt('No previous versions to show for this student');
 3079:         }
 3080:         $result .= '</div>';
 3081:     }
 3082:     return ($current,$displayed,$result,$js);
 3083: }
 3084: 
 3085: sub previous_display_javascript {
 3086:     my ($nomenu,$current) = @_;
 3087:     my $js = <<"JSONE";
 3088: <script type="text/javascript">
 3089: // <![CDATA[
 3090: function previousVersion(uname,udom,symb) {
 3091:     var current = '$current';
 3092:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3093:     var prevstr = new RegExp("^\\\\d+\$");
 3094:     if (!prevstr.test(version)) {
 3095:         return false;
 3096:     }
 3097:     var url = '';
 3098:     if (version == current) {
 3099:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3100:     } else {
 3101:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3102:     }
 3103: JSONE
 3104:     if ($nomenu) {
 3105:         $js .= <<"JSTWO";
 3106:     document.location.href = url;
 3107: JSTWO
 3108:     } else {
 3109:         $js .= <<"JSTHREE";
 3110:     var newwin = 0;
 3111:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3112:         if (document.getprev.prevwin[i].checked == true) {
 3113:             newwin = document.getprev.prevwin[i].value;
 3114:         }
 3115:     }
 3116:     if (newwin == 1) {
 3117:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3118:         url = url+'&inhibitmenu=yes';
 3119:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3120:             previousWin = window.open(url,'',options,1);
 3121:         } else {
 3122:             previousWin.location.href = url;
 3123:         }
 3124:         previousWin.focus();
 3125:         return false;
 3126:     } else {
 3127:         document.location.href = url;
 3128:         return false;
 3129:     }
 3130: JSTHREE
 3131:     }
 3132:     $js .= <<"ENDJS";
 3133:     return false;
 3134: }
 3135: // ]]>
 3136: </script>
 3137: ENDJS
 3138: 
 3139: }
 3140: 
 3141: #--- Called from submission routine
 3142: sub processHandGrade {
 3143:     my ($request,$symb) = @_;
 3144:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3145:     my $button = $env{'form.gradeOpt'};
 3146:     my $ngrade = $env{'form.NCT'};
 3147:     my $ntstu  = $env{'form.NTSTU'};
 3148:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3149:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3150: 
 3151:     if ($button eq 'Save & Next') {
 3152: 	my $ctr = 0;
 3153: 	while ($ctr < $ngrade) {
 3154: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3155: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3156:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3157: 	    if ($errorflag eq 'no_score') {
 3158: 		$ctr++;
 3159: 		next;
 3160: 	    }
 3161: 	    if ($errorflag eq 'not_allowed') {
 3162: 		$request->print(
 3163:                     '<span class="LC_error">'
 3164:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3165:                    .'</span>');
 3166: 		$ctr++;
 3167: 		next;
 3168: 	    }
 3169:             if ($numhidden) {
 3170:                 $request->print(
 3171:                     '<span class="LC_info">'
 3172:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3173:                    .'</span><br />');
 3174:             }
 3175: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3176: 	    my ($subject,$message,$msgstatus) = ('','','');
 3177: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3178:             my ($feedurl,$showsymb) =
 3179: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3180: 	    my $messagetail;
 3181: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3182: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3183: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3184: 		$subject.=' ['.$restitle.']';
 3185: 		my (@msgnum) = split(/,/,$includemsg);
 3186: 		foreach (@msgnum) {
 3187: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3188: 		}
 3189: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3190: 		if ($env{'form.withgrades'.$ctr}) {
 3191: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3192: 		    $messagetail = " for <a href=\"".
 3193: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3194: 		}
 3195: 		$msgstatus = 
 3196:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3197: 						     $message.$messagetail,
 3198:                                                      undef,$feedurl,undef,
 3199:                                                      undef,undef,$showsymb,
 3200:                                                      $restitle);
 3201: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3202: 				$msgstatus.'<br />');
 3203: 	    }
 3204: 	    if ($env{'form.collaborator'.$ctr}) {
 3205: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3206: 		foreach my $collabstr (@collabstrs) {
 3207: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3208: 		    foreach my $collaborator (@collaborators) {
 3209: 			my ($errorflag,$pts,$wgt) = 
 3210: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3211: 					   $env{'form.unamedom'.$ctr},$part);
 3212: 			if ($errorflag eq 'not_allowed') {
 3213: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3214: 			    next;
 3215: 			} elsif ($message ne '') {
 3216: 			    my ($baseurl,$showsymb) = 
 3217: 				&get_feedurl_and_symb($symb,$collaborator,
 3218: 						      $udom);
 3219: 			    if ($env{'form.withgrades'.$ctr}) {
 3220: 				$messagetail = " for <a href=\"".
 3221:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3222: 			    }
 3223: 			    $msgstatus = 
 3224: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3225: 			}
 3226: 		    }
 3227: 		}
 3228: 	    }
 3229: 	    $ctr++;
 3230: 	}
 3231:     }
 3232: 
 3233:     my $res_error;
 3234:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3235:     if ($res_error) {
 3236:         $request->print(&navmap_errormsg());
 3237:         return;
 3238:     }
 3239: 
 3240:     my %keyhash = ();
 3241:     if ($numessay) {
 3242: 	# Keywords sorted in alphabatical order
 3243: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3244: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3245: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3246: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3247: 	$env{'form.keywords'} = join(' ',@keywords);
 3248: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3249: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3250: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3251: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3252: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3253:     }
 3254: 
 3255:     if ($env{'form.compmsg'}) {
 3256: 	# message center - Order of message gets changed. Blank line is eliminated.
 3257: 	# New messages are saved in env for the next student.
 3258: 	# All messages are saved in nohist_handgrade.db
 3259: 	my ($ctr,$idx) = (1,1);
 3260: 	while ($ctr <= $env{'form.savemsgN'}) {
 3261: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3262: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3263: 		$idx++;
 3264: 	    }
 3265: 	    $ctr++;
 3266: 	}
 3267: 	$ctr = 0;
 3268: 	while ($ctr < $ngrade) {
 3269: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3270: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3271: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3272: 	        $idx++;
 3273: 	    }
 3274: 	    $ctr++;
 3275: 	}
 3276: 	$env{'form.savemsgN'} = --$idx;
 3277: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3278:     }
 3279:     if (($numessay) || ($env{'form.compmsg'})) {
 3280:         my $putresult = &Apache::lonnet::put
 3281:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3282:     }
 3283: 
 3284:     # Called by Save & Refresh from Highlight Attribute Window
 3285:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3286:     if ($env{'form.refresh'} eq 'on') {
 3287: 	my ($ctr,$total) = (0,0);
 3288: 	while ($ctr < $ngrade) {
 3289: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3290: 	    $ctr++;
 3291: 	}
 3292: 	$env{'form.NTSTU'}=$ngrade;
 3293: 	$ctr = 0;
 3294: 	while ($ctr < $total) {
 3295: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3296: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3297: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3298: 	    &submission($request,$ctr,$total-1,$symb);
 3299: 	    $ctr++;
 3300: 	}
 3301: 	return '';
 3302:     }
 3303: 
 3304:     # Get the next/previous one or group of students
 3305:     my $firststu = $env{'form.unamedom0'};
 3306:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3307:     my $ctr = 2;
 3308:     while ($laststu eq '') {
 3309: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3310: 	$ctr++;
 3311: 	$laststu = $firststu if ($ctr > $ngrade);
 3312:     }
 3313: 
 3314:     my (@parsedlist,@nextlist);
 3315:     my ($nextflg) = 0;
 3316:     foreach my $item (sort 
 3317: 	     {
 3318: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3319: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3320: 		 }
 3321: 		 return $a cmp $b;
 3322: 	     } (keys(%$fullname))) {
 3323: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3324: 	    push(@parsedlist,$item);
 3325: 	}
 3326: 	$nextflg = 1 if ($item eq $laststu);
 3327: 	if ($button eq 'Previous') {
 3328: 	    last if ($item eq $firststu);
 3329: 	    push(@parsedlist,$item);
 3330: 	}
 3331:     }
 3332:     $ctr = 0;
 3333:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3334:     foreach my $student (@parsedlist) {
 3335: 	my $submitonly=$env{'form.submitonly'};
 3336: 	my ($uname,$udom) = split(/:/,$student);
 3337: 	
 3338: 	if ($submitonly eq 'queued') {
 3339: 	    my %queue_status = 
 3340: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3341: 							$udom,$uname);
 3342: 	    next if (!defined($queue_status{'gradingqueue'}));
 3343: 	}
 3344: 
 3345: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3346: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3347: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3348: 	    my $submitted = 0;
 3349: 	    my $ungraded = 0;
 3350: 	    my $incorrect = 0;
 3351: 	    foreach my $item (keys(%status)) {
 3352: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3353: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3354: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3355: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3356: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3357: 		    $submitted = 0;
 3358: 		}
 3359: 	    }
 3360: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3361: 				     $submitonly eq 'incorrect' ||
 3362: 				     $submitonly eq 'graded'));
 3363: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3364: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3365: 	}
 3366: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3367: 	last if ($ctr == $ntstu);
 3368: 	$ctr++;
 3369:     }
 3370: 
 3371:     $ctr = 0;
 3372:     my $total = scalar(@nextlist)-1;
 3373: 
 3374:     foreach (sort(@nextlist)) {
 3375: 	my ($uname,$udom,$submitter) = split(/:/);
 3376: 	$env{'form.student'}  = $uname;
 3377: 	$env{'form.userdom'}  = $udom;
 3378: 	$env{'form.fullname'} = $$fullname{$_};
 3379: 	&submission($request,$ctr,$total,$symb);
 3380: 	$ctr++;
 3381:     }
 3382:     if ($total < 0) {
 3383: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3384: 	$request->print($the_end);
 3385:     }
 3386:     return '';
 3387: }
 3388: 
 3389: #---- Save the score and award for each student, if changed
 3390: sub saveHandGrade {
 3391:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3392:     my @version_parts;
 3393:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3394: 					   $env{'request.course.id'});
 3395:     if (!&canmodify($usec)) { return('not_allowed'); }
 3396:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3397:     my @parts_graded;
 3398:     my %newrecord  = ();
 3399:     my ($pts,$wgt,$totchg) = ('','',0);
 3400:     my %aggregate = ();
 3401:     my $aggregateflag = 0;
 3402:     if ($env{'form.HIDE'.$newflg}) {
 3403:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3404:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3405:         $totchg += $numchgs;
 3406:     }
 3407:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3408:     foreach my $new_part (@parts) {
 3409: 	#collaborator ($submi may vary for different parts
 3410: 	if ($submitter && $new_part ne $part) { next; }
 3411: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3412: 	if ($dropMenu eq 'excused') {
 3413: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3414: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3415: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3416: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3417: 		}
 3418: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3419: 	    }
 3420: 	} elsif ($dropMenu eq 'reset status'
 3421: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3422: 	    foreach my $key (keys(%record)) {
 3423: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3424: 	    }
 3425: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3426: 		"$env{'user.name'}:$env{'user.domain'}";
 3427:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3428: 
 3429:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3430: 					       [$new_part]);
 3431:             my $aggtries =$totaltries;
 3432:             if ($last_resets{$new_part}) {
 3433:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3434: 					   $new_part);
 3435:             }
 3436: 
 3437:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3438:             if ($aggtries > 0) {
 3439:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3440:                 $aggregateflag = 1;
 3441:             }
 3442: 	} elsif ($dropMenu eq '') {
 3443: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3444: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3445: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3446: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3447: 		next;
 3448: 	    }
 3449: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3450: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3451: 	    my $partial= $pts/$wgt;
 3452: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3453: 		#do not update score for part if not changed.
 3454:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3455: 		next;
 3456: 	    } else {
 3457: 	        push(@parts_graded,$new_part);
 3458: 	    }
 3459: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3460: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3461: 	    }
 3462: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3463: 	    if ($partial == 0) {
 3464: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3465: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3466: 		}
 3467: 	    } else {
 3468: 		if ($record{$reckey} ne 'correct_by_override') {
 3469: 		    $newrecord{$reckey} = 'correct_by_override';
 3470: 		}
 3471: 	    }	    
 3472: 	    if ($submitter && 
 3473: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3474: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3475: 	    }
 3476: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3477: 		"$env{'user.name'}:$env{'user.domain'}";
 3478: 	}
 3479: 	# unless problem has been graded, set flag to version the submitted files
 3480: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3481: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3482: 	        $dropMenu eq 'reset status')
 3483: 	   {
 3484: 	    push(@version_parts,$new_part);
 3485: 	}
 3486:     }
 3487:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3488:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3489: 
 3490:     if (%newrecord) {
 3491:         if (@version_parts) {
 3492:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3493:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3494: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3495: 	    foreach my $new_part (@version_parts) {
 3496: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3497: 				$new_part,\%newrecord);
 3498: 	    }
 3499:         }
 3500: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3501: 				$env{'request.course.id'},$domain,$stuname);
 3502: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3503: 				     $cdom,$cnum,$domain,$stuname);
 3504:     }
 3505:     if ($aggregateflag) {
 3506:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3507: 			      $cdom,$cnum);
 3508:     }
 3509:     return ('',$pts,$wgt,$totchg);
 3510: }
 3511: 
 3512: sub makehidden {
 3513:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3514:     return unless (ref($record) eq 'HASH');
 3515:     my %modified;
 3516:     my $numchanged = 0;
 3517:     if (exists($record->{$version.':keys'})) {
 3518:         my $partsregexp = $parts;
 3519:         $partsregexp =~ s/,/|/g;
 3520:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3521:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3522:                  my $item = $1;
 3523:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3524:                      $modified{$key} = $record->{$version.':'.$key};
 3525:                  }
 3526:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3527:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3528:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3529:                 $modified{$key} = $record->{$version.':'.$key};
 3530:             }
 3531:         }
 3532:         if (keys(%modified)) {
 3533:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3534:                                           $domain,$stuname,$tolog) eq 'ok') {
 3535:                 $numchanged ++;
 3536:             }
 3537:         }
 3538:     }
 3539:     return $numchanged;
 3540: }
 3541: 
 3542: sub check_and_remove_from_queue {
 3543:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3544:     my @ungraded_parts;
 3545:     foreach my $part (@{$parts}) {
 3546: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3547: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3548: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3549: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3550: 		) {
 3551: 	    push(@ungraded_parts, $part);
 3552: 	}
 3553:     }
 3554:     if ( !@ungraded_parts ) {
 3555: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3556: 					       $cnum,$domain,$stuname);
 3557:     }
 3558: }
 3559: 
 3560: sub handback_files {
 3561:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3562:     my $portfolio_root = '/userfiles/portfolio';
 3563:     my $res_error;
 3564:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3565:     if ($res_error) {
 3566:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3567:         return;
 3568:     }
 3569:     my @handedback;
 3570:     my $file_msg;
 3571:     my @part_response_id = &flatten_responseType($responseType);
 3572:     foreach my $part_response_id (@part_response_id) {
 3573:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3574: 	my $part_resp = join('_',@{ $part_response_id });
 3575:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3576:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3577:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3578:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3579:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3580:                     my ($directory,$answer_file) = 
 3581:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3582:                     my ($answer_name,$answer_ver,$answer_ext) =
 3583: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3584: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3585:                     my $getpropath = 1;
 3586:                     my ($dir_list,$listerror) =
 3587:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3588:                                                  $domain,$stuname,$getpropath);
 3589: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3590:                     # fix filename
 3591:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3592:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3593:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3594:             	                                $save_file_name);
 3595:                     if ($result !~ m|^/uploaded/|) {
 3596:                         $request->print('<br /><span class="LC_error">'.
 3597:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3598:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3599:                                         '</span>');
 3600:                     } else {
 3601:                         # mark the file as read only
 3602:                         push(@handedback,$save_file_name);
 3603: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3604: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3605: 			}
 3606:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3607: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3608:                     }
 3609:                     $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>'));
 3610:                 }
 3611:             }
 3612:         }
 3613:     }
 3614:     if (@handedback > 0) {
 3615:         $request->print('<br />');
 3616:         my @what = ($symb,$env{'request.course.id'},'handback');
 3617:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3618:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3619:         my ($subject,$message);
 3620:         if (scalar(@handedback) == 1) {
 3621:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3622:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3623:         } else {
 3624:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3625:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3626:         }
 3627:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3628:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3629:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3630:         my ($feedurl,$showsymb) =
 3631:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3632:         my $restitle = &Apache::lonnet::gettitle($symb);
 3633:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3634:         my $msgstatus =
 3635:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3636:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3637:                  $restitle);
 3638:         if ($msgstatus) {
 3639:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3640:         }
 3641:     }
 3642:     return;
 3643: }
 3644: 
 3645: sub get_feedurl_and_symb {
 3646:     my ($symb,$uname,$udom) = @_;
 3647:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3648:     $url = &Apache::lonnet::clutter($url);
 3649:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3650: 					$symb,$udom,$uname);
 3651:     if ($encrypturl =~ /^yes$/i) {
 3652: 	&Apache::lonenc::encrypted(\$url,1);
 3653: 	&Apache::lonenc::encrypted(\$symb,1);
 3654:     }
 3655:     return ($url,$symb);
 3656: }
 3657: 
 3658: sub get_submitted_files {
 3659:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3660:     my @files;
 3661:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3662:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3663:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3664:     	    push(@files,$file_url.$file);
 3665:         }
 3666:     }
 3667:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3668:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3669:     }
 3670:     return (\@files);
 3671: }
 3672: 
 3673: # ----------- Provides number of tries since last reset.
 3674: sub get_num_tries {
 3675:     my ($record,$last_reset,$part) = @_;
 3676:     my $timestamp = '';
 3677:     my $num_tries = 0;
 3678:     if ($$record{'version'}) {
 3679:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3680:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3681:                 $timestamp = $$record{$version.':timestamp'};
 3682:                 if ($timestamp > $last_reset) {
 3683:                     $num_tries ++;
 3684:                 } else {
 3685:                     last;
 3686:                 }
 3687:             }
 3688:         }
 3689:     }
 3690:     return $num_tries;
 3691: }
 3692: 
 3693: # ----------- Determine decrements required in aggregate totals 
 3694: sub decrement_aggs {
 3695:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3696:     my %decrement = (
 3697:                         attempts => 0,
 3698:                         users => 0,
 3699:                         correct => 0
 3700:                     );
 3701:     $decrement{'attempts'} = $aggtries;
 3702:     if ($solvedstatus =~ /^correct/) {
 3703:         $decrement{'correct'} = 1;
 3704:     }
 3705:     if ($aggtries == $totaltries) {
 3706:         $decrement{'users'} = 1;
 3707:     }
 3708:     foreach my $type (keys(%decrement)) {
 3709:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3710:     }
 3711:     return;
 3712: }
 3713: 
 3714: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3715: sub get_last_resets {
 3716:     my ($symb,$courseid,$partids) =@_;
 3717:     my %last_resets;
 3718:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3719:     my $cname = $env{'course.'.$courseid.'.num'};
 3720:     my @keys;
 3721:     foreach my $part (@{$partids}) {
 3722: 	push(@keys,"$symb\0$part\0resettime");
 3723:     }
 3724:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3725: 				     $cdom,$cname);
 3726:     foreach my $part (@{$partids}) {
 3727: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3728:     }
 3729:     return %last_resets;
 3730: }
 3731: 
 3732: # ----------- Handles creating versions for portfolio files as answers
 3733: sub version_portfiles {
 3734:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3735:     my $version_parts = join('|',@$v_flag);
 3736:     my @returned_keys;
 3737:     my $parts = join('|', @$parts_graded);
 3738:     foreach my $key (keys(%$record)) {
 3739:         my $new_portfiles;
 3740:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3741:             my @versioned_portfiles;
 3742:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3743:             if (@portfiles) {
 3744:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3745:                                                       \@versioned_portfiles);
 3746:             }
 3747:             $$record{$key} = join(',',@versioned_portfiles);
 3748:             push(@returned_keys,$key);
 3749:         }
 3750:     } 
 3751:     return (@returned_keys);   
 3752: }
 3753: 
 3754: #--------------------------------------------------------------------------------------
 3755: #
 3756: #-------------------------- Next few routines handles grading by section or whole class
 3757: #
 3758: #--- Javascript to handle grading by section or whole class
 3759: sub viewgrades_js {
 3760:     my ($request) = shift;
 3761: 
 3762:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3763:     &js_escape(\$alertmsg);
 3764:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3765:    function writePoint(partid,weight,point) {
 3766: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3767: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3768: 	if (point == "textval") {
 3769: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3770: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3771: 		alert("$alertmsg"+parseFloat(point));
 3772: 		var resetbox = false;
 3773: 		for (var i=0; i<radioButton.length; i++) {
 3774: 		    if (radioButton[i].checked) {
 3775: 			textbox.value = i;
 3776: 			resetbox = true;
 3777: 		    }
 3778: 		}
 3779: 		if (!resetbox) {
 3780: 		    textbox.value = "";
 3781: 		}
 3782: 		return;
 3783: 	    }
 3784: 	    if (parseFloat(point) > parseFloat(weight)) {
 3785: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3786: 				   ") greater than the weight for the part. Accept?");
 3787: 		if (resp == false) {
 3788: 		    textbox.value = "";
 3789: 		    return;
 3790: 		}
 3791: 	    }
 3792: 	    for (var i=0; i<radioButton.length; i++) {
 3793: 		radioButton[i].checked=false;
 3794: 		if (parseFloat(point) == i) {
 3795: 		    radioButton[i].checked=true;
 3796: 		}
 3797: 	    }
 3798: 
 3799: 	} else {
 3800: 	    textbox.value = parseFloat(point);
 3801: 	}
 3802: 	for (i=0;i<document.classgrade.total.value;i++) {
 3803: 	    var user = document.classgrade["ctr"+i].value;
 3804: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3805: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3806: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3807: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3808: 	    if (saveval != "correct") {
 3809: 		scorename.value = point;
 3810: 		if (selname[0].selected != true) {
 3811: 		    selname[0].selected = true;
 3812: 		}
 3813: 	    }
 3814: 	}
 3815: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3816:     }
 3817: 
 3818:     function writeRadText(partid,weight) {
 3819: 	var selval   = document.classgrade["SELVAL_"+partid];
 3820: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3821:         var override = document.classgrade["FORCE_"+partid].checked;
 3822: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3823: 	if (selval[1].selected || selval[2].selected) {
 3824: 	    for (var i=0; i<radioButton.length; i++) {
 3825: 		radioButton[i].checked=false;
 3826: 
 3827: 	    }
 3828: 	    textbox.value = "";
 3829: 
 3830: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3831: 		var user = document.classgrade["ctr"+i].value;
 3832: 		user = user.replace(new RegExp(':', 'g'),"_");
 3833: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3834: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3835: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3836: 		if ((saveval != "correct") || override) {
 3837: 		    scorename.value = "";
 3838: 		    if (selval[1].selected) {
 3839: 			selname[1].selected = true;
 3840: 		    } else {
 3841: 			selname[2].selected = true;
 3842: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3843: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3844: 		    }
 3845: 		}
 3846: 	    }
 3847: 	} else {
 3848: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3849: 		var user = document.classgrade["ctr"+i].value;
 3850: 		user = user.replace(new RegExp(':', 'g'),"_");
 3851: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3852: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3853: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3854: 		if ((saveval != "correct") || override) {
 3855: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3856: 		    selname[0].selected = true;
 3857: 		}
 3858: 	    }
 3859: 	}	    
 3860:     }
 3861: 
 3862:     function changeSelect(partid,user) {
 3863: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3864: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3865: 	var point  = textbox.value;
 3866: 	var weight = document.classgrade["weight_"+partid].value;
 3867: 
 3868: 	if (isNaN(point) || parseFloat(point) < 0) {
 3869: 	    alert("$alertmsg"+parseFloat(point));
 3870: 	    textbox.value = "";
 3871: 	    return;
 3872: 	}
 3873: 	if (parseFloat(point) > parseFloat(weight)) {
 3874: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3875: 			       ") greater than the weight of the part. Accept?");
 3876: 	    if (resp == false) {
 3877: 		textbox.value = "";
 3878: 		return;
 3879: 	    }
 3880: 	}
 3881: 	selval[0].selected = true;
 3882:     }
 3883: 
 3884:     function changeOneScore(partid,user) {
 3885: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3886: 	if (selval[1].selected || selval[2].selected) {
 3887: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3888: 	    if (selval[2].selected) {
 3889: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3890: 	    }
 3891:         }
 3892:     }
 3893: 
 3894:     function resetEntry(numpart) {
 3895: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3896: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3897: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3898: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3899: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3900: 	    for (var i=0; i<radioButton.length; i++) {
 3901: 		radioButton[i].checked=false;
 3902: 
 3903: 	    }
 3904: 	    textbox.value = "";
 3905: 	    selval[0].selected = true;
 3906: 
 3907: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3908: 		var user = document.classgrade["ctr"+i].value;
 3909: 		user = user.replace(new RegExp(':', 'g'),"_");
 3910: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3911: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3912: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3913: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3914: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3915: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3916: 		if (saveselval == "excused") {
 3917: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3918: 		} else {
 3919: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3920: 		}
 3921: 	    }
 3922: 	}
 3923:     }
 3924: 
 3925: VIEWJAVASCRIPT
 3926: }
 3927: 
 3928: #--- show scores for a section or whole class w/ option to change/update a score
 3929: sub viewgrades {
 3930:     my ($request,$symb) = @_;
 3931:     my ($is_tool,$toolsymb);
 3932:     if ($symb =~ /ext\.tool$/) {
 3933:         $is_tool = 1;
 3934:         $toolsymb = $symb;
 3935:     }
 3936:     &viewgrades_js($request);
 3937: 
 3938:     #need to make sure we have the correct data for later EXT calls, 
 3939:     #thus invalidate the cache
 3940:     &Apache::lonnet::devalidatecourseresdata(
 3941:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3942:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3943:     &Apache::lonnet::clear_EXT_cache_status();
 3944: 
 3945:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3946: 
 3947:     #view individual student submission form - called using Javascript viewOneStudent
 3948:     $result.=&jscriptNform($symb);
 3949: 
 3950:     #beginning of class grading form
 3951:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3952:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3953: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3954: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3955: 	&build_section_inputs().
 3956: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3957: 
 3958:     #retrieve selected groups
 3959:     my (@groups,$group_display);
 3960:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3961:     if (grep(/^all$/,@groups)) {
 3962:         @groups = ('all');
 3963:     } elsif (grep(/^none$/,@groups)) {
 3964:         @groups = ('none');
 3965:     } elsif (@groups > 0) {
 3966:         $group_display = join(', ',@groups);
 3967:     }
 3968: 
 3969:     my ($common_header,$specific_header,@sections,$section_display);
 3970:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3971:     if (grep(/^all$/,@sections)) {
 3972:         @sections = ('all');
 3973:         if ($group_display) {
 3974:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3975:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3976:         } elsif (grep(/^none$/,@groups)) {
 3977:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3978:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3979:         } else {
 3980: 	    $common_header = &mt('Assign Common Grade to Class');
 3981:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3982:         }
 3983:     } elsif (grep(/^none$/,@sections)) {
 3984:         @sections = ('none');
 3985:         if ($group_display) {
 3986:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3987:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3988:         } elsif (grep(/^none$/,@groups)) {
 3989:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3990:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3991:         } else {
 3992:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3993: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3994:         }
 3995:     } else {
 3996:         $section_display = join (", ",@sections);
 3997:         if ($group_display) {
 3998:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3999:                                  $section_display,$group_display);
 4000:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4001:                                    $section_display,$group_display);
 4002:         } elsif (grep(/^none$/,@groups)) {
 4003:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4004:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4005:         } else {
 4006:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4007: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4008:         }
 4009:     }
 4010:     my %submit_types = &substatus_options();
 4011:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4012: 
 4013:     if ($env{'form.submitonly'} eq 'all') {
 4014:         $result.= '<h3>'.$common_header.'</h3>';
 4015:     } else {
 4016:         my $text;
 4017:         if ($is_tool) {
 4018:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4019:         } else {
 4020:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4021:         }
 4022:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4023:     }
 4024:     $result .= &Apache::loncommon::start_data_table();
 4025:     #radio buttons/text box for assigning points for a section or class.
 4026:     #handles different parts of a problem
 4027:     my $res_error;
 4028:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4029:     if ($res_error) {
 4030:         return &navmap_errormsg();
 4031:     }
 4032:     my %weight = ();
 4033:     my $ctsparts = 0;
 4034:     my %seen = ();
 4035:     my @part_response_id;
 4036:     if ($is_tool) {
 4037:         @part_response_id = ([0,'']);
 4038:     } else {
 4039:         @part_response_id = &flatten_responseType($responseType);
 4040:     }
 4041:     foreach my $part_response_id (@part_response_id) {
 4042:     	my ($partid,$respid) = @{ $part_response_id };
 4043: 	my $part_resp = join('_',@{ $part_response_id });
 4044: 	next if $seen{$partid};
 4045: 	$seen{$partid}++;
 4046: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4047: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4048: 
 4049: 	my $display_part=&get_display_part($partid,$symb);
 4050: 	my $radio.='<table border="0"><tr>';  
 4051: 	my $ctr = 0;
 4052: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4053: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4054: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4055: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4056: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4057: 	    $ctr++;
 4058: 	}
 4059: 	$radio.='</tr></table>';
 4060: 	my $line = '<input type="text" name="TEXTVAL_'.
 4061: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4062: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4063: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4064:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4065:             '<select name="SELVAL_'.$partid.'" '.
 4066:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4067:                 $weight{$partid}.')"> '.
 4068: 	    '<option selected="selected"> </option>'.
 4069: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4070: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4071: 	    '</select></td>'.
 4072:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4073: 	$line.='<input type="hidden" name="partid_'.
 4074: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4075: 	$line.='<input type="hidden" name="weight_'.
 4076: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4077: 
 4078: 	$result.=
 4079: 	    &Apache::loncommon::start_data_table_row()."\n".
 4080: 	    '<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>'.
 4081: 	    &Apache::loncommon::end_data_table_row()."\n";
 4082: 	$ctsparts++;
 4083:     }
 4084:     $result.=&Apache::loncommon::end_data_table()."\n".
 4085: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4086:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4087: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4088: 
 4089:     #table listing all the students in a section/class
 4090:     #header of table
 4091:     if ($env{'form.submitonly'} eq 'all') {
 4092:         $result.= '<h3>'.$specific_header.'</h3>';
 4093:     } else {
 4094:         my $text;
 4095:         if ($is_tool) {
 4096:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4097:         } else {
 4098:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4099:         }
 4100:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4101:     }
 4102:     $result.= &Apache::loncommon::start_data_table().
 4103: 	      &Apache::loncommon::start_data_table_header_row().
 4104: 	      '<th>'.&mt('No.').'</th>'.
 4105: 	      '<th>'.&nameUserString('header')."</th>\n";
 4106:     my $partserror;
 4107:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4108:     if ($partserror) {
 4109:         return &navmap_errormsg();
 4110:     }
 4111:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4112:     my @partids = ();
 4113:     foreach my $part (@parts) {
 4114: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4115:         my $narrowtext = &mt('Tries');
 4116: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4117: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4118: 	my ($partid) = &split_part_type($part);
 4119:         push(@partids,$partid);
 4120: #
 4121: # FIXME: Looks like $display looks at English text
 4122: #
 4123: 	my $display_part=&get_display_part($partid,$symb);
 4124: 	if ($display =~ /^Partial Credit Factor/) {
 4125: 	    $result.='<th>'.
 4126: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4127: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4128: 	    next;
 4129: 	    
 4130: 	} else {
 4131: 	    if ($display =~ /Problem Status/) {
 4132: 		my $grade_status_mt = &mt('Grade Status');
 4133: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4134: 	    }
 4135: 	    my $part_mt = &mt('Part:');
 4136: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4137: 	}
 4138: 
 4139: 	$result.='<th>'.$display.'</th>'."\n";
 4140:     }
 4141:     $result.=&Apache::loncommon::end_data_table_header_row();
 4142: 
 4143:     my %last_resets = 
 4144: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4145: 
 4146:     #get info for each student
 4147:     #list all the students - with points and grade status
 4148:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4149:     my $ctr = 0;
 4150:     foreach (sort 
 4151: 	     {
 4152: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4153: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4154: 		 }
 4155: 		 return $a cmp $b;
 4156: 	     } (keys(%$fullname))) {
 4157: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4158: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4159:     }
 4160:     $result.=&Apache::loncommon::end_data_table();
 4161:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4162:     $result.='<input type="button" value="'.&mt('Save').'" '.
 4163: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4164:     if ($ctr == 0) {
 4165:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4166:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4167:                 '<span class="LC_warning">';
 4168:         if ($env{'form.submitonly'} eq 'all') {
 4169:             if (grep(/^all$/,@sections)) {
 4170:                 if (grep(/^all$/,@groups)) {
 4171:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4172:                                    $stu_status);
 4173:                 } elsif (grep(/^none$/,@groups)) {
 4174:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4175:                                    $stu_status); 
 4176:                 } else {
 4177:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4178:                                    $group_display,$stu_status);
 4179:                 }
 4180:             } elsif (grep(/^none$/,@sections)) {
 4181:                 if (grep(/^all$/,@groups)) {
 4182:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4183:                                    $stu_status);
 4184:                 } elsif (grep(/^none$/,@groups)) {
 4185:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4186:                                    $stu_status);
 4187:                 } else {
 4188:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4189:                                    $group_display,$stu_status);
 4190:                 }
 4191:             } else {
 4192:                 if (grep(/^all$/,@groups)) {
 4193:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4194:                                    $section_display,$stu_status);
 4195:                 } elsif (grep(/^none$/,@groups)) {
 4196:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4197:                                    $section_display,$stu_status);
 4198:                 } else {
 4199:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4200:                                    $section_display,$group_display,$stu_status);
 4201:                 }
 4202:             }
 4203:         } else {
 4204:             if (grep(/^all$/,@sections)) {
 4205:                 if (grep(/^all$/,@groups)) {
 4206:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4207:                                    $stu_status,$submission_status);
 4208:                 } elsif (grep(/^none$/,@groups)) {
 4209:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4210:                                    $stu_status,$submission_status);
 4211:                 } else {
 4212:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4213:                                    $group_display,$stu_status,$submission_status);
 4214:                 }
 4215:             } elsif (grep(/^none$/,@sections)) {
 4216:                 if (grep(/^all$/,@groups)) {
 4217:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4218:                                    $stu_status,$submission_status);
 4219:                 } elsif (grep(/^none$/,@groups)) {
 4220:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4221:                                    $stu_status,$submission_status);
 4222:                 } else {
 4223:                     $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.',
 4224:                                    $group_display,$stu_status,$submission_status);
 4225:                 }
 4226:             } else {
 4227:                 if (grep(/^all$/,@groups)) {
 4228: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4229: 	                           $section_display,$stu_status,$submission_status);
 4230:                 } elsif (grep(/^none$/,@groups)) {
 4231:                     $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.',
 4232:                                    $section_display,$stu_status,$submission_status);
 4233:                 } else {
 4234:                     $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.',
 4235:                                    $section_display,$group_display,$stu_status,$submission_status);
 4236:                 }
 4237:             }
 4238:         }
 4239: 	$result .= '</span><br />';
 4240:     }
 4241:     return $result;
 4242: }
 4243: 
 4244: #--- call by previous routine to display each student who satisfies submission filter. 
 4245: sub viewstudentgrade {
 4246:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4247:     my ($uname,$udom) = split(/:/,$student);
 4248:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4249:     my $submitonly = $env{'form.submitonly'};
 4250:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4251:         my %partstatus = ();
 4252:         if (ref($parts) eq 'ARRAY') {
 4253:             foreach my $apart (@{$parts}) {
 4254:                 my ($part,$type) = &split_part_type($apart);
 4255:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4256:                 $status = 'nothing' if ($status eq '');
 4257:                 $partstatus{$part}      = $status;
 4258:                 my $subkey = "resource.$part.submitted_by";
 4259:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4260:             }
 4261:             my $submitted = 0;
 4262:             my $graded = 0;
 4263:             my $incorrect = 0;
 4264:             foreach my $key (keys(%partstatus)) {
 4265:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4266:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4267:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4268: 
 4269:                 my $partid = (split(/\./,$key))[1];
 4270:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4271:                     $submitted = 0;
 4272:                 }
 4273:             }
 4274:             return if (!$submitted && ($submitonly eq 'yes' ||
 4275:                                        $submitonly eq 'incorrect' ||
 4276:                                        $submitonly eq 'graded'));
 4277:             return if (!$graded && ($submitonly eq 'graded'));
 4278:             return if (!$incorrect && $submitonly eq 'incorrect');
 4279:         }
 4280:     }
 4281:     if ($submitonly eq 'queued') {
 4282:         my ($cdom,$cnum) = split(/_/,$courseid);
 4283:         my %queue_status =
 4284:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4285:                                                     $udom,$uname);
 4286:         return if (!defined($queue_status{'gradingqueue'}));
 4287:     }
 4288:     $$ctr++;
 4289:     my %aggregates = ();
 4290:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4291: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4292: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4293: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4294: 	'\');" target="_self">'.$fullname.'</a> '.
 4295: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4296:     $student=~s/:/_/; # colon doen't work in javascript for names
 4297:     foreach my $apart (@$parts) {
 4298: 	my ($part,$type) = &split_part_type($apart);
 4299: 	my $score=$record{"resource.$part.$type"};
 4300:         $result.='<td align="center">';
 4301:         my ($aggtries,$totaltries);
 4302:         unless (exists($aggregates{$part})) {
 4303: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4304: 	    $aggtries = $totaltries;
 4305:             if ($$last_resets{$part}) {  
 4306:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4307: 					   $part);
 4308:             }
 4309:             $result.='<input type="hidden" name="'.
 4310:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4311:             $result.='<input type="hidden" name="'.
 4312:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4313:             $aggregates{$part} = 1;
 4314:         }
 4315: 	if ($type eq 'awarded') {
 4316: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4317: 	    $result.='<input type="hidden" name="'.
 4318: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4319: 	    $result.='<input type="text" name="'.
 4320: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4321:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4322: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4323: 	} elsif ($type eq 'solved') {
 4324: 	    my ($status,$foo)=split(/_/,$score,2);
 4325: 	    $status = 'nothing' if ($status eq '');
 4326: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4327: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4328: 	    $result.='&nbsp;<select name="'.
 4329: 		'GD_'.$student.'_'.$part.'_solved" '.
 4330:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4331: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4332: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4333: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4334: 	    $result.="</select>&nbsp;</td>\n";
 4335: 	} else {
 4336: 	    $result.='<input type="hidden" name="'.
 4337: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4338: 		    "\n";
 4339: 	    $result.='<input type="text" name="'.
 4340: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4341: 		'value="'.$score.'" size="4" /></td>'."\n";
 4342: 	}
 4343:     }
 4344:     $result.=&Apache::loncommon::end_data_table_row();
 4345:     return $result;
 4346: }
 4347: 
 4348: #--- change scores for all the students in a section/class
 4349: #    record does not get update if unchanged
 4350: sub editgrades {
 4351:     my ($request,$symb) = @_;
 4352:     my $toolsymb;
 4353:     if ($symb =~ /ext\.tool$/) {
 4354:         $toolsymb = $symb;
 4355:     }
 4356: 
 4357:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4358:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4359:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4360: 
 4361:     my $result= &Apache::loncommon::start_data_table().
 4362: 	&Apache::loncommon::start_data_table_header_row().
 4363: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4364: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4365:     my %scoreptr = (
 4366: 		    'correct'  =>'correct_by_override',
 4367: 		    'incorrect'=>'incorrect_by_override',
 4368: 		    'excused'  =>'excused',
 4369: 		    'ungraded' =>'ungraded_attempted',
 4370:                     'credited' =>'credit_attempted',
 4371: 		    'nothing'  => '',
 4372: 		    );
 4373:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4374: 
 4375:     my (@partid);
 4376:     my %weight = ();
 4377:     my %columns = ();
 4378:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4379: 
 4380:     my $partserror;
 4381:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4382:     if ($partserror) {
 4383:         return &navmap_errormsg();
 4384:     }
 4385:     my $header;
 4386:     while ($ctr < $env{'form.totalparts'}) {
 4387: 	my $partid = $env{'form.partid_'.$ctr};
 4388: 	push(@partid,$partid);
 4389: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4390: 	$ctr++;
 4391:     }
 4392:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4393:     my $totcolspan = 0;
 4394:     foreach my $partid (@partid) {
 4395: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4396: 	    '<th align="center">'.&mt('New Score').'</th>';
 4397: 	$columns{$partid}=2;
 4398: 	foreach my $stores (@parts) {
 4399: 	    my ($part,$type) = &split_part_type($stores);
 4400: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4401: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4402: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4403: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4404:             my $narrowtext = &mt('Tries');
 4405: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4406: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4407: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4408: 	    $columns{$partid}+=2;
 4409: 	}
 4410:         $totcolspan += $columns{$partid};
 4411:     }
 4412:     foreach my $partid (@partid) {
 4413: 	my $display_part=&get_display_part($partid,$symb);
 4414: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4415: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4416: 	    '</th>';
 4417: 
 4418:     }
 4419:     $result .= &Apache::loncommon::end_data_table_header_row().
 4420: 	&Apache::loncommon::start_data_table_header_row().
 4421: 	$header.
 4422: 	&Apache::loncommon::end_data_table_header_row();
 4423:     my @noupdate;
 4424:     my ($updateCtr,$noupdateCtr) = (1,1);
 4425:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4426: 	my $user = $env{'form.ctr'.$i};
 4427: 	my ($uname,$udom)=split(/:/,$user);
 4428: 	my %newrecord;
 4429: 	my $updateflag = 0;
 4430: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4431: 	my $canmodify = &canmodify($usec);
 4432: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4433: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4434: 	if (!$canmodify) {
 4435: 	    push(@noupdate,
 4436: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4437: 		 &mt('Not allowed to modify student')."</span></td>");
 4438: 	    next;
 4439: 	}
 4440:         my %aggregate = ();
 4441:         my $aggregateflag = 0;
 4442: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4443: 	foreach (@partid) {
 4444: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4445: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4446: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4447: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4448: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4449: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4450: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4451: 	    my $score;
 4452: 	    if ($partial eq '') {
 4453: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4454: 	    } elsif ($partial > 0) {
 4455: 		$score = 'correct_by_override';
 4456: 	    } elsif ($partial == 0) {
 4457: 		$score = 'incorrect_by_override';
 4458: 	    }
 4459: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4460: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4461: 
 4462: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4463: 		"$env{'user.name'}:$env{'user.domain'}";
 4464: 	    if ($dropMenu eq 'reset status' &&
 4465: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4466: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4467: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4468: 		$newrecord{'resource.'.$_.'.award'} = '';
 4469: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4470: 		$updateflag = 1;
 4471:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4472:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4473:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4474:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4475:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4476:                     $aggregateflag = 1;
 4477:                 }
 4478: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4479: 		$updateflag = 1;
 4480: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4481: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4482: 		$rec_update++;
 4483: 	    }
 4484: 
 4485: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4486: 		'<td align="center">'.$awarded.
 4487: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4488: 
 4489: 
 4490: 	    my $partid=$_;
 4491: 	    foreach my $stores (@parts) {
 4492: 		my ($part,$type) = &split_part_type($stores);
 4493: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4494: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4495: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4496: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4497: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4498: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4499: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4500: 		    $updateflag=1;
 4501: 		}
 4502: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4503: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4504: 	    }
 4505: 	}
 4506: 	$line.="\n";
 4507: 
 4508: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4509: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4510: 
 4511: 	if ($updateflag) {
 4512: 	    $count++;
 4513: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4514: 				    $udom,$uname);
 4515: 
 4516: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4517: 					      $cnum,$udom,$uname)) {
 4518: 		# need to figure out if should be in queue.
 4519: 		my %record =  
 4520: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4521: 					     $udom,$uname);
 4522: 		my $all_graded = 1;
 4523: 		my $none_graded = 1;
 4524: 		foreach my $part (@parts) {
 4525: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4526: 			$all_graded = 0;
 4527: 		    } else {
 4528: 			$none_graded = 0;
 4529: 		    }
 4530: 		}
 4531: 
 4532: 		if ($all_graded || $none_graded) {
 4533: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4534: 							   $symb,$cdom,$cnum,
 4535: 							   $udom,$uname);
 4536: 		}
 4537: 	    }
 4538: 
 4539: 	    $result.=&Apache::loncommon::start_data_table_row().
 4540: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4541: 		&Apache::loncommon::end_data_table_row();
 4542: 	    $updateCtr++;
 4543: 	} else {
 4544: 	    push(@noupdate,
 4545: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4546: 	    $noupdateCtr++;
 4547: 	}
 4548:         if ($aggregateflag) {
 4549:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4550: 				  $cdom,$cnum);
 4551:         }
 4552:     }
 4553:     if (@noupdate) {
 4554:         my $numcols=$totcolspan+2;
 4555: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4556: 	    '<td align="center" colspan="'.$numcols.'">'.
 4557: 	    &mt('No Changes Occurred For the Students Below').
 4558: 	    '</td>'.
 4559: 	    &Apache::loncommon::end_data_table_row();
 4560: 	foreach my $line (@noupdate) {
 4561: 	    $result.=
 4562: 		&Apache::loncommon::start_data_table_row().
 4563: 		$line.
 4564: 		&Apache::loncommon::end_data_table_row();
 4565: 	}
 4566:     }
 4567:     $result .= &Apache::loncommon::end_data_table();
 4568:     my $msg = '<p><b>'.
 4569: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4570: 	    $rec_update,$count).'</b><br />'.
 4571: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4572: 	'</b></p>';
 4573:     return $title.$msg.$result;
 4574: }
 4575: 
 4576: sub split_part_type {
 4577:     my ($partstr) = @_;
 4578:     my ($temp,@allparts)=split(/_/,$partstr);
 4579:     my $type=pop(@allparts);
 4580:     my $part=join('_',@allparts);
 4581:     return ($part,$type);
 4582: }
 4583: 
 4584: #------------- end of section for handling grading by section/class ---------
 4585: #
 4586: #----------------------------------------------------------------------------
 4587: 
 4588: 
 4589: #----------------------------------------------------------------------------
 4590: #
 4591: #-------------------------- Next few routines handles grading by csv upload
 4592: #
 4593: #--- Javascript to handle csv upload
 4594: sub csvupload_javascript_reverse_associate {
 4595:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4596:     my $error2=&mt('You need to specify at least one grading field');
 4597:   &js_escape(\$error1);
 4598:   &js_escape(\$error2);
 4599:   return(<<ENDPICK);
 4600:   function verify(vf) {
 4601:     var foundsomething=0;
 4602:     var founduname=0;
 4603:     var foundID=0;
 4604:     var foundclicker=0;
 4605:     for (i=0;i<=vf.nfields.value;i++) {
 4606:       tw=eval('vf.f'+i+'.selectedIndex');
 4607:       if (i==0 && tw!=0) { foundID=1; }
 4608:       if (i==1 && tw!=0) { founduname=1; }
 4609:       if (i==2 && tw!=0) { foundclicker=1; }
 4610:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4611:     }
 4612:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4613: 	alert('$error1');
 4614: 	return;
 4615:     }
 4616:     if (foundsomething==0) {
 4617: 	alert('$error2');
 4618: 	return;
 4619:     }
 4620:     vf.submit();
 4621:   }
 4622:   function flip(vf,tf) {
 4623:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4624:     var i;
 4625:     for (i=0;i<=vf.nfields.value;i++) {
 4626:       //can not pick the same destination field for both name and domain
 4627:       if (((i ==0)||(i ==1)) && 
 4628:           ((tf==0)||(tf==1)) && 
 4629:           (i!=tf) &&
 4630:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4631:         eval('vf.f'+i+'.selectedIndex=0;')
 4632:       }
 4633:     }
 4634:   }
 4635: ENDPICK
 4636: }
 4637: 
 4638: sub csvupload_javascript_forward_associate {
 4639:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4640:     my $error2=&mt('You need to specify at least one grading field');
 4641:   &js_escape(\$error1);
 4642:   &js_escape(\$error2);
 4643:   return(<<ENDPICK);
 4644:   function verify(vf) {
 4645:     var foundsomething=0;
 4646:     var founduname=0;
 4647:     var foundID=0;
 4648:     var foundclicker=0;
 4649:     for (i=0;i<=vf.nfields.value;i++) {
 4650:       tw=eval('vf.f'+i+'.selectedIndex');
 4651:       if (tw==1) { foundID=1; }
 4652:       if (tw==2) { founduname=1; }
 4653:       if (tw==3) { foundclicker=1; }
 4654:       if (tw>4) { foundsomething=1; }
 4655:     }
 4656:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4657: 	alert('$error1');
 4658: 	return;
 4659:     }
 4660:     if (foundsomething==0) {
 4661: 	alert('$error2');
 4662: 	return;
 4663:     }
 4664:     vf.submit();
 4665:   }
 4666:   function flip(vf,tf) {
 4667:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4668:     var i;
 4669:     //can not pick the same destination field twice
 4670:     for (i=0;i<=vf.nfields.value;i++) {
 4671:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4672:         eval('vf.f'+i+'.selectedIndex=0;')
 4673:       }
 4674:     }
 4675:   }
 4676: ENDPICK
 4677: }
 4678: 
 4679: sub csvuploadmap_header {
 4680:     my ($request,$symb,$datatoken,$distotal)= @_;
 4681:     my $javascript;
 4682:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4683: 	$javascript=&csvupload_javascript_reverse_associate();
 4684:     } else {
 4685: 	$javascript=&csvupload_javascript_forward_associate();
 4686:     }
 4687: 
 4688:     $symb = &Apache::lonenc::check_encrypt($symb);
 4689:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4690:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4691:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4692:     my $reverse=&mt("Reverse Association");
 4693:     $request->print(<<ENDPICK);
 4694: <br />
 4695: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4696: <input type="hidden" name="associate"  value="" />
 4697: <input type="hidden" name="phase"      value="three" />
 4698: <input type="hidden" name="datatoken"  value="$datatoken" />
 4699: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4700: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4701: <input type="hidden" name="upfile_associate" 
 4702:                                        value="$env{'form.upfile_associate'}" />
 4703: <input type="hidden" name="symb"       value="$symb" />
 4704: <input type="hidden" name="command"    value="csvuploadoptions" />
 4705: <hr />
 4706: ENDPICK
 4707:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4708:     return '';
 4709: 
 4710: }
 4711: 
 4712: sub csvupload_fields {
 4713:     my ($symb,$errorref) = @_;
 4714:     my $toolsymb;
 4715:     if ($symb =~ /ext\.tool$/) {
 4716:         $toolsymb = $symb;
 4717:     }
 4718:     my (@parts) = &getpartlist($symb,$errorref);
 4719:     if (ref($errorref)) {
 4720:         if ($$errorref) {
 4721:             return;
 4722:         }
 4723:     }
 4724: 
 4725:     my @fields=(['ID','Student/Employee ID'],
 4726: 		['username','Student Username'],
 4727: 		['clicker','Clicker ID'],
 4728: 		['domain','Student Domain']);
 4729:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4730:     foreach my $part (sort(@parts)) {
 4731: 	my @datum;
 4732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4733: 	my $name=$part;
 4734: 	if (!$display) { $display = $name; }
 4735: 	@datum=($name,$display);
 4736: 	if ($name=~/^stores_(.*)_awarded/) {
 4737: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4738: 	}
 4739: 	push(@fields,\@datum);
 4740:     }
 4741:     return (@fields);
 4742: }
 4743: 
 4744: sub csvuploadmap_footer {
 4745:     my ($request,$i,$keyfields) =@_;
 4746:     my $buttontext = &mt('Assign Grades');
 4747:     $request->print(<<ENDPICK);
 4748: </table>
 4749: <input type="hidden" name="nfields" value="$i" />
 4750: <input type="hidden" name="keyfields" value="$keyfields" />
 4751: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4752: </form>
 4753: ENDPICK
 4754: }
 4755: 
 4756: sub checkforfile_js {
 4757:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4758:     &js_escape(\$alertmsg);
 4759:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4760:     function checkUpload(formname) {
 4761: 	if (formname.upfile.value == "") {
 4762: 	    alert("$alertmsg");
 4763: 	    return false;
 4764: 	}
 4765: 	formname.submit();
 4766:     }
 4767: CSVFORMJS
 4768:     return $result;
 4769: }
 4770: 
 4771: sub upcsvScores_form {
 4772:     my ($request,$symb) = @_;
 4773:     if (!$symb) {return '';}
 4774:     my $result=&checkforfile_js();
 4775:     $result.=&Apache::loncommon::start_data_table().
 4776:              &Apache::loncommon::start_data_table_header_row().
 4777:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4778:              &Apache::loncommon::end_data_table_header_row().
 4779:              &Apache::loncommon::start_data_table_row().'<td>';
 4780:     my $upload=&mt("Upload Scores");
 4781:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4782:     my $ignore=&mt('Ignore First Line');
 4783:     $symb = &Apache::lonenc::check_encrypt($symb);
 4784:     $result.=<<ENDUPFORM;
 4785: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4786: <input type="hidden" name="symb" value="$symb" />
 4787: <input type="hidden" name="command" value="csvuploadmap" />
 4788: $upfile_select
 4789: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4790: </form>
 4791: ENDUPFORM
 4792:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4793:                            &mt("How do I create a CSV file from a spreadsheet")).
 4794:              '</td>'.
 4795:             &Apache::loncommon::end_data_table_row().
 4796:             &Apache::loncommon::end_data_table();
 4797:     return $result;
 4798: }
 4799: 
 4800: 
 4801: sub csvuploadmap {
 4802:     my ($request,$symb) = @_;
 4803:     if (!$symb) {return '';}
 4804: 
 4805:     my $datatoken;
 4806:     if (!$env{'form.datatoken'}) {
 4807: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4808:     } else {
 4809: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4810:         if ($datatoken ne '') {
 4811: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4812:         }
 4813:     }
 4814:     my @records=&Apache::loncommon::upfile_record_sep();
 4815:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4816:     my ($i,$keyfields);
 4817:     if (@records) {
 4818:         my $fieldserror;
 4819: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4820:         if ($fieldserror) {
 4821:             $request->print(&navmap_errormsg());
 4822:             return;
 4823:         }
 4824: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4825: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4826: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4827: 							  \@fields);
 4828: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4829: 	    chop($keyfields);
 4830: 	} else {
 4831: 	    unshift(@fields,['none','']);
 4832: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4833: 							    \@fields);
 4834:             foreach my $rec (@records) {
 4835:                 my %temp = &Apache::loncommon::record_sep($rec);
 4836:                 if (%temp) {
 4837:                     $keyfields=join(',',sort(keys(%temp)));
 4838:                     last;
 4839:                 }
 4840:             }
 4841: 	}
 4842:     }
 4843:     &csvuploadmap_footer($request,$i,$keyfields);
 4844: 
 4845:     return '';
 4846: }
 4847: 
 4848: sub csvuploadoptions {
 4849:     my ($request,$symb)= @_;
 4850:     my $overwrite=&mt('Overwrite any existing score');
 4851:     $request->print(<<ENDPICK);
 4852: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4853: <input type="hidden" name="command"    value="csvuploadassign" />
 4854: <p>
 4855: <label>
 4856:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4857:    $overwrite
 4858: </label>
 4859: </p>
 4860: ENDPICK
 4861:     my %fields=&get_fields();
 4862:     if (!defined($fields{'domain'})) {
 4863: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4864: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4865:     }
 4866:     foreach my $key (sort(keys(%env))) {
 4867: 	if ($key !~ /^form\.(.*)$/) { next; }
 4868: 	my $cleankey=$1;
 4869: 	if ($cleankey eq 'command') { next; }
 4870: 	$request->print('<input type="hidden" name="'.$cleankey.
 4871: 			'"  value="'.$env{$key}.'" />'."\n");
 4872:     }
 4873:     # FIXME do a check for any duplicated user ids...
 4874:     # FIXME do a check for any invalid user ids?...
 4875:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4876: <hr /></form>'."\n");
 4877:     return '';
 4878: }
 4879: 
 4880: sub get_fields {
 4881:     my %fields;
 4882:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4883:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4884: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4885: 	    if ($env{'form.f'.$i} ne 'none') {
 4886: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4887: 	    }
 4888: 	} else {
 4889: 	    if ($env{'form.f'.$i} ne 'none') {
 4890: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4891: 	    }
 4892: 	}
 4893:     }
 4894:     return %fields;
 4895: }
 4896: 
 4897: sub csvuploadassign {
 4898:     my ($request,$symb) = @_;
 4899:     if (!$symb) {return '';}
 4900:     my $error_msg = '';
 4901:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4902:     if ($datatoken ne '') { 
 4903:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4904:     }
 4905:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4906:     my %fields=&get_fields();
 4907:     my $courseid=$env{'request.course.id'};
 4908:     my ($classlist) = &getclasslist('all',0);
 4909:     my @notallowed;
 4910:     my @skipped;
 4911:     my @warnings;
 4912:     my $countdone=0;
 4913:     foreach my $grade (@gradedata) {
 4914: 	my %entries=&Apache::loncommon::record_sep($grade);
 4915: 	my $domain;
 4916: 	if ($entries{$fields{'domain'}}) {
 4917: 	    $domain=$entries{$fields{'domain'}};
 4918: 	} else {
 4919: 	    $domain=$env{'form.default_domain'};
 4920: 	}
 4921: 	$domain=~s/\s//g;
 4922: 	my $username=$entries{$fields{'username'}};
 4923: 	$username=~s/\s//g;
 4924: 	if (!$username) {
 4925: 	    my $id=$entries{$fields{'ID'}};
 4926: 	    $id=~s/\s//g;
 4927:             if ($id ne '') {
 4928: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4929: 	        $username=$ids{$id};
 4930:             } else {
 4931:                 if ($entries{$fields{'clicker'}}) {
 4932:                     my $clicker = $entries{$fields{'clicker'}};
 4933:                     $clicker=~s/\s//g;
 4934:                     if ($clicker ne '') {
 4935:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4936:                         if ($clickers{$clicker} ne '') {  
 4937:                             my $match = 0;
 4938:                             my @inclass;
 4939:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4940:                                 if (exists($$classlist{"$poss:$domain"})) {
 4941:                                     $username = $poss;
 4942:                                     push(@inclass,$poss);
 4943:                                     $match ++;
 4944:                                     
 4945:                                 }
 4946:                             }
 4947:                             if ($match > 1) {
 4948:                                 undef($username); 
 4949:                                 $request->print('<p class="LC_warning">'.
 4950:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4951:                                                 $clicker,join(', ',@inclass)).'</p>');
 4952:                             }
 4953:                         }
 4954:                     }
 4955:                 }
 4956:             }
 4957: 	}
 4958: 	if (!exists($$classlist{"$username:$domain"})) {
 4959: 	    my $id=$entries{$fields{'ID'}};
 4960: 	    $id=~s/\s//g;
 4961:             my $clicker = $entries{$fields{'clicker'}};
 4962:             $clicker=~s/\s//g;
 4963:             if ($clicker) {
 4964:                 push(@skipped,"$clicker:$domain");
 4965: 	    } elsif ($id) {
 4966: 		push(@skipped,"$id:$domain");
 4967: 	    } else {
 4968: 		push(@skipped,"$username:$domain");
 4969: 	    }
 4970: 	    next;
 4971: 	}
 4972: 	my $usec=$classlist->{"$username:$domain"}[5];
 4973: 	if (!&canmodify($usec)) {
 4974: 	    push(@notallowed,"$username:$domain");
 4975: 	    next;
 4976: 	}
 4977: 	my %points;
 4978: 	my %grades;
 4979: 	foreach my $dest (keys(%fields)) {
 4980: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4981: 		$dest eq 'domain') { next; }
 4982: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4983: 	    if ($dest=~/stores_(.*)_points/) {
 4984: 		my $part=$1;
 4985: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4986: 					      $symb,$domain,$username);
 4987:                 if ($wgt) {
 4988:                     $entries{$fields{$dest}}=~s/\s//g;
 4989:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4990:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4991:                                           : 'correct_by_override';
 4992:                     if ($pcr>1) {
 4993:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4994:                     }
 4995:                     $grades{"resource.$part.awarded"}=$pcr;
 4996:                     $grades{"resource.$part.solved"}=$award;
 4997:                     $points{$part}=1;
 4998:                 } else {
 4999:                     $error_msg = "<br />" .
 5000:                         &mt("Some point values were assigned"
 5001:                             ." for problems with a weight "
 5002:                             ."of zero. These values were "
 5003:                             ."ignored.");
 5004:                 }
 5005: 	    } else {
 5006: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5007: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5008: 		my $store_key=$dest;
 5009: 		$store_key=~s/^stores/resource/;
 5010: 		$store_key=~s/_/\./g;
 5011: 		$grades{$store_key}=$entries{$fields{$dest}};
 5012: 	    }
 5013: 	}
 5014: 	if (! %grades) {
 5015:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5016:         } else {
 5017: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5018: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5019: 					   $env{'request.course.id'},
 5020: 					   $domain,$username);
 5021: 	   if ($result eq 'ok') {
 5022: # Successfully stored
 5023: 	      $request->print('.');
 5024: # Remove from grading queue
 5025:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5026:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5027:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5028:                                              $domain,$username);
 5029:               $countdone++;
 5030:            } else {
 5031: 	      $request->print("<p><span class=\"LC_error\">".
 5032:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5033:                                   "$username:$domain",$result)."</span></p>");
 5034: 	   }
 5035: 	   $request->rflush();
 5036:         }
 5037:     }
 5038:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5039:     if (@warnings) {
 5040:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5041:         $request->print(join(', ',@warnings));
 5042:     }
 5043:     if (@skipped) {
 5044: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5045:         $request->print(join(', ',@skipped));
 5046:     }
 5047:     if (@notallowed) {
 5048: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5049: 	$request->print(join(', ',@notallowed));
 5050:     }
 5051:     $request->print("<br />\n");
 5052:     return $error_msg;
 5053: }
 5054: #------------- end of section for handling csv file upload ---------
 5055: #
 5056: #-------------------------------------------------------------------
 5057: #
 5058: #-------------- Next few routines handle grading by page/sequence
 5059: #
 5060: #--- Select a page/sequence and a student to grade
 5061: sub pickStudentPage {
 5062:     my ($request,$symb) = @_;
 5063: 
 5064:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5065:     &js_escape(\$alertmsg);
 5066:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5067: 
 5068: function checkPickOne(formname) {
 5069:     if (radioSelection(formname.student) == null) {
 5070: 	alert("$alertmsg");
 5071: 	return;
 5072:     }
 5073:     ptr = pullDownSelection(formname.selectpage);
 5074:     formname.page.value = formname["page"+ptr].value;
 5075:     formname.title.value = formname["title"+ptr].value;
 5076:     formname.submit();
 5077: }
 5078: 
 5079: LISTJAVASCRIPT
 5080:     &commonJSfunctions($request);
 5081: 
 5082:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5083:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5084:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5085:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5086: 
 5087:     my $result='<h3><span class="LC_info">&nbsp;'.
 5088: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5089: 
 5090:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5091:     my $map_error;
 5092:     my ($titles,$symbx) = &getSymbMap($map_error);
 5093:     if ($map_error) {
 5094:         $request->print(&navmap_errormsg());
 5095:         return; 
 5096:     }
 5097:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5098: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5099: #    my $type=($curpage =~ /\.(page|sequence)/);
 5100: 
 5101:     # Collection of hidden fields
 5102:     my $ctr=0;
 5103:     foreach (@$titles) {
 5104:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5105:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5106:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5107:         $ctr++;
 5108:     }
 5109:     $result.='<input type="hidden" name="page" />'."\n".
 5110:         '<input type="hidden" name="title" />'."\n";
 5111: 
 5112:     $result.=&build_section_inputs();
 5113:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5114:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5115: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5116: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5117: 
 5118:     # Show grading options
 5119:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5120:     my $select = '<select name="selectpage">'."\n";
 5121:     $ctr=0;
 5122:     foreach (@$titles) {
 5123: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5124: 	$select.='<option value="'.$ctr.'"'.
 5125: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5126: 	    '>'.$showtitle.'</option>'."\n";
 5127: 	$ctr++;
 5128:     }
 5129:     $select.= '</select>';
 5130: 
 5131:     $result.=
 5132:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5133:        .$select
 5134:        .&Apache::lonhtmlcommon::row_closure();
 5135: 
 5136:     $result.=
 5137:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5138:        .'<label><input type="radio" name="vProb" value="no"'
 5139:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5140:        .'<label><input type="radio" name="vProb" value="yes" />'
 5141:            .&mt('yes').'</label>'."\n"
 5142:        .&Apache::lonhtmlcommon::row_closure();
 5143: 
 5144:     $result.=
 5145:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5146:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5147:            .&mt('none').' </label>'."\n"
 5148:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5149:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5150:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5151:            .&mt('all submissions with details').' </label>'
 5152:        .&Apache::lonhtmlcommon::row_closure();
 5153:     
 5154:     $result.=
 5155:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5156:        .'<input type="text" name="CODE" value="" />'
 5157:        .&Apache::lonhtmlcommon::row_closure(1)
 5158:        .&Apache::lonhtmlcommon::end_pick_box();
 5159: 
 5160:     # Show list of students to select for grading
 5161:     $result.='<br /><input type="button" '.
 5162:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5163: 
 5164:     $request->print($result);
 5165: 
 5166:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5167: 	&Apache::loncommon::start_data_table().
 5168: 	&Apache::loncommon::start_data_table_header_row().
 5169: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5170: 	'<th>'.&nameUserString('header').'</th>'.
 5171: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5172: 	'<th>'.&nameUserString('header').'</th>'.
 5173: 	&Apache::loncommon::end_data_table_header_row();
 5174:  
 5175:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5176:     my $ptr = 1;
 5177:     foreach my $student (sort 
 5178: 			 {
 5179: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5180: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5181: 			     }
 5182: 			     return $a cmp $b;
 5183: 			 } (keys(%$fullname))) {
 5184: 	my ($uname,$udom) = split(/:/,$student);
 5185: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5186:                                   : '</td>');
 5187: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5188: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5189: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5190: 	$studentTable.=
 5191: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5192:                          : '');
 5193: 	$ptr++;
 5194:     }
 5195:     if ($ptr%2 == 0) {
 5196: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5197: 	    &Apache::loncommon::end_data_table_row();
 5198:     }
 5199:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5200:     $studentTable.='<input type="button" '.
 5201:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5202: 
 5203:     $request->print($studentTable);
 5204: 
 5205:     return '';
 5206: }
 5207: 
 5208: sub getSymbMap {
 5209:     my ($map_error) = @_;
 5210:     my $navmap = Apache::lonnavmaps::navmap->new();
 5211:     unless (ref($navmap)) {
 5212:         if (ref($map_error)) {
 5213:             $$map_error = 'navmap';
 5214:         }
 5215:         return;
 5216:     }
 5217:     my %symbx = ();
 5218:     my @titles = ();
 5219:     my $minder = 0;
 5220: 
 5221:     # Gather every sequence that has problems.
 5222:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5223: 					       1,0,1);
 5224:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5225: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5226: 	    my $title = $minder.'.'.
 5227: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5228: 	    push(@titles, $title); # minder in case two titles are identical
 5229: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5230: 	    $minder++;
 5231: 	}
 5232:     }
 5233:     return \@titles,\%symbx;
 5234: }
 5235: 
 5236: #
 5237: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5238: sub displayPage {
 5239:     my ($request,$symb) = @_;
 5240:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5241:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5242:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5243:     my $pageTitle = $env{'form.page'};
 5244:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5245:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5246:     my $usec=$classlist->{$env{'form.student'}}[5];
 5247: 
 5248:     #need to make sure we have the correct data for later EXT calls, 
 5249:     #thus invalidate the cache
 5250:     &Apache::lonnet::devalidatecourseresdata(
 5251:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5252:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5253:     &Apache::lonnet::clear_EXT_cache_status();
 5254: 
 5255:     if (!&canview($usec)) {
 5256:         $request->print(
 5257:             '<span class="LC_warning">'.
 5258:             &mt('Unable to view requested student. ([_1])',
 5259:                     $env{'form.student'}).
 5260:             '</span>');
 5261:         return;
 5262:     }
 5263:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5264:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5265: 	'</h3>'."\n";
 5266:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5267:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5268: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5269:     } else {
 5270: 	delete($env{'form.CODE'});
 5271:     }
 5272:     &sub_page_js($request);
 5273:     $request->print($result);
 5274: 
 5275:     my $navmap = Apache::lonnavmaps::navmap->new();
 5276:     unless (ref($navmap)) {
 5277:         $request->print(&navmap_errormsg());
 5278:         return;
 5279:     }
 5280:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5281:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5282:     if (!$map) {
 5283: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5284: 	return; 
 5285:     }
 5286:     my $iterator = $navmap->getIterator($map->map_start(),
 5287: 					$map->map_finish());
 5288: 
 5289:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5290: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5291: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5292: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5293: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5294: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5295: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5296: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5297: 
 5298:     if (defined($env{'form.CODE'})) {
 5299: 	$studentTable.=
 5300: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5301:     }
 5302:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5303: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5304: 
 5305:     $studentTable.='&nbsp;<span class="LC_info">'.
 5306:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5307:         '</span>'."\n".
 5308: 	&Apache::loncommon::start_data_table().
 5309: 	&Apache::loncommon::start_data_table_header_row().
 5310: 	'<th>'.&mt('Prob.').'</th>'.
 5311: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5312: 	&Apache::loncommon::end_data_table_header_row();
 5313: 
 5314:     &Apache::lonxml::clear_problem_counter();
 5315:     my ($depth,$question,$prob) = (1,1,1);
 5316:     $iterator->next(); # skip the first BEGIN_MAP
 5317:     my $curRes = $iterator->next(); # for "current resource"
 5318:     while ($depth > 0) {
 5319:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5320:         if($curRes == $iterator->END_MAP) { $depth--; }
 5321: 
 5322:         if (ref($curRes) && $curRes->is_gradable()) {
 5323: 	    my $parts = $curRes->parts();
 5324:             my $title = $curRes->compTitle();
 5325: 	    my $symbx = $curRes->symb();
 5326:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5327: 	    $studentTable.=
 5328: 		&Apache::loncommon::start_data_table_row().
 5329: 		'<td align="center" valign="top" >'.$prob.
 5330: 		(scalar(@{$parts}) == 1 ? '' 
 5331: 		                        : '<br />('.&mt('[_1]parts',
 5332: 							scalar(@{$parts}).'&nbsp;').')'
 5333: 		 ).
 5334: 		 '</td>';
 5335: 	    $studentTable.='<td valign="top">';
 5336: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5337:             if ($is_tool) {
 5338:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5339:             } else {
 5340: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5341: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5342: 					         undef,'both',\%form);
 5343: 	        } else {
 5344: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5345: 		    $companswer =~ s|<form(.*?)>||g;
 5346: 		    $companswer =~ s|</form>||g;
 5347: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5348: #		        $companswer =~ s/$1/ /ms;
 5349: #		        $request->print('match='.$1."<br />\n");
 5350: #		    }
 5351: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5352: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5353: 		}
 5354: 	    }
 5355: 
 5356: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5357: 
 5358: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5359: 		if ($record{'version'} eq '') {
 5360:                     my $msg = &mt('No recorded submission for this problem.');
 5361:                     if ($is_tool) {
 5362:                         $msg = &mt('No recorded transactions for this external tool');
 5363:                     }
 5364: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5365: 		} else {
 5366: 		    my %responseType = ();
 5367: 		    foreach my $partid (@{$parts}) {
 5368: 			my @responseIds =$curRes->responseIds($partid);
 5369: 			my @responseType =$curRes->responseType($partid);
 5370: 			my %responseIds;
 5371: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5372: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5373: 			}
 5374: 			$responseType{$partid} = \%responseIds;
 5375: 		    }
 5376: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5377: 		}
 5378: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5379: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5380:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5381: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5382: 									$env{'request.course.id'},
 5383: 									'','.submission',undef,
 5384:                                                                         $usec,$identifier);
 5385:  
 5386: 	    }
 5387: 	    if (&canmodify($usec)) {
 5388:             $studentTable.=&gradeBox_start();
 5389: 		foreach my $partid (@{$parts}) {
 5390: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5391: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5392: 		    $question++;
 5393: 		}
 5394:             $studentTable.=&gradeBox_end();
 5395: 		$prob++;
 5396: 	    }
 5397: 	    $studentTable.='</td></tr>';
 5398: 
 5399: 	}
 5400:         $curRes = $iterator->next();
 5401:     }
 5402: 
 5403:     $studentTable.=
 5404:         '</table>'."\n".
 5405:         '<input type="button" value="'.&mt('Save').'" '.
 5406:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5407:         '</form>'."\n";
 5408:     $request->print($studentTable);
 5409: 
 5410:     return '';
 5411: }
 5412: 
 5413: sub displaySubByDates {
 5414:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5415:     my $isCODE=0;
 5416:     my $isTask = ($symb =~/\.task$/);
 5417:     my $is_tool = ($symb =~/\.tool$/);
 5418:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5419:     my $studentTable=&Apache::loncommon::start_data_table().
 5420: 	&Apache::loncommon::start_data_table_header_row().
 5421: 	'<th>'.&mt('Date/Time').'</th>'.
 5422: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5423:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5424: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5425: 	'<th>'.&mt('Status').'</th>'.
 5426: 	&Apache::loncommon::end_data_table_header_row();
 5427:     my ($version);
 5428:     my %mark;
 5429:     my %orders;
 5430:     $mark{'correct_by_student'} = $checkIcon;
 5431:     if (!exists($$record{'1:timestamp'})) {
 5432:         if ($is_tool) {
 5433:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5434:         } else {
 5435:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5436:         }
 5437:     }
 5438: 
 5439:     my $interaction;
 5440:     my $no_increment = 1;
 5441:     my (%lastrndseed,%lasttype);
 5442:     for ($version=1;$version<=$$record{'version'};$version++) {
 5443: 	my $timestamp = 
 5444: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5445: 	if (exists($$record{$version.':resource.0.version'})) {
 5446: 	    $interaction = $$record{$version.':resource.0.version'};
 5447: 	}
 5448:         if ($isTask && $env{'form.previousversion'}) {
 5449:             next unless ($interaction == $env{'form.previousversion'});
 5450:         }
 5451: 	my $where = ($isTask ? "$version:resource.$interaction"
 5452: 		             : "$version:resource");
 5453: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5454: 	    '<td>'.$timestamp.'</td>';
 5455: 	if ($isCODE) {
 5456: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5457: 	}
 5458:         if ($isTask) {
 5459:             $studentTable.='<td>'.$interaction.'</td>';
 5460:         }
 5461: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5462: 	my @displaySub = ();
 5463: 	foreach my $partid (@{$parts}) {
 5464:             my ($hidden,$type);
 5465:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5466:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5467:                 $hidden = 1;
 5468:             }
 5469:             my @matchKey;
 5470:             if ($isTask) {
 5471:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5472:             } elsif ($is_tool) {
 5473:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5474:             } else {
 5475:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5476:             }
 5477: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5478: 	    my $display_part=&get_display_part($partid,$symb);
 5479: 	    foreach my $matchKey (@matchKey) {
 5480: 		if (exists($$record{$version.':'.$matchKey}) &&
 5481: 		    $$record{$version.':'.$matchKey} ne '') {
 5482:                     if ($is_tool) {
 5483:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5484:                     } else {
 5485: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5486: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5487:                         $displaySub[0].='<span class="LC_nobreak">';
 5488:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5489:                                        .' <span class="LC_internal_info">'
 5490:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5491:                                        .'</span>'
 5492:                                        .' <b>';
 5493:                         if ($hidden) {
 5494:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5495:                         } else {
 5496:                             my ($trial,$rndseed,$newvariation);
 5497:                             if ($type eq 'randomizetry') {
 5498:                                 $trial = $$record{"$where.$partid.tries"};
 5499:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5500:                             }
 5501: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5502: 			        $displaySub[0].=&mt('Trial not counted');
 5503: 		            } else {
 5504: 			        $displaySub[0].=&mt('Trial: [_1]',
 5505: 					        $$record{"$where.$partid.tries"});
 5506:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5507:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5508:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5509:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5510:                                     }
 5511:                                 }
 5512:                                 $lastrndseed{$partid} = $rndseed;
 5513:                                 $lasttype{$partid} = $type;
 5514: 		            }
 5515: 		            my $responseType=($isTask ? 'Task'
 5516:                                               : $responseType->{$partid}->{$responseId});
 5517: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5518: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5519: 			        $orders{$partid}->{$responseId}=
 5520: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5521:                                                $no_increment,$type,$trial,$rndseed);
 5522: 		            }
 5523: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5524: 		            $displaySub[0].='&nbsp; '.
 5525: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5526:                         }
 5527:                     }
 5528: 		}
 5529: 	    }
 5530: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5531: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5532: 				    $$record{"$where.$partid.checkedin"},
 5533: 				    $$record{"$where.$partid.checkedin.slot"}).
 5534: 					'<br />';
 5535: 	    }
 5536: 	    if (exists $$record{"$where.$partid.award"}) {
 5537: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5538: 		    lc($$record{"$where.$partid.award"}).' '.
 5539: 		    $mark{$$record{"$where.$partid.solved"}}.
 5540: 		    '<br />';
 5541: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5542: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5543: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5544: 		}
 5545: 	    }
 5546: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5547: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5548: 		unless ($is_tool) {
 5549: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5550: 		}
 5551: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5552: 		$displaySub[2].=
 5553: 		    $$record{"$version:resource.$partid.regrader"};
 5554:                 unless ($is_tool) {
 5555: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5556:                 }
 5557: 	    }
 5558: 	}
 5559: 	# needed because old essay regrader has not parts info
 5560: 	if (exists $$record{"$version:resource.regrader"}) {
 5561: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5562: 	}
 5563: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5564: 	if ($displaySub[2]) {
 5565: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5566: 	}
 5567: 	$studentTable.='&nbsp;</td>'.
 5568: 	    &Apache::loncommon::end_data_table_row();
 5569:     }
 5570:     $studentTable.=&Apache::loncommon::end_data_table();
 5571:     return $studentTable;
 5572: }
 5573: 
 5574: sub updateGradeByPage {
 5575:     my ($request,$symb) = @_;
 5576: 
 5577:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5578:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5579:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5580:     my $pageTitle = $env{'form.page'};
 5581:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5582:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5583:     my $usec=$classlist->{$env{'form.student'}}[5];
 5584:     if (!&canmodify($usec)) {
 5585: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5586: 	return;
 5587:     }
 5588:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5589:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5590: 	'</h3>'."\n";
 5591: 
 5592:     $request->print($result);
 5593: 
 5594: 
 5595:     my $navmap = Apache::lonnavmaps::navmap->new();
 5596:     unless (ref($navmap)) {
 5597:         $request->print(&navmap_errormsg());
 5598:         return;
 5599:     }
 5600:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5601:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5602:     if (!$map) {
 5603: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5604: 	return; 
 5605:     }
 5606:     my $iterator = $navmap->getIterator($map->map_start(),
 5607: 					$map->map_finish());
 5608: 
 5609:     my $studentTable=
 5610: 	&Apache::loncommon::start_data_table().
 5611: 	&Apache::loncommon::start_data_table_header_row().
 5612: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5613: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5614: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5615: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5616: 	&Apache::loncommon::end_data_table_header_row();
 5617: 
 5618:     $iterator->next(); # skip the first BEGIN_MAP
 5619:     my $curRes = $iterator->next(); # for "current resource"
 5620:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5621:     while ($depth > 0) {
 5622:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5623:         if($curRes == $iterator->END_MAP) { $depth--; }
 5624: 
 5625:         if (ref($curRes) && $curRes->is_problem()) {
 5626: 	    my $parts = $curRes->parts();
 5627:             my $title = $curRes->compTitle();
 5628: 	    my $symbx = $curRes->symb();
 5629: 	    $studentTable.=
 5630: 		&Apache::loncommon::start_data_table_row().
 5631: 		'<td align="center" valign="top" >'.$prob.
 5632: 		(scalar(@{$parts}) == 1 ? '' 
 5633:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5634: 		.')').'</td>';
 5635: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5636: 
 5637: 	    my %newrecord=();
 5638: 	    my @displayPts=();
 5639:             my %aggregate = ();
 5640:             my $aggregateflag = 0;
 5641:             if ($env{'form.HIDE'.$prob}) {
 5642:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5643:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5644:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5645:                 $hideflag += $numchgs;
 5646:             }
 5647: 	    foreach my $partid (@{$parts}) {
 5648: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5649: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5650: 
 5651: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5652: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5653: 		my $partial = $newpts/$wgt;
 5654: 		my $score;
 5655: 		if ($partial > 0) {
 5656: 		    $score = 'correct_by_override';
 5657: 		} elsif ($newpts ne '') { #empty is taken as 0
 5658: 		    $score = 'incorrect_by_override';
 5659: 		}
 5660: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5661: 		if ($dropMenu eq 'excused') {
 5662: 		    $partial = '';
 5663: 		    $score = 'excused';
 5664: 		} elsif ($dropMenu eq 'reset status'
 5665: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5666: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5667: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5668: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5669: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5670: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5671: 		    $changeflag++;
 5672: 		    $newpts = '';
 5673:                     
 5674:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5675:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5676:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5677:                     if ($aggtries > 0) {
 5678:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5679:                         $aggregateflag = 1;
 5680:                     }
 5681: 		}
 5682: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5683: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5684: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5685: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5686: 		    '&nbsp;<br />';
 5687: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5688: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5689: 		    '&nbsp;<br />';
 5690: 		$question++;
 5691: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5692: 
 5693: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5694: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5695: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5696: 		    if (scalar(keys(%newrecord)) > 0);
 5697: 
 5698: 		$changeflag++;
 5699: 	    }
 5700: 	    if (scalar(keys(%newrecord)) > 0) {
 5701: 		my %record = 
 5702: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5703: 					     $udom,$uname);
 5704: 
 5705: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5706: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5707: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5708: 		    $newrecord{'resource.CODE'} = '';
 5709: 		}
 5710: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5711: 					$udom,$uname);
 5712: 		%record = &Apache::lonnet::restore($symbx,
 5713: 						   $env{'request.course.id'},
 5714: 						   $udom,$uname);
 5715: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5716: 					     $cdom,$cnum,$udom,$uname);
 5717: 	    }
 5718: 	    
 5719:             if ($aggregateflag) {
 5720:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5721:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5722:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5723:             }
 5724: 
 5725: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5726: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5727: 		&Apache::loncommon::end_data_table_row();
 5728: 
 5729: 	    $prob++;
 5730: 	}
 5731:         $curRes = $iterator->next();
 5732:     }
 5733: 
 5734:     $studentTable.=&Apache::loncommon::end_data_table();
 5735:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5736: 		  &mt('The scores were changed for [quant,_1,problem].',
 5737: 		  $changeflag).'<br />');
 5738:     my $hidemsg=($hideflag == 0 ? '' :
 5739:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5740:                      $hideflag).'<br />');
 5741:     $request->print($hidemsg.$grademsg.$studentTable);
 5742: 
 5743:     return '';
 5744: }
 5745: 
 5746: #-------- end of section for handling grading by page/sequence ---------
 5747: #
 5748: #-------------------------------------------------------------------
 5749: 
 5750: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5751: #
 5752: #------ start of section for handling grading by page/sequence ---------
 5753: 
 5754: =pod
 5755: 
 5756: =head1 Bubble sheet grading routines
 5757: 
 5758:   For this documentation:
 5759: 
 5760:    'scanline' refers to the full line of characters
 5761:    from the file that we are parsing that represents one entire sheet
 5762: 
 5763:    'bubble line' refers to the data
 5764:    representing the line of bubbles that are on the physical bubblesheet
 5765: 
 5766: 
 5767: The overall process is that a scanned in bubblesheet data is uploaded
 5768: into a course. When a user wants to grade, they select a
 5769: sequence/folder of resources, a file of bubblesheet info, and pick
 5770: one of the predefined configurations for what each scanline looks
 5771: like.
 5772: 
 5773: Next each scanline is checked for any errors of either 'missing
 5774: bubbles' (it's an error because it may have been mis-scanned
 5775: because too light bubbling), 'double bubble' (each bubble line should
 5776: have no more than one letter picked), invalid or duplicated CODE,
 5777: invalid student/employee ID
 5778: 
 5779: If the CODE option is used that determines the randomization of the
 5780: homework problems, either way the student/employee ID is looked up into a
 5781: username:domain.
 5782: 
 5783: During the validation phase the instructor can choose to skip scanlines. 
 5784: 
 5785: After the validation phase, there are now 3 bubblesheet files
 5786: 
 5787:   scantron_original_filename (unmodified original file)
 5788:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5789:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5790: 
 5791: Also there is a separate hash nohist_scantrondata that contains extra
 5792: correction information that isn't representable in the bubblesheet
 5793: file (see &scantron_getfile() for more information)
 5794: 
 5795: After all scanlines are either valid, marked as valid or skipped, then
 5796: foreach line foreach problem in the picked sequence, an ssi request is
 5797: made that simulates a user submitting their selected letter(s) against
 5798: the homework problem.
 5799: 
 5800: =over 4
 5801: 
 5802: 
 5803: 
 5804: =item defaultFormData
 5805: 
 5806:   Returns html hidden inputs used to hold context/default values.
 5807: 
 5808:  Arguments:
 5809:   $symb - $symb of the current resource 
 5810: 
 5811: =cut
 5812: 
 5813: sub defaultFormData {
 5814:     my ($symb)=@_;
 5815:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5816: }
 5817: 
 5818: 
 5819: =pod 
 5820: 
 5821: =item getSequenceDropDown
 5822: 
 5823:    Return html dropdown of possible sequences to grade
 5824:  
 5825:  Arguments:
 5826:    $symb - $symb of the current resource
 5827:    $map_error - ref to scalar which will container error if
 5828:                 $navmap object is unavailable in &getSymbMap().
 5829: 
 5830: =cut
 5831: 
 5832: sub getSequenceDropDown {
 5833:     my ($symb,$map_error)=@_;
 5834:     my $result='<select name="selectpage">'."\n";
 5835:     my ($titles,$symbx) = &getSymbMap($map_error);
 5836:     if (ref($map_error)) {
 5837:         return if ($$map_error);
 5838:     }
 5839:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5840:     my $ctr=0;
 5841:     foreach (@$titles) {
 5842: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5843: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5844: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5845: 	    '>'.$showtitle.'</option>'."\n";
 5846: 	$ctr++;
 5847:     }
 5848:     $result.= '</select>';
 5849:     return $result;
 5850: }
 5851: 
 5852: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5853:                                    # key is zero-based index - 0, 1, 2 ...
 5854: 
 5855: my %first_bubble_line;             # First bubble line no. for each bubble.
 5856: 
 5857: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5858:                                    # matchresponse or rankresponse, where 
 5859:                                    # an individual response can have multiple 
 5860:                                    # lines
 5861: 
 5862: my %responsetype_per_response;     # responsetype for each response
 5863: 
 5864: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5865:                                    # numbered response. Needed when randomorder
 5866:                                    # or randompick are in use. Key is ID, value 
 5867:                                    # is response number.
 5868: 
 5869: # Save and restore the bubble lines array to the form env.
 5870: 
 5871: 
 5872: sub save_bubble_lines {
 5873:     foreach my $line (keys(%bubble_lines_per_response)) {
 5874: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5875: 	$env{"form.scantron.first_bubble_line.$line"} =
 5876: 	    $first_bubble_line{$line};
 5877:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5878:             $subdivided_bubble_lines{$line};
 5879:         $env{"form.scantron.responsetype.$line"} =
 5880:             $responsetype_per_response{$line};
 5881:     }
 5882:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5883:         my $line = $masterseq_id_responsenum{$resid};
 5884:         $env{"form.scantron.residpart.$line"} = $resid;
 5885:     }
 5886: }
 5887: 
 5888: 
 5889: sub restore_bubble_lines {
 5890:     my $line = 0;
 5891:     %bubble_lines_per_response = ();
 5892:     %masterseq_id_responsenum = ();
 5893:     while ($env{"form.scantron.bubblelines.$line"}) {
 5894: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5895: 	$bubble_lines_per_response{$line} = $value;
 5896: 	$first_bubble_line{$line}  =
 5897: 	    $env{"form.scantron.first_bubble_line.$line"};
 5898:         $subdivided_bubble_lines{$line} =
 5899:             $env{"form.scantron.sub_bubblelines.$line"};
 5900:         $responsetype_per_response{$line} =
 5901:             $env{"form.scantron.responsetype.$line"};
 5902:         my $id = $env{"form.scantron.residpart.$line"};
 5903:         $masterseq_id_responsenum{$id} = $line;
 5904: 	$line++;
 5905:     }
 5906: }
 5907: 
 5908: =pod 
 5909: 
 5910: =item scantron_filenames
 5911: 
 5912:    Returns a list of the scantron files in the current course 
 5913: 
 5914: =cut
 5915: 
 5916: sub scantron_filenames {
 5917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5918:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5919:     my $getpropath = 1;
 5920:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5921:                                                         $cname,$getpropath);
 5922:     my @possiblenames;
 5923:     if (ref($dirlist) eq 'ARRAY') {
 5924:         foreach my $filename (sort(@{$dirlist})) {
 5925: 	    ($filename)=split(/&/,$filename);
 5926: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5927: 	    $filename=~s/^scantron_orig_//;
 5928: 	    push(@possiblenames,$filename);
 5929:         }
 5930:     }
 5931:     return @possiblenames;
 5932: }
 5933: 
 5934: =pod 
 5935: 
 5936: =item scantron_uploads
 5937: 
 5938:    Returns  html drop-down list of scantron files in current course.
 5939: 
 5940:  Arguments:
 5941:    $file2grade - filename to set as selected in the dropdown
 5942: 
 5943: =cut
 5944: 
 5945: sub scantron_uploads {
 5946:     my ($file2grade) = @_;
 5947:     my $result=	'<select name="scantron_selectfile">';
 5948:     $result.="<option></option>";
 5949:     foreach my $filename (sort(&scantron_filenames())) {
 5950: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5951:     }
 5952:     $result.="</select>";
 5953:     return $result;
 5954: }
 5955: 
 5956: =pod 
 5957: 
 5958: =item scantron_scantab
 5959: 
 5960:   Returns html drop down of the scantron formats in the scantronformat.tab
 5961:   file.
 5962: 
 5963: =cut
 5964: 
 5965: sub scantron_scantab {
 5966:     my $result='<select name="scantron_format">'."\n";
 5967:     $result.='<option></option>'."\n";
 5968:     my @lines = &Apache::lonnet::get_scantronformat_file();
 5969:     if (@lines > 0) {
 5970:         foreach my $line (@lines) {
 5971:             next if (($line =~ /^\#/) || ($line eq ''));
 5972: 	    my ($name,$descrip)=split(/:/,$line);
 5973: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5974:         }
 5975:     }
 5976:     $result.='</select>'."\n";
 5977:     return $result;
 5978: }
 5979: 
 5980: =pod 
 5981: 
 5982: =item scantron_CODElist
 5983: 
 5984:   Returns html drop down of the saved CODE lists from current course,
 5985:   generated from earlier printings.
 5986: 
 5987: =cut
 5988: 
 5989: sub scantron_CODElist {
 5990:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5991:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5992:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5993:     my $namechoice='<option></option>';
 5994:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5995: 	if ($name =~ /^error: 2 /) { next; }
 5996: 	if ($name =~ /^type\0/) { next; }
 5997: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5998:     }
 5999:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6000:     return $namechoice;
 6001: }
 6002: 
 6003: =pod 
 6004: 
 6005: =item scantron_CODEunique
 6006: 
 6007:   Returns the html for "Each CODE to be used once" radio.
 6008: 
 6009: =cut
 6010: 
 6011: sub scantron_CODEunique {
 6012:     my $result='<span class="LC_nobreak">
 6013:                  <label><input type="radio" name="scantron_CODEunique"
 6014:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6015:                 </span>
 6016:                 <span class="LC_nobreak">
 6017:                  <label><input type="radio" name="scantron_CODEunique"
 6018:                         value="no" />'.&mt('No').' </label>
 6019:                 </span>';
 6020:     return $result;
 6021: }
 6022: 
 6023: =pod 
 6024: 
 6025: =item scantron_selectphase
 6026: 
 6027:   Generates the initial screen to start the bubblesheet process.
 6028:   Allows for - starting a grading run.
 6029:              - downloading existing scan data (original, corrected
 6030:                                                 or skipped info)
 6031: 
 6032:              - uploading new scan data
 6033: 
 6034:  Arguments:
 6035:   $r          - The Apache request object
 6036:   $file2grade - name of the file that contain the scanned data to score
 6037: 
 6038: =cut
 6039: 
 6040: sub scantron_selectphase {
 6041:     my ($r,$file2grade,$symb) = @_;
 6042:     if (!$symb) {return '';}
 6043:     my $map_error;
 6044:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6045:     if ($map_error) {
 6046:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6047:         return;
 6048:     }
 6049:     my $default_form_data=&defaultFormData($symb);
 6050:     my $file_selector=&scantron_uploads($file2grade);
 6051:     my $format_selector=&scantron_scantab();
 6052:     my $CODE_selector=&scantron_CODElist();
 6053:     my $CODE_unique=&scantron_CODEunique();
 6054:     my $result;
 6055: 
 6056:     $ssi_error = 0;
 6057: 
 6058:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6059: 
 6060: 	# Chunk of form to prompt for a scantron file upload.
 6061: 
 6062:         $r->print('
 6063:     <br />');
 6064:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6065:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6066:     my $csec= $env{'request.course.sec'};
 6067:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6068:     &js_escape(\$alertmsg);
 6069:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6070:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6071:     function checkUpload(formname) {
 6072: 	if (formname.upfile.value == "") {
 6073: 	    alert("'.$alertmsg.'");
 6074: 	    return false;
 6075: 	}
 6076: 	formname.submit();
 6077:     }'."\n".$formatjs));
 6078:     $r->print('
 6079:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6080:                 '.$default_form_data.'
 6081:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6082:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6083:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6084:                 <input name="command" value="scantronupload_save" type="hidden" />
 6085:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6086:               '.&Apache::loncommon::start_data_table_header_row().'
 6087:                 <th>
 6088:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6089:                 </th>
 6090:               '.&Apache::loncommon::end_data_table_header_row().'
 6091:               '.&Apache::loncommon::start_data_table_row().'
 6092:             <td>
 6093:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6094:     if ($formatoptions) {
 6095:         $r->print('</td>
 6096:                  '.&Apache::loncommon::end_data_table_row().'
 6097:                  '.&Apache::loncommon::start_data_table_row().'
 6098:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6099:                  </td>
 6100:                  '.&Apache::loncommon::end_data_table_row().'
 6101:                  '.&Apache::loncommon::start_data_table_row().'
 6102:                  <td>'
 6103:         );
 6104:     } else {
 6105:         $r->print(' <br />');
 6106:     }
 6107:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6108:               </td>
 6109:              '.&Apache::loncommon::end_data_table_row().'
 6110:              '.&Apache::loncommon::end_data_table().'
 6111:              </form>'
 6112:     );
 6113: 
 6114:     }
 6115: 
 6116:     # Chunk of form to prompt for a file to grade and how:
 6117: 
 6118:     $result.= '
 6119:     <br />
 6120:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6121:     <input type="hidden" name="command" value="scantron_warning" />
 6122:     '.$default_form_data.'
 6123:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6124:        '.&Apache::loncommon::start_data_table_header_row().'
 6125:             <th colspan="2">
 6126:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6127:             </th>
 6128:        '.&Apache::loncommon::end_data_table_header_row().'
 6129:        '.&Apache::loncommon::start_data_table_row().'
 6130:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6131:        '.&Apache::loncommon::end_data_table_row().'
 6132:        '.&Apache::loncommon::start_data_table_row().'
 6133:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6134:        '.&Apache::loncommon::end_data_table_row().'
 6135:        '.&Apache::loncommon::start_data_table_row().'
 6136:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6137:        '.&Apache::loncommon::end_data_table_row().'
 6138:        '.&Apache::loncommon::start_data_table_row().'
 6139:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6140:        '.&Apache::loncommon::end_data_table_row().'
 6141:        '.&Apache::loncommon::start_data_table_row().'
 6142:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6143:        '.&Apache::loncommon::end_data_table_row().'
 6144:        '.&Apache::loncommon::start_data_table_row().'
 6145: 	    <td> '.&mt('Options:').' </td>
 6146:             <td>
 6147: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6148:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6149:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6150: 	    </td>
 6151:        '.&Apache::loncommon::end_data_table_row().'
 6152:        '.&Apache::loncommon::start_data_table_row().'
 6153:             <td colspan="2">
 6154:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6155:             </td>
 6156:        '.&Apache::loncommon::end_data_table_row().'
 6157:     '.&Apache::loncommon::end_data_table().'
 6158:     </form>
 6159: ';
 6160:    
 6161:     $r->print($result);
 6162: 
 6163:     # Chunk of the form that prompts to view a scoring office file,
 6164:     # corrected file, skipped records in a file.
 6165: 
 6166:     $r->print('
 6167:    <br />
 6168:    <form action="/adm/grades" name="scantron_download">
 6169:      '.$default_form_data.'
 6170:      <input type="hidden" name="command" value="scantron_download" />
 6171:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6172:        '.&Apache::loncommon::start_data_table_header_row().'
 6173:               <th>
 6174:                 &nbsp;'.&mt('Download a scoring office file').'
 6175:               </th>
 6176:        '.&Apache::loncommon::end_data_table_header_row().'
 6177:        '.&Apache::loncommon::start_data_table_row().'
 6178:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6179:                 <br />
 6180:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6181:        '.&Apache::loncommon::end_data_table_row().'
 6182:      '.&Apache::loncommon::end_data_table().'
 6183:    </form>
 6184:    <br />
 6185: ');
 6186: 
 6187:     &Apache::lonpickcode::code_list($r,2);
 6188: 
 6189:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6190:              $default_form_data."\n".
 6191:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6192:              &Apache::loncommon::start_data_table_header_row()."\n".
 6193:              '<th colspan="2">
 6194:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6195:              '</th>'."\n".
 6196:               &Apache::loncommon::end_data_table_header_row()."\n".
 6197:               &Apache::loncommon::start_data_table_row()."\n".
 6198:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6199:               '<td> '.$sequence_selector.' </td>'.
 6200:               &Apache::loncommon::end_data_table_row()."\n".
 6201:               &Apache::loncommon::start_data_table_row()."\n".
 6202:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6203:               '<td> '.$file_selector.' </td>'."\n".
 6204:               &Apache::loncommon::end_data_table_row()."\n".
 6205:               &Apache::loncommon::start_data_table_row()."\n".
 6206:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6207:               '<td> '.$format_selector.' </td>'."\n".
 6208:               &Apache::loncommon::end_data_table_row()."\n".
 6209:               &Apache::loncommon::start_data_table_row()."\n".
 6210:               '<td> '.&mt('Options').' </td>'."\n".
 6211:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6212:               &Apache::loncommon::end_data_table_row()."\n".
 6213:               &Apache::loncommon::start_data_table_row()."\n".
 6214:               '<td colspan="2">'."\n".
 6215:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6216:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6217:               '</td>'."\n".
 6218:               &Apache::loncommon::end_data_table_row()."\n".
 6219:               &Apache::loncommon::end_data_table()."\n".
 6220:               '</form><br />');
 6221:     return;
 6222: }
 6223: 
 6224: =pod 
 6225: 
 6226: =item username_to_idmap
 6227: 
 6228:     creates a hash keyed by student/employee ID with values of the corresponding
 6229:     student username:domain. If a single ID occurs for more than one student,
 6230:     the status of the student is checked, and if Active, the value in the hash
 6231:     will be set to the Active student.
 6232: 
 6233:   Arguments:
 6234: 
 6235:     $classlist - reference to the class list hash. This is a hash
 6236:                  keyed by student name:domain  whose elements are references
 6237:                  to arrays containing various chunks of information
 6238:                  about the student. (See loncoursedata for more info).
 6239: 
 6240:   Returns
 6241:     %idmap - the constructed hash
 6242: 
 6243: =cut
 6244: 
 6245: sub username_to_idmap {
 6246:     my ($classlist)= @_;
 6247:     my %idmap;
 6248:     foreach my $student (keys(%$classlist)) {
 6249:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6250:         unless ($id eq '') {
 6251:             if (!exists($idmap{$id})) {
 6252:                 $idmap{$id} = $student;
 6253:             } else {
 6254:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6255:                 if ($status eq 'Active') {
 6256:                     $idmap{$id} = $student;
 6257:                 }
 6258:             }
 6259:         }
 6260:     }
 6261:     return %idmap;
 6262: }
 6263: 
 6264: =pod
 6265: 
 6266: =item scantron_fixup_scanline
 6267: 
 6268:    Process a requested correction to a scanline.
 6269: 
 6270:   Arguments:
 6271:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6272:     $scan_data         - hash of correction information 
 6273:                           (see &scantron_getfile())
 6274:     $line              - existing scanline
 6275:     $whichline         - line number of the passed in scanline
 6276:     $field             - type of change to process 
 6277:                          (either 
 6278:                           'ID'     -> correct the student/employee ID
 6279:                           'CODE'   -> correct the CODE
 6280:                           'answer' -> fixup the submitted answers)
 6281:     
 6282:    $args               - hash of additional info,
 6283:                           - 'ID' 
 6284:                                'newid' -> studentID to use in replacement
 6285:                                           of existing one
 6286:                           - 'CODE' 
 6287:                                'CODE_ignore_dup' - set to true if duplicates
 6288:                                                    should be ignored.
 6289: 	                       'CODE' - is new code or 'use_unfound'
 6290:                                         if the existing unfound code should
 6291:                                         be used as is
 6292:                           - 'answer'
 6293:                                'response' - new answer or 'none' if blank
 6294:                                'question' - the bubble line to change
 6295:                                'questionnum' - the question identifier,
 6296:                                                may include subquestion. 
 6297: 
 6298:   Returns:
 6299:     $line - the modified scanline
 6300: 
 6301:   Side effects: 
 6302:     $scan_data - may be updated
 6303: 
 6304: =cut
 6305: 
 6306: 
 6307: sub scantron_fixup_scanline {
 6308:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6309:     if ($field eq 'ID') {
 6310: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6311: 	    return ($line,1,'New value too large');
 6312: 	}
 6313: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6314: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6315: 				     $args->{'newid'});
 6316: 	}
 6317: 	substr($line,$$scantron_config{'IDstart'}-1,
 6318: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6319: 	if ($args->{'newid'}=~/^\s*$/) {
 6320: 	    &scan_data($scan_data,"$whichline.user",
 6321: 		       $args->{'username'}.':'.$args->{'domain'});
 6322: 	}
 6323:     } elsif ($field eq 'CODE') {
 6324: 	if ($args->{'CODE_ignore_dup'}) {
 6325: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6326: 	}
 6327: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6328: 	if ($args->{'CODE'} ne 'use_unfound') {
 6329: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6330: 		return ($line,1,'New CODE value too large');
 6331: 	    }
 6332: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6333: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6334: 	    }
 6335: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6336: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6337: 	}
 6338:     } elsif ($field eq 'answer') {
 6339: 	my $length=$scantron_config->{'Qlength'};
 6340: 	my $off=$scantron_config->{'Qoff'};
 6341: 	my $on=$scantron_config->{'Qon'};
 6342: 	my $answer=${off}x$length;
 6343: 	if ($args->{'response'} eq 'none') {
 6344: 	    &scan_data($scan_data,
 6345: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6346: 	} else {
 6347: 	    if ($on eq 'letter') {
 6348: 		my @alphabet=('A'..'Z');
 6349: 		$answer=$alphabet[$args->{'response'}];
 6350: 	    } elsif ($on eq 'number') {
 6351: 		$answer=$args->{'response'}+1;
 6352: 		if ($answer == 10) { $answer = '0'; }
 6353: 	    } else {
 6354: 		substr($answer,$args->{'response'},1)=$on;
 6355: 	    }
 6356: 	    &scan_data($scan_data,
 6357: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6358: 	}
 6359: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6360: 	substr($line,$where-1,$length)=$answer;
 6361:     }
 6362:     return $line;
 6363: }
 6364: 
 6365: =pod
 6366: 
 6367: =item scan_data
 6368: 
 6369:     Edit or look up  an item in the scan_data hash.
 6370: 
 6371:   Arguments:
 6372:     $scan_data  - The hash (see scantron_getfile)
 6373:     $key        - shorthand of the key to edit (actual key is
 6374:                   scantronfilename_key).
 6375:     $data        - New value of the hash entry.
 6376:     $delete      - If true, the entry is removed from the hash.
 6377: 
 6378:   Returns:
 6379:     The new value of the hash table field (undefined if deleted).
 6380: 
 6381: =cut
 6382: 
 6383: 
 6384: sub scan_data {
 6385:     my ($scan_data,$key,$value,$delete)=@_;
 6386:     my $filename=$env{'form.scantron_selectfile'};
 6387:     if (defined($value)) {
 6388: 	$scan_data->{$filename.'_'.$key} = $value;
 6389:     }
 6390:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6391:     return $scan_data->{$filename.'_'.$key};
 6392: }
 6393: 
 6394: # ----- These first few routines are general use routines.----
 6395: 
 6396: # Return the number of occurences of a pattern in a string.
 6397: 
 6398: sub occurence_count {
 6399:     my ($string, $pattern) = @_;
 6400: 
 6401:     my @matches = ($string =~ /$pattern/g);
 6402: 
 6403:     return scalar(@matches);
 6404: }
 6405: 
 6406: 
 6407: # Take a string known to have digits and convert all the
 6408: # digits into letters in the range J,A..I.
 6409: 
 6410: sub digits_to_letters {
 6411:     my ($input) = @_;
 6412: 
 6413:     my @alphabet = ('J', 'A'..'I');
 6414: 
 6415:     my @input    = split(//, $input);
 6416:     my $output ='';
 6417:     for (my $i = 0; $i < scalar(@input); $i++) {
 6418: 	if ($input[$i] =~ /\d/) {
 6419: 	    $output .= $alphabet[$input[$i]];
 6420: 	} else {
 6421: 	    $output .= $input[$i];
 6422: 	}
 6423:     }
 6424:     return $output;
 6425: }
 6426: 
 6427: =pod 
 6428: 
 6429: =item scantron_parse_scanline
 6430: 
 6431:   Decodes a scanline from the selected bubblesheet file
 6432: 
 6433:  Arguments:
 6434:     line             - The text of the bubblesheet file line to process
 6435:     whichline        - Line number
 6436:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6437:     scan_data        - Hash of extra information about the scanline
 6438:                        (see scantron_getfile for more information)
 6439:     just_header      - True if should not process question answers but only
 6440:                        the stuff to the left of the answers.
 6441:     randomorder      - True if randomorder in use
 6442:     randompick       - True if randompick in use
 6443:     sequence         - Exam folder URL
 6444:     master_seq       - Ref to array containing symbs in exam folder
 6445:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6446:                        (corresponding values are resource objects)
 6447:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6448:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6449:                        are refs to an array of resource objects, ordered
 6450:                        according to order used for CODE, when randomorder
 6451:                        and or randompick are in use.
 6452:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6453:                        for current line to question number used for same question
 6454:                         in "Master Sequence" (as seen by Course Coordinator).
 6455:     startline        - Ref to hash where key is question number (0 is first)
 6456:                        and value is number of first bubble line for current 
 6457:                        student or code-based randompick and/or randomorder.
 6458:     totalref         - Ref of scalar used to score total number of bubble
 6459:                        lines needed for responses in a scan line (used when
 6460:                        randompick in use. 
 6461:     
 6462:  Returns:
 6463:    Hash containing the result of parsing the scanline
 6464: 
 6465:    Keys are all proceeded by the string 'scantron.'
 6466: 
 6467:        CODE    - the CODE in use for this scanline
 6468:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6469:                  by the operator
 6470:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6471:                             CODEs were selected, but the usage has been
 6472:                             forced by the operator
 6473:        ID  - student/employee ID
 6474:        PaperID - if used, the ID number printed on the sheet when the 
 6475:                  paper was scanned
 6476:        FirstName - first name from the sheet
 6477:        LastName  - last name from the sheet
 6478: 
 6479:      if just_header was not true these key may also exist
 6480: 
 6481:        missingerror - a list of bubble ranges that are considered to be answers
 6482:                       to a single question that don't have any bubbles filled in.
 6483:                       Of the form questionnumber:firstbubblenumber:count.
 6484:        doubleerror  - a list of bubble ranges that are considered to be answers
 6485:                       to a single question that have more than one bubble filled in.
 6486:                       Of the form questionnumber::firstbubblenumber:count
 6487:    
 6488:                 In the above, count is the number of bubble responses in the
 6489:                 input line needed to represent the possible answers to the question.
 6490:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6491:                 per line would have count = 2.
 6492: 
 6493:        maxquest     - the number of the last bubble line that was parsed
 6494: 
 6495:        (<number> starts at 1)
 6496:        <number>.answer - zero or more letters representing the selected
 6497:                          letters from the scanline for the bubble line 
 6498:                          <number>.
 6499:                          if blank there was either no bubble or there where
 6500:                          multiple bubbles, (consult the keys missingerror and
 6501:                          doubleerror if this is an error condition)
 6502: 
 6503: =cut
 6504: 
 6505: sub scantron_parse_scanline {
 6506:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6507:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6508:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6509: 
 6510:     my %record;
 6511:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6512:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6513: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6514: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6515: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6516: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6517: 	    $record{'scantron.CODE'}=substr($data,
 6518: 					    $$scantron_config{'CODEstart'}-1,
 6519: 					    $$scantron_config{'CODElength'});
 6520: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6521: 		$record{'scantron.useCODE'}=1;
 6522: 	    }
 6523: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6524: 		$record{'scantron.CODE_ignore_dup'}=1;
 6525: 	    }
 6526: 	} else {
 6527: 	    #FIXME interpret first N questions
 6528: 	}
 6529:     }
 6530:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6531: 				  $$scantron_config{'IDlength'});
 6532:     $record{'scantron.PaperID'}=
 6533: 	substr($data,$$scantron_config{'PaperID'}-1,
 6534: 	       $$scantron_config{'PaperIDlength'});
 6535:     $record{'scantron.FirstName'}=
 6536: 	substr($data,$$scantron_config{'FirstName'}-1,
 6537: 	       $$scantron_config{'FirstNamelength'});
 6538:     $record{'scantron.LastName'}=
 6539: 	substr($data,$$scantron_config{'LastName'}-1,
 6540: 	       $$scantron_config{'LastNamelength'});
 6541:     if ($just_header) { return \%record; }
 6542: 
 6543:     my @alphabet=('A'..'Z');
 6544:     my $questnum=0;
 6545:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6546: 
 6547:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6548:     if ($randompick || $randomorder) {
 6549:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6550:                                          $master_seq,$symb_to_resource,
 6551:                                          $partids_by_symb,$orderedforcode,
 6552:                                          $respnumlookup,$startline);
 6553:         if ($total) {
 6554:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6555:         }
 6556:         if (ref($totalref)) {
 6557:             $$totalref = $total;
 6558:         }
 6559:     }
 6560:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6561:     chomp($questions);		# Get rid of any trailing \n.
 6562:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6563:     while (length($questions)) {
 6564:         my $answers_needed;
 6565:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6566:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6567:         } else {
 6568: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6569:         }
 6570:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6571:                              || 1;
 6572:         $questnum++;
 6573:         my $quest_id = $questnum;
 6574:         my $currentquest = substr($questions,0,$answer_length);
 6575:         $questions       = substr($questions,$answer_length);
 6576:         if (length($currentquest) < $answer_length) { next; }
 6577: 
 6578:         my $subdivided;
 6579:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6580:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6581:         } else {
 6582:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6583:         }
 6584:         if ($subdivided =~ /,/) {
 6585:             my $subquestnum = 1;
 6586:             my $subquestions = $currentquest;
 6587:             my @subanswers_needed = split(/,/,$subdivided);
 6588:             foreach my $subans (@subanswers_needed) {
 6589:                 my $subans_length =
 6590:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6591:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6592:                 $subquestions   = substr($subquestions,$subans_length);
 6593:                 $quest_id = "$questnum.$subquestnum";
 6594:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6595:                     ($$scantron_config{'Qon'} eq 'number')) {
 6596:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6597:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6598:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6599:                         $randomorder,$randompick,$respnumlookup);
 6600:                 } else {
 6601:                     $ansnum = &scantron_validator_positional($ansnum,
 6602:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6603:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6604:                         $randomorder,$randompick,$respnumlookup);
 6605:                 }
 6606:                 $subquestnum ++;
 6607:             }
 6608:         } else {
 6609:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6610:                 ($$scantron_config{'Qon'} eq 'number')) {
 6611:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6612:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6613:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6614:                     $randomorder,$randompick,$respnumlookup);
 6615:             } else {
 6616:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6617:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6618:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6619:                     $randomorder,$randompick,$respnumlookup);
 6620:             }
 6621:         }
 6622:     }
 6623:     $record{'scantron.maxquest'}=$questnum;
 6624:     return \%record;
 6625: }
 6626: 
 6627: sub get_master_seq {
 6628:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6629:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6630:                    (ref($symb_to_resource) eq 'HASH'));
 6631:     my $resource_error;
 6632:     foreach my $resource (@{$resources}) {
 6633:         my $ressymb;
 6634:         if (ref($resource)) {
 6635:             $ressymb = $resource->symb();
 6636:             push(@{$master_seq},$ressymb);
 6637:             $symb_to_resource->{$ressymb} = $resource;
 6638:         } else {
 6639:             $resource_error = 1;
 6640:             last;
 6641:         }
 6642:     }
 6643:     return $resource_error;
 6644: }
 6645: 
 6646: sub get_respnum_lookups {
 6647:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6648:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6649:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6650:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6651:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6652:                    (ref($startline) eq 'HASH'));
 6653:     my ($user,$scancode);
 6654:     if ((exists($record->{'scantron.CODE'})) &&
 6655:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6656:         $scancode = $record->{'scantron.CODE'};
 6657:     } else {
 6658:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6659:     }
 6660:     my @mapresources =
 6661:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6662:                      $orderedforcode);
 6663:     my $total = 0;
 6664:     my $count = 0;
 6665:     foreach my $resource (@mapresources) {
 6666:         my $id = $resource->id();
 6667:         my $symb = $resource->symb();
 6668:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6669:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6670:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6671:                 if ($respnum ne '') {
 6672:                     $respnumlookup->{$count} = $respnum;
 6673:                     $startline->{$count} = $total;
 6674:                     $total += $bubble_lines_per_response{$respnum};
 6675:                     $count ++;
 6676:                 }
 6677:             }
 6678:         }
 6679:     }
 6680:     return $total;
 6681: }
 6682: 
 6683: sub scantron_validator_lettnum {
 6684:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6685:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6686:         $randompick,$respnumlookup) = @_;
 6687: 
 6688:     # Qon 'letter' implies for each slot in currquest we have:
 6689:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6690:     #    about anything else (esp. a value of Qoff) for missing
 6691:     #    bubbles.
 6692:     #
 6693:     # Qon 'number' implies each slot gives a digit that indexes the
 6694:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6695:     #    and * or ? for double bubbles on a single line.
 6696:     #
 6697: 
 6698:     my $matchon;
 6699:     if ($$scantron_config{'Qon'} eq 'letter') {
 6700:         $matchon = '[A-Z]';
 6701:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6702:         $matchon = '\d';
 6703:     }
 6704:     my $occurrences = 0;
 6705:     my $responsenum = $questnum-1;
 6706:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6707:        $responsenum = $respnumlookup->{$questnum-1} 
 6708:     }
 6709:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6710:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6711:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6712:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6713:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6714:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6715:         my @singlelines = split('',$currquest);
 6716:         foreach my $entry (@singlelines) {
 6717:             $occurrences = &occurence_count($entry,$matchon);
 6718:             if ($occurrences > 1) {
 6719:                 last;
 6720:             }
 6721:         }
 6722:     } else {
 6723:         $occurrences = &occurence_count($currquest,$matchon); 
 6724:     }
 6725:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6726:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6727:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6728:             my $bubble = substr($currquest,$ans,1);
 6729:             if ($bubble =~ /$matchon/ ) {
 6730:                 if ($$scantron_config{'Qon'} eq 'number') {
 6731:                     if ($bubble == 0) {
 6732:                         $bubble = 10; 
 6733:                     }
 6734:                     $record->{"scantron.$ansnum.answer"} = 
 6735:                         $alphabet->[$bubble-1];
 6736:                 } else {
 6737:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6738:                 }
 6739:             } else {
 6740:                 $record->{"scantron.$ansnum.answer"}='';
 6741:             }
 6742:             $ansnum++;
 6743:         }
 6744:     } elsif (!defined($currquest)
 6745:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6746:             || (&occurence_count($currquest,$matchon) == 0)) {
 6747:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6748:             $record->{"scantron.$ansnum.answer"}='';
 6749:             $ansnum++;
 6750:         }
 6751:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6752:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6753:         }
 6754:     } else {
 6755:         if ($$scantron_config{'Qon'} eq 'number') {
 6756:             $currquest = &digits_to_letters($currquest);            
 6757:         }
 6758:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6759:             my $bubble = substr($currquest,$ans,1);
 6760:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6761:             $ansnum++;
 6762:         }
 6763:     }
 6764:     return $ansnum;
 6765: }
 6766: 
 6767: sub scantron_validator_positional {
 6768:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6769:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6770:         $randomorder,$randompick,$respnumlookup) = @_;
 6771: 
 6772:     # Otherwise there's a positional notation;
 6773:     # each bubble line requires Qlength items, and there are filled in
 6774:     # bubbles for each case where there 'Qon' characters.
 6775:     #
 6776: 
 6777:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6778: 
 6779:     # If the split only gives us one element.. the full length of the
 6780:     # answer string, no bubbles are filled in:
 6781: 
 6782:     if ($answers_needed eq '') {
 6783:         return;
 6784:     }
 6785: 
 6786:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6787:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6788:             $record->{"scantron.$ansnum.answer"}='';
 6789:             $ansnum++;
 6790:         }
 6791:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6792:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6793:         }
 6794:     } elsif (scalar(@array) == 2) {
 6795:         my $location = length($array[0]);
 6796:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6797:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6798:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6799:             if ($ans eq $line_num) {
 6800:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6801:             } else {
 6802:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6803:             }
 6804:             $ansnum++;
 6805:          }
 6806:     } else {
 6807:         #  If there's more than one instance of a bubble character
 6808:         #  That's a double bubble; with positional notation we can
 6809:         #  record all the bubbles filled in as well as the
 6810:         #  fact this response consists of multiple bubbles.
 6811:         #
 6812:         my $responsenum = $questnum-1;
 6813:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6814:             $responsenum = $respnumlookup->{$questnum-1}
 6815:         }
 6816:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6817:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6818:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6819:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6820:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6821:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6822:             my $doubleerror = 0;
 6823:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6824:                    (!$doubleerror)) {
 6825:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6826:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6827:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6828:                if (length(@currarray) > 2) {
 6829:                    $doubleerror = 1;
 6830:                } 
 6831:             }
 6832:             if ($doubleerror) {
 6833:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6834:             }
 6835:         } else {
 6836:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6837:         }
 6838:         my $item = $ansnum;
 6839:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6840:             $record->{"scantron.$item.answer"} = '';
 6841:             $item ++;
 6842:         }
 6843: 
 6844:         my @ans=@array;
 6845:         my $i=0;
 6846:         my $increment = 0;
 6847:         while ($#ans) {
 6848:             $i+=length($ans[0]) + $increment;
 6849:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6850:             my $bubble = $i%$$scantron_config{'Qlength'};
 6851:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6852:             shift(@ans);
 6853:             $increment = 1;
 6854:         }
 6855:         $ansnum += $answers_needed;
 6856:     }
 6857:     return $ansnum;
 6858: }
 6859: 
 6860: =pod
 6861: 
 6862: =item scantron_add_delay
 6863: 
 6864:    Adds an error message that occurred during the grading phase to a
 6865:    queue of messages to be shown after grading pass is complete
 6866: 
 6867:  Arguments:
 6868:    $delayqueue  - arrary ref of hash ref of error messages
 6869:    $scanline    - the scanline that caused the error
 6870:    $errormesage - the error message
 6871:    $errorcode   - a numeric code for the error
 6872: 
 6873:  Side Effects:
 6874:    updates the $delayqueue to have a new hash ref of the error
 6875: 
 6876: =cut
 6877: 
 6878: sub scantron_add_delay {
 6879:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6880:     push(@$delayqueue,
 6881: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6882: 	  'ecode' => $errorcode }
 6883: 	 );
 6884: }
 6885: 
 6886: =pod
 6887: 
 6888: =item scantron_find_student
 6889: 
 6890:    Finds the username for the current scanline
 6891: 
 6892:   Arguments:
 6893:    $scantron_record - hash result from scantron_parse_scanline
 6894:    $scan_data       - hash of correction information 
 6895:                       (see &scantron_getfile() form more information)
 6896:    $idmap           - hash from &username_to_idmap()
 6897:    $line            - number of current scanline
 6898:  
 6899:   Returns:
 6900:    Either 'username:domain' or undef if unknown
 6901: 
 6902: =cut
 6903: 
 6904: sub scantron_find_student {
 6905:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6906:     my $scanID=$$scantron_record{'scantron.ID'};
 6907:     if ($scanID =~ /^\s*$/) {
 6908:  	return &scan_data($scan_data,"$line.user");
 6909:     }
 6910:     foreach my $id (keys(%$idmap)) {
 6911:  	if (lc($id) eq lc($scanID)) {
 6912:  	    return $$idmap{$id};
 6913:  	}
 6914:     }
 6915:     return undef;
 6916: }
 6917: 
 6918: =pod
 6919: 
 6920: =item scantron_filter
 6921: 
 6922:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6923:    hidden resources was selected
 6924: 
 6925: =cut
 6926: 
 6927: sub scantron_filter {
 6928:     my ($curres)=@_;
 6929: 
 6930:     if (ref($curres) && $curres->is_problem()) {
 6931: 	# if the user has asked to not have either hidden
 6932: 	# or 'randomout' controlled resources to be graded
 6933: 	# don't include them
 6934: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6935: 	    && $curres->randomout) {
 6936: 	    return 0;
 6937: 	}
 6938: 	return 1;
 6939:     }
 6940:     return 0;
 6941: }
 6942: 
 6943: =pod
 6944: 
 6945: =item scantron_process_corrections
 6946: 
 6947:    Gets correction information out of submitted form data and corrects
 6948:    the scanline
 6949: 
 6950: =cut
 6951: 
 6952: sub scantron_process_corrections {
 6953:     my ($r) = @_;
 6954:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 6955:     my ($scanlines,$scan_data)=&scantron_getfile();
 6956:     my $classlist=&Apache::loncoursedata::get_classlist();
 6957:     my $which=$env{'form.scantron_line'};
 6958:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6959:     my ($skip,$err,$errmsg);
 6960:     if ($env{'form.scantron_skip_record'}) {
 6961: 	$skip=1;
 6962:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6963: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6964: 	    $env{'form.scantron_domain'};
 6965: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6966: 	($line,$err,$errmsg)=
 6967: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6968: 				     'ID',{'newid'=>$newid,
 6969: 				    'username'=>$env{'form.scantron_username'},
 6970: 				    'domain'=>$env{'form.scantron_domain'}});
 6971:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6972: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6973: 	my $newCODE;
 6974: 	my %args;
 6975: 	if      ($resolution eq 'use_unfound') {
 6976: 	    $newCODE='use_unfound';
 6977: 	} elsif ($resolution eq 'use_found') {
 6978: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6979: 	} elsif ($resolution eq 'use_typed') {
 6980: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6981: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6982: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6983: 	}
 6984: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6985: 	    $args{'CODE_ignore_dup'}=1;
 6986: 	}
 6987: 	$args{'CODE'}=$newCODE;
 6988: 	($line,$err,$errmsg)=
 6989: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6990: 				     'CODE',\%args);
 6991:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6992: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6993: 	    ($line,$err,$errmsg)=
 6994: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6995: 					 $which,'answer',
 6996: 					 { 'question'=>$question,
 6997: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6998:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6999: 	    if ($err) { last; }
 7000: 	}
 7001:     }
 7002:     if ($err) {
 7003:         $r->print(
 7004:             '<p class="LC_error">'
 7005:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7006:                 $errmsg)
 7007:            .'</p>');
 7008:     } else {
 7009: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7010: 	&scantron_putfile($scanlines,$scan_data);
 7011:     }
 7012: }
 7013: 
 7014: =pod
 7015: 
 7016: =item reset_skipping_status
 7017: 
 7018:    Forgets the current set of remember skipped scanlines (and thus
 7019:    reverts back to considering all lines in the
 7020:    scantron_skipped_<filename> file)
 7021: 
 7022: =cut
 7023: 
 7024: sub reset_skipping_status {
 7025:     my ($scanlines,$scan_data)=&scantron_getfile();
 7026:     &scan_data($scan_data,'remember_skipping',undef,1);
 7027:     &scantron_putfile(undef,$scan_data);
 7028: }
 7029: 
 7030: =pod
 7031: 
 7032: =item start_skipping
 7033: 
 7034:    Marks a scanline to be skipped. 
 7035: 
 7036: =cut
 7037: 
 7038: sub start_skipping {
 7039:     my ($scan_data,$i)=@_;
 7040:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7041:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7042: 	$remembered{$i}=2;
 7043:     } else {
 7044: 	$remembered{$i}=1;
 7045:     }
 7046:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7047: }
 7048: 
 7049: =pod
 7050: 
 7051: =item should_be_skipped
 7052: 
 7053:    Checks whether a scanline should be skipped.
 7054: 
 7055: =cut
 7056: 
 7057: sub should_be_skipped {
 7058:     my ($scanlines,$scan_data,$i)=@_;
 7059:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7060: 	# not redoing old skips
 7061: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7062: 	return 0;
 7063:     }
 7064:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7065: 
 7066:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7067: 	return 0;
 7068:     }
 7069:     return 1;
 7070: }
 7071: 
 7072: =pod
 7073: 
 7074: =item remember_current_skipped
 7075: 
 7076:    Discovers what scanlines are in the scantron_skipped_<filename>
 7077:    file and remembers them into scan_data for later use.
 7078: 
 7079: =cut
 7080: 
 7081: sub remember_current_skipped {
 7082:     my ($scanlines,$scan_data)=&scantron_getfile();
 7083:     my %to_remember;
 7084:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7085: 	if ($scanlines->{'skipped'}[$i]) {
 7086: 	    $to_remember{$i}=1;
 7087: 	}
 7088:     }
 7089: 
 7090:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7091:     &scantron_putfile(undef,$scan_data);
 7092: }
 7093: 
 7094: =pod
 7095: 
 7096: =item check_for_error
 7097: 
 7098:     Checks if there was an error when attempting to remove a specific
 7099:     scantron_.. bubblesheet data file. Prints out an error if
 7100:     something went wrong.
 7101: 
 7102: =cut
 7103: 
 7104: sub check_for_error {
 7105:     my ($r,$result)=@_;
 7106:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7107: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7108:     }
 7109: }
 7110: 
 7111: =pod
 7112: 
 7113: =item scantron_warning_screen
 7114: 
 7115:    Interstitial screen to make sure the operator has selected the
 7116:    correct options before we start the validation phase.
 7117: 
 7118: =cut
 7119: 
 7120: sub scantron_warning_screen {
 7121:     my ($button_text,$symb)=@_;
 7122:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7123:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7124:     my $CODElist;
 7125:     if ($scantron_config{'CODElocation'} &&
 7126: 	$scantron_config{'CODEstart'} &&
 7127: 	$scantron_config{'CODElength'}) {
 7128: 	$CODElist=$env{'form.scantron_CODElist'};
 7129: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7130: 	$CODElist=
 7131: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7132: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7133:     }
 7134:     my $lastbubblepoints;
 7135:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7136:         $lastbubblepoints =
 7137:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7138:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7139:     }
 7140:     return '
 7141: <p>
 7142: <span class="LC_warning">
 7143: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7144: </p>
 7145: <table>
 7146: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7147: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7148: '.$CODElist.$lastbubblepoints.'
 7149: </table>
 7150: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7151: '.&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>
 7152: ';
 7153: }
 7154: 
 7155: =pod
 7156: 
 7157: =item scantron_do_warning
 7158: 
 7159:    Check if the operator has picked something for all required
 7160:    fields. Error out if something is missing.
 7161: 
 7162: =cut
 7163: 
 7164: sub scantron_do_warning {
 7165:     my ($r,$symb)=@_;
 7166:     if (!$symb) {return '';}
 7167:     my $default_form_data=&defaultFormData($symb);
 7168:     $r->print(&scantron_form_start().$default_form_data);
 7169:     if ( $env{'form.selectpage'} eq '' ||
 7170: 	 $env{'form.scantron_selectfile'} eq '' ||
 7171: 	 $env{'form.scantron_format'} eq '' ) {
 7172: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7173: 	if ( $env{'form.selectpage'} eq '') {
 7174: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7175: 	} 
 7176: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7177: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7178: 	}
 7179: 	if ( $env{'form.scantron_format'} eq '') {
 7180: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7181: 	}
 7182:     } else {
 7183: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7184:         my ($checksec,@possibles) = &gradable_sections();
 7185:         my $gradesections;
 7186:         if ($checksec) {
 7187:             my $file=$env{'form.scantron_selectfile'};
 7188:             if (&valid_file($file)) {
 7189:                 my %bysec = &scantron_get_sections();
 7190:                 my $table;
 7191:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7192:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7193:                     $table = &Apache::loncommon::start_data_table()."\n".
 7194:                              &Apache::loncommon::start_data_table_header_row().
 7195:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7196:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7197:                     if ($bysec{'none'}) {
 7198:                         $table .= &Apache::loncommon::start_data_table_row().
 7199:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7200:                                   &Apache::loncommon::end_data_table_row()."\n";
 7201:                     }
 7202:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7203:                         next if ($sec eq 'none');
 7204:                         $table .= &Apache::loncommon::start_data_table_row().
 7205:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7206:                                   &Apache::loncommon::end_data_table_row()."\n";
 7207:                     }
 7208:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7209:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7210:                                       '<p>'.$table.'</p>';
 7211:                     if (@possibles) {
 7212:                         $gradesections .= '<p>'.
 7213:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7214:                                               scalar(@possibles)).'<br />'.
 7215:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7216:                                               '<i>'.$checksec.'</i>').' ';
 7217:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7218:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7219:                         }
 7220:                         $gradesections .= '</p>';
 7221:                     }
 7222:                 }
 7223:             } else {
 7224:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7225:             }
 7226:         }
 7227:         my $bubbledbyhand=&hand_bubble_option();
 7228: 	$r->print('
 7229: '.$warning.$gradesections.$bubbledbyhand.'
 7230: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7231: <input type="hidden" name="command" value="scantron_validate" />
 7232: ');
 7233:     }
 7234:     $r->print("</form><br />");
 7235:     return '';
 7236: }
 7237: 
 7238: =pod
 7239: 
 7240: =item scantron_form_start
 7241: 
 7242:     html hidden input for remembering all selected grading options
 7243: 
 7244: =cut
 7245: 
 7246: sub scantron_form_start {
 7247:     my ($max_bubble)=@_;
 7248:     my $result= <<SCANTRONFORM;
 7249: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7250:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7251:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7252:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7253:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7254:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7255:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7256:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7257:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7258:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7259: SCANTRONFORM
 7260: 
 7261:   my $line = 0;
 7262:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7263:        my $chunk =
 7264: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7265:        $chunk .=
 7266: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7267:        $chunk .= 
 7268:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7269:        $chunk .=
 7270:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7271:        $chunk .=
 7272:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7273:        $result .= $chunk;
 7274:        $line++;
 7275:     }
 7276:     return $result;
 7277: }
 7278: 
 7279: =pod
 7280: 
 7281: =item scantron_validate_file
 7282: 
 7283:     Dispatch routine for doing validation of a bubblesheet data file.
 7284: 
 7285:     Also processes any necessary information resets that need to
 7286:     occur before validation begins (ignore previous corrections,
 7287:     restarting the skipped records processing)
 7288: 
 7289: =cut
 7290: 
 7291: sub scantron_validate_file {
 7292:     my ($r,$symb) = @_;
 7293:     if (!$symb) {return '';}
 7294:     my $default_form_data=&defaultFormData($symb);
 7295:     
 7296:     # do the detection of only doing skipped records first before we delete
 7297:     # them when doing the corrections reset
 7298:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7299: 	&reset_skipping_status();
 7300:     }
 7301:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7302: 	&remember_current_skipped();
 7303: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7304:     }
 7305: 
 7306:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7307: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7308: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7309: 	&check_for_error($r,&scantron_remove_scan_data());
 7310: 	$env{'form.scantron_options_ignore'}='done';
 7311:     }
 7312: 
 7313:     if ($env{'form.scantron_corrections'}) {
 7314: 	&scantron_process_corrections($r);
 7315:     }
 7316: 
 7317:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7318:     my ($checksec,@gradable);
 7319:     if ($env{'request.course.sec'}) {
 7320:         ($checksec,my @possibles) = &gradable_sections();
 7321:         if ($checksec) {
 7322:             if (@possibles) {
 7323:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7324:                 if (@chosensecs) {
 7325:                     foreach my $sec (@chosensecs) {
 7326:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7327:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7328:                                 push(@gradable,$sec);
 7329:                             }
 7330:                         }
 7331:                     }
 7332:                 }
 7333:             }
 7334:             $r->print('<p><table>');
 7335:             if (@gradable) {
 7336:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7337:                 $r->print(
 7338:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7339:             } else {
 7340:                 $r->print(
 7341:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7342:             }
 7343:             $r->print('</table></p>');
 7344:         }
 7345:     }
 7346:     $r->rflush();
 7347: 
 7348:     #get the student pick code ready
 7349:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7350:     my $nav_error;
 7351:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7352:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7353:     if ($nav_error) {
 7354:         $r->print(&navmap_errormsg());
 7355:         return '';
 7356:     }
 7357:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7358:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7359:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7360:     }
 7361:     $r->print($result);
 7362:     
 7363:     my @validate_phases=( 'sequence',
 7364: 			  'ID',
 7365: 			  'CODE',
 7366: 			  'doublebubble',
 7367: 			  'missingbubbles');
 7368:     if (!$env{'form.validatepass'}) {
 7369: 	$env{'form.validatepass'} = 0;
 7370:     }
 7371:     my $currentphase=$env{'form.validatepass'};
 7372:     my %skipbysec=();
 7373: 
 7374:     my $stop=0;
 7375:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7376: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7377: 	$r->rflush();
 7378:      
 7379: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7380: 	{
 7381: 	    no strict 'refs';
 7382:             my @extras=();
 7383:             if ($validate_phases[$currentphase] eq 'ID') {
 7384:                 @extras = (\%skipbysec,$checksec,@gradable);
 7385:             }
 7386: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7387: 	}
 7388:     }
 7389:     if (!$stop) {
 7390: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7391:         my $secinfo;
 7392:         if (keys(%skipbysec) > 0) {
 7393:             my $seclist = '<ul>';
 7394:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7395:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7396:             }
 7397:             $seclist .= '</ul>';
 7398:             $secinfo = '<p class="LC_info">'.
 7399:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7400:                            $seclist).
 7401:                        '</p>';
 7402:         }
 7403: 	$r->print(&mt('Validation process complete.').'<br />'.
 7404:                   $secinfo.$warning.
 7405:                   &mt('Perform verification for each student after storage of submissions?').
 7406:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7407:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7408:                   ('&nbsp;'x3).'<label>'.
 7409:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7410:                   '</label></span><br />'.
 7411:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7412:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7413:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7414:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7415:     } else {
 7416: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7417: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7418:     }
 7419:     if ($stop) {
 7420: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7421: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7422: 	    $r->print(' '.&mt('this error').' <br />');
 7423: 
 7424: 	    $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>');
 7425: 	} else {
 7426:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7427: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7428:             } else {
 7429:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7430:             }
 7431: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7432: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7433: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7434: 	}
 7435:     }
 7436:     $r->print(" </form><br />");
 7437:     return '';
 7438: }
 7439: 
 7440: 
 7441: =pod
 7442: 
 7443: =item scantron_remove_file
 7444: 
 7445:    Removes the requested bubblesheet data file, makes sure that
 7446:    scantron_original_<filename> is never removed
 7447: 
 7448: 
 7449: =cut
 7450: 
 7451: sub scantron_remove_file {
 7452:     my ($which)=@_;
 7453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7455:     my $file='scantron_';
 7456:     if ($which eq 'corrected' || $which eq 'skipped') {
 7457: 	$file.=$which.'_';
 7458:     } else {
 7459: 	return 'refused';
 7460:     }
 7461:     $file.=$env{'form.scantron_selectfile'};
 7462:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7463: }
 7464: 
 7465: 
 7466: =pod
 7467: 
 7468: =item scantron_remove_scan_data
 7469: 
 7470:    Removes all scan_data correction for the requested bubblesheet
 7471:    data file.  (In the case that both the are doing skipped records we need
 7472:    to remember the old skipped lines for the time being so that element
 7473:    persists for a while.)
 7474: 
 7475: =cut
 7476: 
 7477: sub scantron_remove_scan_data {
 7478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7480:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7481:     my @todelete;
 7482:     my $filename=$env{'form.scantron_selectfile'};
 7483:     foreach my $key (@keys) {
 7484: 	if ($key=~/^\Q$filename\E_/) {
 7485: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7486: 		$key=~/remember_skipping/) {
 7487: 		next;
 7488: 	    }
 7489: 	    push(@todelete,$key);
 7490: 	}
 7491:     }
 7492:     my $result;
 7493:     if (@todelete) {
 7494: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7495: 				       \@todelete,$cdom,$cname);
 7496:     } else {
 7497: 	$result = 'ok';
 7498:     }
 7499:     return $result;
 7500: }
 7501: 
 7502: 
 7503: =pod
 7504: 
 7505: =item scantron_getfile
 7506: 
 7507:     Fetches the requested bubblesheet data file (all 3 versions), and
 7508:     the scan_data hash
 7509:   
 7510:   Arguments:
 7511:     None
 7512: 
 7513:   Returns:
 7514:     2 hash references
 7515: 
 7516:      - first one has 
 7517:          orig      -
 7518:          corrected -
 7519:          skipped   -  each of which points to an array ref of the specified
 7520:                       file broken up into individual lines
 7521:          count     - number of scanlines
 7522:  
 7523:      - second is the scan_data hash possible keys are
 7524:        ($number refers to scanline numbered $number and thus the key affects
 7525:         only that scanline
 7526:         $bubline refers to the specific bubble line element and the aspects
 7527:         refers to that specific bubble line element)
 7528: 
 7529:        $number.user - username:domain to use
 7530:        $number.CODE_ignore_dup 
 7531:                     - ignore the duplicate CODE error 
 7532:        $number.useCODE
 7533:                     - use the CODE in the scanline as is
 7534:        $number.no_bubble.$bubline
 7535:                     - it is valid that there is no bubbled in bubble
 7536:                       at $number $bubline
 7537:        remember_skipping
 7538:                     - a frozen hash containing keys of $number and values
 7539:                       of either 
 7540:                         1 - we are on a 'do skipped records pass' and plan
 7541:                             on processing this line
 7542:                         2 - we are on a 'do skipped records pass' and this
 7543:                             scanline has been marked to skip yet again
 7544: 
 7545: =cut
 7546: 
 7547: sub scantron_getfile {
 7548:     #FIXME really would prefer a scantron directory
 7549:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7550:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7551:     my $lines;
 7552:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7553: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7554:     my %scanlines;
 7555:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7556:     my $temp=$scanlines{'orig'};
 7557:     $scanlines{'count'}=$#$temp;
 7558: 
 7559:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7560: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7561:     if ($lines eq '-1') {
 7562: 	$scanlines{'corrected'}=[];
 7563:     } else {
 7564: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7565:     }
 7566:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7567: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7568:     if ($lines eq '-1') {
 7569: 	$scanlines{'skipped'}=[];
 7570:     } else {
 7571: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7572:     }
 7573:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7574:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7575:     my %scan_data = @tmp;
 7576:     return (\%scanlines,\%scan_data);
 7577: }
 7578: 
 7579: =pod
 7580: 
 7581: =item lonnet_putfile
 7582: 
 7583:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7584: 
 7585:  Arguments:
 7586:    $contents - data to store
 7587:    $filename - filename to store $contents into
 7588: 
 7589:  Returns:
 7590:    result value from &Apache::lonnet::finishuserfileupload
 7591: 
 7592: =cut
 7593: 
 7594: sub lonnet_putfile {
 7595:     my ($contents,$filename)=@_;
 7596:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7597:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7598:     $env{'form.sillywaytopassafilearound'}=$contents;
 7599:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7600: 
 7601: }
 7602: 
 7603: =pod
 7604: 
 7605: =item scantron_putfile
 7606: 
 7607:     Stores the current version of the bubblesheet data files, and the
 7608:     scan_data hash. (Does not modify the original version only the
 7609:     corrected and skipped versions.
 7610: 
 7611:  Arguments:
 7612:     $scanlines - hash ref that looks like the first return value from
 7613:                  &scantron_getfile()
 7614:     $scan_data - hash ref that looks like the second return value from
 7615:                  &scantron_getfile()
 7616: 
 7617: =cut
 7618: 
 7619: sub scantron_putfile {
 7620:     my ($scanlines,$scan_data) = @_;
 7621:     #FIXME really would prefer a scantron directory
 7622:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7623:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7624:     if ($scanlines) {
 7625: 	my $prefix='scantron_';
 7626: # no need to update orig, shouldn't change
 7627: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7628: #		    $env{'form.scantron_selectfile'});
 7629: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7630: 			$prefix.'corrected_'.
 7631: 			$env{'form.scantron_selectfile'});
 7632: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7633: 			$prefix.'skipped_'.
 7634: 			$env{'form.scantron_selectfile'});
 7635:     }
 7636:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7637: }
 7638: 
 7639: =pod
 7640: 
 7641: =item scantron_get_line
 7642: 
 7643:    Returns the correct version of the scanline
 7644: 
 7645:  Arguments:
 7646:     $scanlines - hash ref that looks like the first return value from
 7647:                  &scantron_getfile()
 7648:     $scan_data - hash ref that looks like the second return value from
 7649:                  &scantron_getfile()
 7650:     $i         - number of the requested line (starts at 0)
 7651: 
 7652:  Returns:
 7653:    A scanline, (either the original or the corrected one if it
 7654:    exists), or undef if the requested scanline should be
 7655:    skipped. (Either because it's an skipped scanline, or it's an
 7656:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7657:    pass.
 7658: 
 7659: =cut
 7660: 
 7661: sub scantron_get_line {
 7662:     my ($scanlines,$scan_data,$i)=@_;
 7663:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7664:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7665:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7666:     return $scanlines->{'orig'}[$i]; 
 7667: }
 7668: 
 7669: =pod
 7670: 
 7671: =item scantron_todo_count
 7672: 
 7673:     Counts the number of scanlines that need processing.
 7674: 
 7675:  Arguments:
 7676:     $scanlines - hash ref that looks like the first return value from
 7677:                  &scantron_getfile()
 7678:     $scan_data - hash ref that looks like the second return value from
 7679:                  &scantron_getfile()
 7680: 
 7681:  Returns:
 7682:     $count - number of scanlines to process
 7683: 
 7684: =cut
 7685: 
 7686: sub get_todo_count {
 7687:     my ($scanlines,$scan_data)=@_;
 7688:     my $count=0;
 7689:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7690: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7691: 	if ($line=~/^[\s\cz]*$/) { next; }
 7692: 	$count++;
 7693:     }
 7694:     return $count;
 7695: }
 7696: 
 7697: =pod
 7698: 
 7699: =item scantron_put_line
 7700: 
 7701:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7702:     data file.
 7703: 
 7704:  Arguments:
 7705:     $scanlines - hash ref that looks like the first return value from
 7706:                  &scantron_getfile()
 7707:     $scan_data - hash ref that looks like the second return value from
 7708:                  &scantron_getfile()
 7709:     $i         - line number to update
 7710:     $newline   - contents of the updated scanline
 7711:     $skip      - if true make the line for skipping and update the
 7712:                  'skipped' file
 7713: 
 7714: =cut
 7715: 
 7716: sub scantron_put_line {
 7717:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7718:     if ($skip) {
 7719: 	$scanlines->{'skipped'}[$i]=$newline;
 7720: 	&start_skipping($scan_data,$i);
 7721: 	return;
 7722:     }
 7723:     $scanlines->{'corrected'}[$i]=$newline;
 7724: }
 7725: 
 7726: =pod
 7727: 
 7728: =item scantron_clear_skip
 7729: 
 7730:    Remove a line from the 'skipped' file
 7731: 
 7732:  Arguments:
 7733:     $scanlines - hash ref that looks like the first return value from
 7734:                  &scantron_getfile()
 7735:     $scan_data - hash ref that looks like the second return value from
 7736:                  &scantron_getfile()
 7737:     $i         - line number to update
 7738: 
 7739: =cut
 7740: 
 7741: sub scantron_clear_skip {
 7742:     my ($scanlines,$scan_data,$i)=@_;
 7743:     if (exists($scanlines->{'skipped'}[$i])) {
 7744: 	undef($scanlines->{'skipped'}[$i]);
 7745: 	return 1;
 7746:     }
 7747:     return 0;
 7748: }
 7749: 
 7750: =pod
 7751: 
 7752: =item scantron_filter_not_exam
 7753: 
 7754:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7755:    filter out resources that are not marked as 'exam' mode
 7756: 
 7757: =cut
 7758: 
 7759: sub scantron_filter_not_exam {
 7760:     my ($curres)=@_;
 7761:     
 7762:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7763: 	# if the user has asked to not have either hidden
 7764: 	# or 'randomout' controlled resources to be graded
 7765: 	# don't include them
 7766: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7767: 	    && $curres->randomout) {
 7768: 	    return 0;
 7769: 	}
 7770: 	return 1;
 7771:     }
 7772:     return 0;
 7773: }
 7774: 
 7775: =pod
 7776: 
 7777: =item scantron_validate_sequence
 7778: 
 7779:     Validates the selected sequence, checking for resource that are
 7780:     not set to exam mode.
 7781: 
 7782: =cut
 7783: 
 7784: sub scantron_validate_sequence {
 7785:     my ($r,$currentphase) = @_;
 7786: 
 7787:     my $navmap=Apache::lonnavmaps::navmap->new();
 7788:     unless (ref($navmap)) {
 7789:         $r->print(&navmap_errormsg());
 7790:         return (1,$currentphase);
 7791:     }
 7792:     my (undef,undef,$sequence)=
 7793: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7794: 
 7795:     my $map=$navmap->getResourceByUrl($sequence);
 7796: 
 7797:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7798:                                     value="ignore" />');
 7799:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7800: 	my @resources=
 7801: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7802: 	if (@resources) {
 7803: 	    $r->print(
 7804:                 '<p class="LC_warning">'
 7805:                .&mt('Some resources in the sequence currently are not set to'
 7806:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7807:                    .' work correctly.')
 7808:                .'</p>'
 7809:             );
 7810: 	    return (1,$currentphase);
 7811: 	}
 7812:     }
 7813: 
 7814:     return (0,$currentphase+1);
 7815: }
 7816: 
 7817: 
 7818: 
 7819: sub scantron_validate_ID {
 7820:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7821:     
 7822:     #get student info
 7823:     my $classlist=&Apache::loncoursedata::get_classlist();
 7824:     my %idmap=&username_to_idmap($classlist);
 7825:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7826: 
 7827:     #get scantron line setup
 7828:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7829:     my ($scanlines,$scan_data)=&scantron_getfile();
 7830: 
 7831:     my $nav_error;
 7832:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7833:     if ($nav_error) {
 7834:         $r->print(&navmap_errormsg());
 7835:         return(1,$currentphase);
 7836:     }
 7837: 
 7838:     my %found=('ids'=>{},'usernames'=>{});
 7839:     my $unsavedskips = 0;
 7840:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7841: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7842: 	if ($line=~/^[\s\cz]*$/) { next; }
 7843: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7844: 						 $scan_data);
 7845: 	my $id=$$scan_record{'scantron.ID'};
 7846: 	my $found;
 7847: 	foreach my $checkid (keys(%idmap)) {
 7848: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7849: 	}
 7850: 	if ($found) {
 7851: 	    my $username=$idmap{$found};
 7852:             if ($checksec) {
 7853:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7854:                     my $stusec = $classlist->{$username}->[$secidx];
 7855:                     if ($stusec ne $checksec) {
 7856:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7857:                             my $skip=1;
 7858:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7859:                             if (ref($skipbysec) eq 'HASH') {
 7860:                                 if ($stusec eq '') {
 7861:                                     $skipbysec->{'none'} ++;
 7862:                                 } else {
 7863:                                     $skipbysec->{$stusec} ++;
 7864:                                 }
 7865:                             }
 7866:                             $unsavedskips ++;
 7867:                             next;
 7868:                         }
 7869:                     }
 7870:                 }
 7871:             }
 7872: 	    if ($found{'ids'}{$found}) {
 7873: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7874: 					 $line,'duplicateID',$found);
 7875:                 if ($unsavedskips) {
 7876:                     &scantron_putfile($scanlines,$scan_data);
 7877:                     $unsavedskips = 0;
 7878:                 }
 7879: 		return(1,$currentphase);
 7880: 	    } elsif ($found{'usernames'}{$username}) {
 7881: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7882: 					 $line,'duplicateID',$username);
 7883:                 if ($unsavedskips) {
 7884:                     &scantron_putfile($scanlines,$scan_data);
 7885:                     $unsavedskips = 0;
 7886:                 }
 7887: 		return(1,$currentphase);
 7888: 	    }
 7889: 	    #FIXME store away line we previously saw the ID on to use above
 7890: 	    $found{'ids'}{$found}++;
 7891: 	    $found{'usernames'}{$username}++;
 7892: 	} else {
 7893: 	    if ($id =~ /^\s*$/) {
 7894: 		my $username=&scan_data($scan_data,"$i.user");
 7895:                 if (($checksec && $username ne '')) {
 7896:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 7897:                         my $stusec = $classlist->{$username}->[$secidx];
 7898:                         if ($stusec ne $checksec) {
 7899:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7900:                                 my $skip=1;
 7901:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7902:                                 if (ref($skipbysec) eq 'HASH') {
 7903:                                     if ($stusec eq '') {
 7904:                                         $skipbysec->{'none'} ++;
 7905:                                     } else {
 7906:                                         $skipbysec->{$stusec} ++;
 7907:                                     }
 7908:                                 }
 7909:                                 $unsavedskips ++;
 7910:                                 next;
 7911:                             }
 7912:                         }
 7913:                     }
 7914: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 7915: 		    &scantron_get_correction($r,$i,$scan_record,
 7916: 					     \%scantron_config,
 7917: 					     $line,'duplicateID',$username);
 7918:                     if ($unsavedskips) {
 7919:                         &scantron_putfile($scanlines,$scan_data);
 7920:                         $unsavedskips = 0;
 7921:                     }
 7922: 		    return(1,$currentphase);
 7923: 		} elsif (!defined($username)) {
 7924: 		    &scantron_get_correction($r,$i,$scan_record,
 7925: 					     \%scantron_config,
 7926: 					     $line,'incorrectID');
 7927:                     if ($unsavedskips) {
 7928:                         &scantron_putfile($scanlines,$scan_data);
 7929:                         $unsavedskips = 0;
 7930:                     }
 7931: 		    return(1,$currentphase);
 7932: 		}
 7933: 		$found{'usernames'}{$username}++;
 7934: 	    } else {
 7935: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7936: 					 $line,'incorrectID');
 7937:                 if ($unsavedskips) {
 7938:                     &scantron_putfile($scanlines,$scan_data);
 7939:                     $unsavedskips = 0;
 7940:                 }
 7941: 		return(1,$currentphase);
 7942: 	    }
 7943: 	}
 7944:     }
 7945:     if ($unsavedskips) {
 7946:         &scantron_putfile($scanlines,$scan_data);
 7947:         $unsavedskips = 0;
 7948:     }
 7949:     return (0,$currentphase+1);
 7950: }
 7951: 
 7952: sub scantron_get_sections {
 7953:     my %bysec;
 7954:     if ($env{'form.scantron_format'} ne '') {
 7955:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7956:         my ($scanlines,$scan_data)=&scantron_getfile();
 7957:         my $classlist=&Apache::loncoursedata::get_classlist();
 7958:         my %idmap=&username_to_idmap($classlist);
 7959:         foreach my $key (keys(%idmap)) {
 7960:             my $lckey = lc($key);
 7961:             $idmap{$lckey} = $idmap{$key};
 7962:         }
 7963:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 7964:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7965:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7966:             if ($line=~/^[\s\cz]*$/) { next; }
 7967:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7968:                                                      $scan_data);
 7969:             my $id=lc($$scan_record{'scantron.ID'});
 7970:             if (exists($idmap{$id})) {
 7971:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 7972:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 7973:                     if ($stusec eq '') {
 7974:                         $bysec{'none'} ++;
 7975:                     } else {
 7976:                         $bysec{$stusec} ++;
 7977:                     }
 7978:                 }
 7979:             }
 7980:         }
 7981:     }
 7982:     return %bysec;
 7983: }
 7984: 
 7985: sub scantron_get_correction {
 7986:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7987:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7988: #FIXME in the case of a duplicated ID the previous line, probably need
 7989: #to show both the current line and the previous one and allow skipping
 7990: #the previous one or the current one
 7991: 
 7992:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7993:         $r->print(
 7994:             '<p class="LC_warning">'
 7995:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7996:                 "<b>$error</b>",
 7997:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7998:            ."</p> \n");
 7999:     } else {
 8000:         $r->print(
 8001:             '<p class="LC_warning">'
 8002:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8003:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8004:            ."</p> \n");
 8005:     }
 8006:     my $message =
 8007:         '<p>'
 8008:        .&mt('The ID on the form is [_1]',
 8009:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8010:        .'<br />'
 8011:        .&mt('The name on the paper is [_1], [_2]',
 8012:             $$scan_record{'scantron.LastName'},
 8013:             $$scan_record{'scantron.FirstName'})
 8014:        .'</p>';
 8015: 
 8016:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8017:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8018:                            # Array populated for doublebubble or
 8019:     my @lines_to_correct;  # missingbubble errors to build javascript
 8020:                            # to validate radio button checking   
 8021: 
 8022:     if ($error =~ /ID$/) {
 8023: 	if ($error eq 'incorrectID') {
 8024:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8025: 		      "</p>\n");
 8026: 	} elsif ($error eq 'duplicateID') {
 8027:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8028: 	}
 8029: 	$r->print($message);
 8030: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8031: 	$r->print("\n<ul><li> ");
 8032: 	#FIXME it would be nice if this sent back the user ID and
 8033: 	#could do partial userID matches
 8034: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8035: 				       'scantron_username','scantron_domain'));
 8036: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8037: 	$r->print("\n:\n".
 8038: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8039: 
 8040: 	$r->print('</li>');
 8041:     } elsif ($error =~ /CODE$/) {
 8042: 	if ($error eq 'incorrectCODE') {
 8043: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8044: 	} elsif ($error eq 'duplicateCODE') {
 8045: 	    $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");
 8046: 	}
 8047: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8048: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8049:                  ."</p>\n");
 8050: 	$r->print($message);
 8051: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8052: 	$r->print("\n<br /> ");
 8053: 	my $i=0;
 8054: 	if ($error eq 'incorrectCODE' 
 8055: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8056: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8057: 	    if ($closest > 0) {
 8058: 		foreach my $testcode (@{$closest}) {
 8059: 		    my $checked='';
 8060: 		    if (!$i) { $checked=' checked="checked"'; }
 8061: 		    $r->print("
 8062:    <label>
 8063:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8064:        ".&mt("Use the similar CODE [_1] instead.",
 8065: 	    "<b><tt>".$testcode."</tt></b>")."
 8066:     </label>
 8067:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8068: 		    $r->print("\n<br />");
 8069: 		    $i++;
 8070: 		}
 8071: 	    }
 8072: 	}
 8073: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8074: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8075: 	    $r->print("
 8076:     <label>
 8077:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8078:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8079: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8080:     </label>");
 8081: 	    $r->print("\n<br />");
 8082: 	}
 8083: 
 8084: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8085: function change_radio(field) {
 8086:     var slct=document.scantronupload.scantron_CODE_resolution;
 8087:     var i;
 8088:     for (i=0;i<slct.length;i++) {
 8089:         if (slct[i].value==field) { slct[i].checked=true; }
 8090:     }
 8091: }
 8092: ENDSCRIPT
 8093: 	my $href="/adm/pickcode?".
 8094: 	   "form=".&escape("scantronupload").
 8095: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8096: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8097: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8098: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8099: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8100: 	    $r->print("
 8101:     <label>
 8102:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8103:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8104: 	     "<a target='_blank' href='$href'>","</a>")."
 8105:     </label> 
 8106:     ".&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\')" />'));
 8107: 	    $r->print("\n<br />");
 8108: 	}
 8109: 	$r->print("
 8110:     <label>
 8111:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8112:        ".&mt("Use [_1] as the CODE.",
 8113: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8114: 	$r->print("\n<br /><br />");
 8115:     } elsif ($error eq 'doublebubble') {
 8116: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8117: 
 8118: 	# The form field scantron_questions is acutally a list of line numbers.
 8119: 	# represented by this form so:
 8120: 
 8121: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8122:                                                 $respnumlookup,$startline);
 8123: 
 8124: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8125: 		  $line_list.'" />');
 8126: 	$r->print($message);
 8127: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8128: 	foreach my $question (@{$arg}) {
 8129: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8130:                                                    $scan_record, $error,
 8131:                                                    $randomorder,$randompick,
 8132:                                                    $respnumlookup,$startline);
 8133:             push(@lines_to_correct,@linenums);
 8134: 	}
 8135:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8136:     } elsif ($error eq 'missingbubble') {
 8137: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8138: 	$r->print($message);
 8139: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8140: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8141: 
 8142: 	# The form field scantron_questions is actually a list of line numbers not
 8143: 	# a list of question numbers. Therefore:
 8144: 	#
 8145: 
 8146: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8147:                                                 $respnumlookup,$startline);
 8148: 
 8149: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8150: 		  $line_list.'" />');
 8151: 	foreach my $question (@{$arg}) {
 8152: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8153:                                                    $scan_record, $error,
 8154:                                                    $randomorder,$randompick,
 8155:                                                    $respnumlookup,$startline);
 8156:             push(@lines_to_correct,@linenums);
 8157: 	}
 8158:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8159:     } else {
 8160: 	$r->print("\n<ul>");
 8161:     }
 8162:     $r->print("\n</li></ul>");
 8163: }
 8164: 
 8165: sub verify_bubbles_checked {
 8166:     my (@ansnums) = @_;
 8167:     my $ansnumstr = join('","',@ansnums);
 8168:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8169:     &js_escape(\$warning);
 8170:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8171: function verify_bubble_radio(form) {
 8172:     var ansnumArray = new Array ("$ansnumstr");
 8173:     var need_bubble_count = 0;
 8174:     for (var i=0; i<ansnumArray.length; i++) {
 8175:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8176:             var bubble_picked = 0; 
 8177:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8178:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8179:                     bubble_picked = 1;
 8180:                 }
 8181:             }
 8182:             if (bubble_picked == 0) {
 8183:                 need_bubble_count ++;
 8184:             }
 8185:         }
 8186:     }
 8187:     if (need_bubble_count) {
 8188:         alert("$warning");
 8189:         return;
 8190:     }
 8191:     form.submit(); 
 8192: }
 8193: ENDSCRIPT
 8194:     return $output;
 8195: }
 8196: 
 8197: =pod
 8198: 
 8199: =item  questions_to_line_list
 8200: 
 8201: Converts a list of questions into a string of comma separated
 8202: line numbers in the answer sheet used by the questions.  This is
 8203: used to fill in the scantron_questions form field.
 8204: 
 8205:   Arguments:
 8206:      questions    - Reference to an array of questions.
 8207:      randomorder  - True if randomorder in use.
 8208:      randompick   - True if randompick in use.
 8209:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8210:                      for current line to question number used for same question
 8211:                      in "Master Seqence" (as seen by Course Coordinator).
 8212:      startline    - Reference to hash where key is question number (0 is first)
 8213:                     and key is number of first bubble line for current student
 8214:                     or code-based randompick and/or randomorder.
 8215: 
 8216: =cut
 8217: 
 8218: 
 8219: sub questions_to_line_list {
 8220:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8221:     my @lines;
 8222: 
 8223:     foreach my $item (@{$questions}) {
 8224:         my $question = $item;
 8225:         my ($first,$count,$last);
 8226:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8227:             $question = $1;
 8228:             my $subquestion = $2;
 8229:             my $responsenum = $question-1;
 8230:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8231:                 $responsenum = $respnumlookup->{$question-1};
 8232:                 if (ref($startline) eq 'HASH') {
 8233:                     $first = $startline->{$question-1} + 1;
 8234:                 }
 8235:             } else {
 8236:                 $first = $first_bubble_line{$responsenum} + 1;
 8237:             }
 8238:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8239:             my $subcount = 1;
 8240:             while ($subcount<$subquestion) {
 8241:                 $first += $subans[$subcount-1];
 8242:                 $subcount ++;
 8243:             }
 8244:             $count = $subans[$subquestion-1];
 8245:         } else {
 8246:             my $responsenum = $question-1;
 8247:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8248:                 $responsenum = $respnumlookup->{$question-1};
 8249:                 if (ref($startline) eq 'HASH') {
 8250:                     $first = $startline->{$question-1} + 1;
 8251:                 }
 8252:             } else {
 8253:                 $first = $first_bubble_line{$responsenum} + 1;
 8254:             }
 8255: 	    $count   = $bubble_lines_per_response{$responsenum};
 8256:         }
 8257:         $last = $first+$count-1;
 8258:         push(@lines, ($first..$last));
 8259:     }
 8260:     return join(',', @lines);
 8261: }
 8262: 
 8263: =pod 
 8264: 
 8265: =item prompt_for_corrections
 8266: 
 8267: Prompts for a potentially multiline correction to the
 8268: user's bubbling (factors out common code from scantron_get_correction
 8269: for multi and missing bubble cases).
 8270: 
 8271:  Arguments:
 8272:    $r           - Apache request object.
 8273:    $question    - The question number to prompt for.
 8274:    $scan_config - The scantron file configuration hash.
 8275:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8276:    $error       - Type of error
 8277:    $randomorder - True if randomorder in use.
 8278:    $randompick  - True if randompick in use.
 8279:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8280:                     for current line to question number used for same question
 8281:                     in "Master Seqence" (as seen by Course Coordinator).
 8282:    $startline   - Reference to hash where key is question number (0 is first)
 8283:                   and value is number of first bubble line for current student
 8284:                   or code-based randompick and/or randomorder.
 8285: 
 8286: 
 8287:  Implicit inputs:
 8288:    %bubble_lines_per_response   - Starting line numbers for each question.
 8289:                                   Numbered from 0 (but question numbers are from
 8290:                                   1.
 8291:    %first_bubble_line           - Starting bubble line for each question.
 8292:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8293:                                   type problems render as separate sub-questions, 
 8294:                                   in exam mode. This hash contains a 
 8295:                                   comma-separated list of the lines per 
 8296:                                   sub-question.
 8297:    %responsetype_per_response   - essayresponse, formularesponse,
 8298:                                   stringresponse, imageresponse, reactionresponse,
 8299:                                   and organicresponse type problem parts can have
 8300:                                   multiple lines per response if the weight
 8301:                                   assigned exceeds 10.  In this case, only
 8302:                                   one bubble per line is permitted, but more 
 8303:                                   than one line might contain bubbles, e.g.
 8304:                                   bubbling of: line 1 - J, line 2 - J, 
 8305:                                   line 3 - B would assign 22 points.  
 8306: 
 8307: =cut
 8308: 
 8309: sub prompt_for_corrections {
 8310:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8311:         $randompick, $respnumlookup, $startline) = @_;
 8312:     my ($current_line,$lines);
 8313:     my @linenums;
 8314:     my $questionnum = $question;
 8315:     my ($first,$responsenum);
 8316:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8317:         $question = $1;
 8318:         my $subquestion = $2;
 8319:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8320:             $responsenum = $respnumlookup->{$question-1};
 8321:             if (ref($startline) eq 'HASH') {
 8322:                 $first = $startline->{$question-1};
 8323:             }
 8324:         } else {
 8325:             $responsenum = $question-1;
 8326:             $first = $first_bubble_line{$responsenum};
 8327:         }
 8328:         $current_line = $first + 1 ;
 8329:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8330:         my $subcount = 1;
 8331:         while ($subcount<$subquestion) {
 8332:             $current_line += $subans[$subcount-1];
 8333:             $subcount ++;
 8334:         }
 8335:         $lines = $subans[$subquestion-1];
 8336:     } else {
 8337:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8338:             $responsenum = $respnumlookup->{$question-1};
 8339:             if (ref($startline) eq 'HASH') { 
 8340:                 $first = $startline->{$question-1};
 8341:             }
 8342:         } else {
 8343:             $responsenum = $question-1;
 8344:             $first = $first_bubble_line{$responsenum};
 8345:         }
 8346:         $current_line = $first + 1;
 8347:         $lines        = $bubble_lines_per_response{$responsenum};
 8348:     }
 8349:     if ($lines > 1) {
 8350:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8351:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8352:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8353:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8354:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8355:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8356:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8357:             $r->print(
 8358:                 &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)
 8359:                .'<br /><br />'
 8360:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8361:                .'<br />'
 8362:                .&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.')
 8363:                .'<br />'
 8364:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8365:                .'<br /><br />'
 8366:             );
 8367:         } else {
 8368:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8369:         }
 8370:     }
 8371:     for (my $i =0; $i < $lines; $i++) {
 8372:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8373: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8374: 	        		  $questionnum,$error,split('', $selected));
 8375:         push(@linenums,$current_line);
 8376: 	$current_line++;
 8377:     }
 8378:     if ($lines > 1) {
 8379: 	$r->print("<hr /><br />");
 8380:     }
 8381:     return @linenums;
 8382: }
 8383: 
 8384: =pod
 8385: 
 8386: =item scantron_bubble_selector
 8387:   
 8388:    Generates the html radiobuttons to correct a single bubble line
 8389:    possibly showing the existing the selected bubbles if known
 8390: 
 8391:  Arguments:
 8392:     $r           - Apache request object
 8393:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8394:     $line        - Number of the line being displayed.
 8395:     $questionnum - Question number (may include subquestion)
 8396:     $error       - Type of error.
 8397:     @selected    - Array of bubbles picked on this line.
 8398: 
 8399: =cut
 8400: 
 8401: sub scantron_bubble_selector {
 8402:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8403:     my $max=$$scan_config{'Qlength'};
 8404: 
 8405:     my $scmode=$$scan_config{'Qon'};
 8406:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8407:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8408:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8409:             $max=$$scan_config{'BubblesPerRow'};
 8410:             if (($scmode eq 'number') && ($max > 10)) {
 8411:                 $max = 10;
 8412:             } elsif (($scmode eq 'letter') && $max > 26) {
 8413:                 $max = 26;
 8414:             }
 8415:         } else {
 8416:             $max = 10;
 8417:         }
 8418:     }
 8419: 
 8420:     my @alphabet=('A'..'Z');
 8421:     $r->print(&Apache::loncommon::start_data_table().
 8422:               &Apache::loncommon::start_data_table_row());
 8423:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8424:     for (my $i=0;$i<$max+1;$i++) {
 8425: 	$r->print("\n".'<td align="center">');
 8426: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8427: 	else { $r->print('&nbsp;'); }
 8428: 	$r->print('</td>');
 8429:     }
 8430:     $r->print(&Apache::loncommon::end_data_table_row().
 8431:               &Apache::loncommon::start_data_table_row());
 8432:     for (my $i=0;$i<$max;$i++) {
 8433: 	$r->print("\n".
 8434: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8435: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8436:     }
 8437:     my $nobub_checked = ' ';
 8438:     if ($error eq 'missingbubble') {
 8439:         $nobub_checked = ' checked = "checked" ';
 8440:     }
 8441:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8442: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8443:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8444:               $line.'" value="'.$questionnum.'" /></td>');
 8445:     $r->print(&Apache::loncommon::end_data_table_row().
 8446:               &Apache::loncommon::end_data_table());
 8447: }
 8448: 
 8449: =pod
 8450: 
 8451: =item num_matches
 8452: 
 8453:    Counts the number of characters that are the same between the two arguments.
 8454: 
 8455:  Arguments:
 8456:    $orig - CODE from the scanline
 8457:    $code - CODE to match against
 8458: 
 8459:  Returns:
 8460:    $count - integer count of the number of same characters between the
 8461:             two arguments
 8462: 
 8463: =cut
 8464: 
 8465: sub num_matches {
 8466:     my ($orig,$code) = @_;
 8467:     my @code=split(//,$code);
 8468:     my @orig=split(//,$orig);
 8469:     my $same=0;
 8470:     for (my $i=0;$i<scalar(@code);$i++) {
 8471: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8472:     }
 8473:     return $same;
 8474: }
 8475: 
 8476: =pod
 8477: 
 8478: =item scantron_get_closely_matching_CODEs
 8479: 
 8480:    Cycles through all CODEs and finds the set that has the greatest
 8481:    number of same characters as the provided CODE
 8482: 
 8483:  Arguments:
 8484:    $allcodes - hash ref returned by &get_codes()
 8485:    $CODE     - CODE from the current scanline
 8486: 
 8487:  Returns:
 8488:    2 element list
 8489:     - first elements is number of how closely matching the best fit is 
 8490:       (5 means best set has 5 matching characters)
 8491:     - second element is an arrary ref containing the set of valid CODEs
 8492:       that best fit the passed in CODE
 8493: 
 8494: =cut
 8495: 
 8496: sub scantron_get_closely_matching_CODEs {
 8497:     my ($allcodes,$CODE)=@_;
 8498:     my @CODEs;
 8499:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8500: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8501:     }
 8502: 
 8503:     return ($#CODEs,$CODEs[-1]);
 8504: }
 8505: 
 8506: =pod
 8507: 
 8508: =item get_codes
 8509: 
 8510:    Builds a hash which has keys of all of the valid CODEs from the selected
 8511:    set of remembered CODEs.
 8512: 
 8513:  Arguments:
 8514:   $old_name - name of the set of remembered CODEs
 8515:   $cdom     - domain of the course
 8516:   $cnum     - internal course name
 8517: 
 8518:  Returns:
 8519:   %allcodes - keys are the valid CODEs, values are all 1
 8520: 
 8521: =cut
 8522: 
 8523: sub get_codes {
 8524:     my ($old_name, $cdom, $cnum) = @_;
 8525:     if (!$old_name) {
 8526: 	$old_name=$env{'form.scantron_CODElist'};
 8527:     }
 8528:     if (!$cdom) {
 8529: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8530:     }
 8531:     if (!$cnum) {
 8532: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8533:     }
 8534:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8535: 				    $cdom,$cnum);
 8536:     my %allcodes;
 8537:     if ($result{"type\0$old_name"} eq 'number') {
 8538: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8539:     } else {
 8540: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8541:     }
 8542:     return %allcodes;
 8543: }
 8544: 
 8545: =pod
 8546: 
 8547: =item scantron_validate_CODE
 8548: 
 8549:    Validates all scanlines in the selected file to not have any
 8550:    invalid or underspecified CODEs and that none of the codes are
 8551:    duplicated if this was requested.
 8552: 
 8553: =cut
 8554: 
 8555: sub scantron_validate_CODE {
 8556:     my ($r,$currentphase) = @_;
 8557:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8558:     if ($scantron_config{'CODElocation'} &&
 8559: 	$scantron_config{'CODEstart'} &&
 8560: 	$scantron_config{'CODElength'}) {
 8561: 	if (!defined($env{'form.scantron_CODElist'})) {
 8562: 	    &FIXME_blow_up()
 8563: 	}
 8564:     } else {
 8565: 	return (0,$currentphase+1);
 8566:     }
 8567:     
 8568:     my %usedCODEs;
 8569: 
 8570:     my %allcodes=&get_codes();
 8571: 
 8572:     my $nav_error;
 8573:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8574:     if ($nav_error) {
 8575:         $r->print(&navmap_errormsg());
 8576:         return(1,$currentphase);
 8577:     }
 8578: 
 8579:     my ($scanlines,$scan_data)=&scantron_getfile();
 8580:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8581: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8582: 	if ($line=~/^[\s\cz]*$/) { next; }
 8583: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8584: 						 $scan_data);
 8585: 	my $CODE=$$scan_record{'scantron.CODE'};
 8586: 	my $error=0;
 8587: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8588: 	    &scantron_get_correction($r,$i,$scan_record,
 8589: 				     \%scantron_config,
 8590: 				     $line,'incorrectCODE',\%allcodes);
 8591: 	    return(1,$currentphase);
 8592: 	}
 8593: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8594: 	    && !$$scan_record{'scantron.useCODE'}) {
 8595: 	    &scantron_get_correction($r,$i,$scan_record,
 8596: 				     \%scantron_config,
 8597: 				     $line,'incorrectCODE',\%allcodes);
 8598: 	    return(1,$currentphase);
 8599: 	}
 8600: 	if (exists($usedCODEs{$CODE}) 
 8601: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8602: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8603: 	    &scantron_get_correction($r,$i,$scan_record,
 8604: 				     \%scantron_config,
 8605: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8606: 	    return(1,$currentphase);
 8607: 	}
 8608: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8609:     }
 8610:     return (0,$currentphase+1);
 8611: }
 8612: 
 8613: =pod
 8614: 
 8615: =item scantron_validate_doublebubble
 8616: 
 8617:    Validates all scanlines in the selected file to not have any
 8618:    bubble lines with multiple bubbles marked.
 8619: 
 8620: =cut
 8621: 
 8622: sub scantron_validate_doublebubble {
 8623:     my ($r,$currentphase) = @_;
 8624:     #get student info
 8625:     my $classlist=&Apache::loncoursedata::get_classlist();
 8626:     my %idmap=&username_to_idmap($classlist);
 8627:     my (undef,undef,$sequence)=
 8628:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8629: 
 8630:     #get scantron line setup
 8631:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8632:     my ($scanlines,$scan_data)=&scantron_getfile();
 8633: 
 8634:     my $navmap = Apache::lonnavmaps::navmap->new();
 8635:     unless (ref($navmap)) {
 8636:         $r->print(&navmap_errormsg());
 8637:         return(1,$currentphase);
 8638:     }
 8639:     my $map=$navmap->getResourceByUrl($sequence);
 8640:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8641:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8642:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8643:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8644: 
 8645:     my $nav_error;
 8646:     if (ref($map)) {
 8647:         $randomorder = $map->randomorder();
 8648:         $randompick = $map->randompick();
 8649:         if ($randomorder || $randompick) {
 8650:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8651:             if ($nav_error) {
 8652:                 $r->print(&navmap_errormsg());
 8653:                 return(1,$currentphase);
 8654:             }
 8655:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8656:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8657:         }
 8658:     } else {
 8659:         $r->print(&navmap_errormsg());
 8660:         return(1,$currentphase);
 8661:     }
 8662: 
 8663:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8664:     if ($nav_error) {
 8665:         $r->print(&navmap_errormsg());
 8666:         return(1,$currentphase);
 8667:     }
 8668: 
 8669:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8670: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8671: 	if ($line=~/^[\s\cz]*$/) { next; }
 8672: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8673: 						 $scan_data,undef,\%idmap,$randomorder,
 8674:                                                  $randompick,$sequence,\@master_seq,
 8675:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8676:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8677: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8678: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8679: 				 'doublebubble',
 8680: 				 $$scan_record{'scantron.doubleerror'},
 8681:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8682:     	return (1,$currentphase);
 8683:     }
 8684:     return (0,$currentphase+1);
 8685: }
 8686: 
 8687: 
 8688: sub scantron_get_maxbubble {
 8689:     my ($nav_error,$scantron_config) = @_;
 8690:     if (defined($env{'form.scantron_maxbubble'}) &&
 8691: 	$env{'form.scantron_maxbubble'}) {
 8692: 	&restore_bubble_lines();
 8693: 	return $env{'form.scantron_maxbubble'};
 8694:     }
 8695: 
 8696:     my (undef, undef, $sequence) =
 8697: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8698: 
 8699:     my $navmap=Apache::lonnavmaps::navmap->new();
 8700:     unless (ref($navmap)) {
 8701:         if (ref($nav_error)) {
 8702:             $$nav_error = 1;
 8703:         }
 8704:         return;
 8705:     }
 8706:     my $map=$navmap->getResourceByUrl($sequence);
 8707:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8708:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8709: 
 8710:     &Apache::lonxml::clear_problem_counter();
 8711: 
 8712:     my $uname       = $env{'user.name'};
 8713:     my $udom        = $env{'user.domain'};
 8714:     my $cid         = $env{'request.course.id'};
 8715:     my $total_lines = 0;
 8716:     %bubble_lines_per_response = ();
 8717:     %first_bubble_line         = ();
 8718:     %subdivided_bubble_lines   = ();
 8719:     %responsetype_per_response = ();
 8720:     %masterseq_id_responsenum  = ();
 8721: 
 8722:     my $response_number = 0;
 8723:     my $bubble_line     = 0;
 8724:     foreach my $resource (@resources) {
 8725:         my $resid = $resource->id(); 
 8726:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8727:                                                           $udom,undef,$bubbles_per_row);
 8728:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8729: 	    foreach my $part_id (@{$parts}) {
 8730:                 my $lines;
 8731: 
 8732: 	        # TODO - make this a persistent hash not an array.
 8733: 
 8734:                 # optionresponse, matchresponse and rankresponse type items 
 8735:                 # render as separate sub-questions in exam mode.
 8736:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8737:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8738:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8739:                     my ($numbub,$numshown);
 8740:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8741:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8742:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8743:                         }
 8744:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8745:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8746:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8747:                         }
 8748:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8749:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8750:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8751:                         }
 8752:                     }
 8753:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8754:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8755:                     }
 8756:                     my $bubbles_per_row =
 8757:                         &bubblesheet_bubbles_per_row($scantron_config);
 8758:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8759:                     if (($numbub % $bubbles_per_row) != 0) {
 8760:                         $inner_bubble_lines++;
 8761:                     }
 8762:                     for (my $i=0; $i<$numshown; $i++) {
 8763:                         $subdivided_bubble_lines{$response_number} .= 
 8764:                             $inner_bubble_lines.',';
 8765:                     }
 8766:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8767:                     $lines = $numshown * $inner_bubble_lines;
 8768:                 } else {
 8769:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8770:                 }
 8771: 
 8772:                 $first_bubble_line{$response_number} = $bubble_line;
 8773: 	        $bubble_lines_per_response{$response_number} = $lines;
 8774:                 $responsetype_per_response{$response_number} = 
 8775:                     $analysis->{$part_id.'.type'};
 8776:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8777: 	        $response_number++;
 8778: 
 8779: 	        $bubble_line +=  $lines;
 8780: 	        $total_lines +=  $lines;
 8781: 	    }
 8782:         }
 8783:     }
 8784:     &Apache::lonnet::delenv('scantron.');
 8785: 
 8786:     &save_bubble_lines();
 8787:     $env{'form.scantron_maxbubble'} =
 8788: 	$total_lines;
 8789:     return $env{'form.scantron_maxbubble'};
 8790: }
 8791: 
 8792: sub bubblesheet_bubbles_per_row {
 8793:     my ($scantron_config) = @_;
 8794:     my $bubbles_per_row;
 8795:     if (ref($scantron_config) eq 'HASH') {
 8796:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8797:     }
 8798:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8799:         $bubbles_per_row = 10;
 8800:     }
 8801:     return $bubbles_per_row;
 8802: }
 8803: 
 8804: sub scantron_validate_missingbubbles {
 8805:     my ($r,$currentphase) = @_;
 8806:     #get student info
 8807:     my $classlist=&Apache::loncoursedata::get_classlist();
 8808:     my %idmap=&username_to_idmap($classlist);
 8809:     my (undef,undef,$sequence)=
 8810:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8811: 
 8812:     #get scantron line setup
 8813:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8814:     my ($scanlines,$scan_data)=&scantron_getfile();
 8815: 
 8816:     my $navmap = Apache::lonnavmaps::navmap->new();
 8817:     unless (ref($navmap)) {
 8818:         $r->print(&navmap_errormsg());
 8819:         return(1,$currentphase);
 8820:     }
 8821: 
 8822:     my $map=$navmap->getResourceByUrl($sequence);
 8823:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8824:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8825:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8826:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8827: 
 8828:     my $nav_error;
 8829:     if (ref($map)) {
 8830:         $randomorder = $map->randomorder();
 8831:         $randompick = $map->randompick();
 8832:         if ($randomorder || $randompick) {
 8833:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8834:             if ($nav_error) {
 8835:                 $r->print(&navmap_errormsg());
 8836:                 return(1,$currentphase);
 8837:             }
 8838:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8839:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8840:         }
 8841:     } else {
 8842:         $r->print(&navmap_errormsg());
 8843:         return(1,$currentphase);
 8844:     }
 8845: 
 8846: 
 8847:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8848:     if ($nav_error) {
 8849:         $r->print(&navmap_errormsg());
 8850:         return(1,$currentphase);
 8851:     }
 8852: 
 8853:     if (!$max_bubble) { $max_bubble=2**31; }
 8854:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8855: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8856: 	if ($line=~/^[\s\cz]*$/) { next; }
 8857: 	my $scan_record =
 8858:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8859: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8860:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8861:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8862: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8863: 	my @to_correct;
 8864: 	
 8865: 	# Probably here's where the error is...
 8866: 
 8867: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8868:             my $lastbubble;
 8869:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8870:                my $question = $1;
 8871:                my $subquestion = $2;
 8872:                my ($first,$responsenum);
 8873:                if ($randomorder || $randompick) {
 8874:                    $responsenum = $respnumlookup{$question-1};
 8875:                    $first = $startline{$question-1};
 8876:                } else {
 8877:                    $responsenum = $question-1; 
 8878:                    $first = $first_bubble_line{$responsenum};
 8879:                }
 8880:                if (!defined($first)) { next; }
 8881:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8882:                my $subcount = 1;
 8883:                while ($subcount<$subquestion) {
 8884:                    $first += $subans[$subcount-1];
 8885:                    $subcount ++;
 8886:                }
 8887:                my $count = $subans[$subquestion-1];
 8888:                $lastbubble = $first + $count;
 8889:             } else {
 8890:                my ($first,$responsenum);
 8891:                if ($randomorder || $randompick) {
 8892:                    $responsenum = $respnumlookup{$missing-1};
 8893:                    $first = $startline{$missing-1};
 8894:                } else {
 8895:                    $responsenum = $missing-1;
 8896:                    $first = $first_bubble_line{$responsenum};
 8897:                }
 8898:                if (!defined($first)) { next; }
 8899:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8900:             }
 8901:             if ($lastbubble > $max_bubble) { next; }
 8902: 	    push(@to_correct,$missing);
 8903: 	}
 8904: 	if (@to_correct) {
 8905: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8906: 				     $line,'missingbubble',\@to_correct,
 8907:                                      $randomorder,$randompick,\%respnumlookup,
 8908:                                      \%startline);
 8909: 	    return (1,$currentphase);
 8910: 	}
 8911: 
 8912:     }
 8913:     return (0,$currentphase+1);
 8914: }
 8915: 
 8916: sub hand_bubble_option {
 8917:     my (undef, undef, $sequence) =
 8918:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8919:     return if ($sequence eq '');
 8920:     my $navmap = Apache::lonnavmaps::navmap->new();
 8921:     unless (ref($navmap)) {
 8922:         return;
 8923:     }
 8924:     my $needs_hand_bubbles;
 8925:     my $map=$navmap->getResourceByUrl($sequence);
 8926:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8927:     foreach my $res (@resources) {
 8928:         if (ref($res)) {
 8929:             if ($res->is_problem()) {
 8930:                 my $partlist = $res->parts();
 8931:                 foreach my $part (@{ $partlist }) {
 8932:                     my @types = $res->responseType($part);
 8933:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8934:                         $needs_hand_bubbles = 1;
 8935:                         last;
 8936:                     }
 8937:                 }
 8938:             }
 8939:         }
 8940:     }
 8941:     if ($needs_hand_bubbles) {
 8942:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8943:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8944:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8945:                &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 />').
 8946:                '<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;'.
 8947:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8948:     }
 8949:     return;
 8950: }
 8951: 
 8952: sub scantron_process_students {
 8953:     my ($r,$symb) = @_;
 8954: 
 8955:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8956:     if (!$symb) {
 8957: 	return '';
 8958:     }
 8959:     my $default_form_data=&defaultFormData($symb);
 8960: 
 8961:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8962:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8963:     my ($scanlines,$scan_data)=&scantron_getfile();
 8964:     my $classlist=&Apache::loncoursedata::get_classlist();
 8965:     my %idmap=&username_to_idmap($classlist);
 8966:     my $navmap=Apache::lonnavmaps::navmap->new();
 8967:     unless (ref($navmap)) {
 8968:         $r->print(&navmap_errormsg());
 8969:         return '';
 8970:     }
 8971:     my $map=$navmap->getResourceByUrl($sequence);
 8972:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8973:         %grader_randomlists_by_symb);
 8974:     if (ref($map)) {
 8975:         $randomorder = $map->randomorder();
 8976:         $randompick = $map->randompick();
 8977:     } else {
 8978:         $r->print(&navmap_errormsg());
 8979:         return '';
 8980:     }
 8981:     my $nav_error;
 8982:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8983:     if ($randomorder || $randompick) {
 8984:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8985:         if ($nav_error) {
 8986:             $r->print(&navmap_errormsg());
 8987:             return '';
 8988:         }
 8989:     }
 8990:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8991:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8992: 
 8993:     my ($uname,$udom);
 8994:     my $result= <<SCANTRONFORM;
 8995: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8996:   <input type="hidden" name="command" value="scantron_configphase" />
 8997:   $default_form_data
 8998: SCANTRONFORM
 8999:     $r->print($result);
 9000: 
 9001:     my ($checksec,@possibles)=&gradable_sections();
 9002:     my @delayqueue;
 9003:     my (%completedstudents,%scandata);
 9004: 
 9005:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9006:     my $count=&get_todo_count($scanlines,$scan_data);
 9007:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9008:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9009:     $r->print('<br />');
 9010:     my $start=&Time::HiRes::time();
 9011:     my $i=-1;
 9012:     my $started;
 9013: 
 9014:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9015:     if ($nav_error) {
 9016:         $r->print(&navmap_errormsg());
 9017:         return '';
 9018:     }
 9019: 
 9020:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9021:     # the user and return.
 9022: 
 9023:     if ($ssi_error) {
 9024: 	$r->print("</form>");
 9025: 	&ssi_print_error($r);
 9026:         &Apache::lonnet::remove_lock($lock);
 9027: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9028:     }
 9029: 
 9030:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9031:     my $numletts = scalar(keys(%lettdig));
 9032:     my %orderedforcode;
 9033: 
 9034:     while ($i<$scanlines->{'count'}) {
 9035:  	($uname,$udom)=('','');
 9036:  	$i++;
 9037:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9038:  	if ($line=~/^[\s\cz]*$/) { next; }
 9039: 	if ($started) {
 9040: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9041: 	}
 9042: 	$started=1;
 9043:         my %respnumlookup = ();
 9044:         my %startline = ();
 9045:         my $total;
 9046:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9047:                                                  $scan_data,undef,\%idmap,$randomorder,
 9048:                                                  $randompick,$sequence,\@master_seq,
 9049:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9050:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9051:                                                  \$total);
 9052:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9053:  					      \%idmap,$i)) {
 9054:   	    &scantron_add_delay(\@delayqueue,$line,
 9055:  				'Unable to find a student that matches',1);
 9056:  	    next;
 9057:   	}
 9058:  	if (exists $completedstudents{$uname}) {
 9059:  	    &scantron_add_delay(\@delayqueue,$line,
 9060:  				'Student '.$uname.' has multiple sheets',2);
 9061:  	    next;
 9062:  	}
 9063:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9064:         if (($checksec ne '') && ($checksec ne $usec)) {
 9065:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9066:                 &scantron_add_delay(\@delayqueue,$line,
 9067:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9068:                 next;
 9069:             }
 9070:         }
 9071:         my $user = $uname.':'.$usec;
 9072:   	($uname,$udom)=split(/:/,$uname);
 9073: 
 9074:         my $scancode;
 9075:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9076:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9077:             $scancode = $scan_record->{'scantron.CODE'};
 9078:         } else {
 9079:             $scancode = '';
 9080:         }
 9081: 
 9082:         my @mapresources = @resources;
 9083:         if ($randomorder || $randompick) {
 9084:             @mapresources = 
 9085:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9086:                              \%orderedforcode);
 9087:         }
 9088:         my (%partids_by_symb,$res_error);
 9089:         foreach my $resource (@mapresources) {
 9090:             my $ressymb;
 9091:             if (ref($resource)) {
 9092:                 $ressymb = $resource->symb();
 9093:             } else {
 9094:                 $res_error = 1;
 9095:                 last;
 9096:             }
 9097:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9098:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9099:                 my $currcode;
 9100:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9101:                     $currcode = $scancode;
 9102:                 }
 9103:                 my ($analysis,$parts) =
 9104:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9105:                                               $uname,$udom,undef,$bubbles_per_row,
 9106:                                               $currcode);
 9107:                 $partids_by_symb{$ressymb} = $parts;
 9108:             } else {
 9109:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9110:             }
 9111:         }
 9112: 
 9113:         if ($res_error) {
 9114:             &scantron_add_delay(\@delayqueue,$line,
 9115:                                 'An error occurred while grading student '.$uname,2);
 9116:             next;
 9117:         }
 9118: 
 9119: 	&Apache::lonxml::clear_problem_counter();
 9120:   	&Apache::lonnet::appenv($scan_record);
 9121: 
 9122: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9123: 	    &scantron_putfile($scanlines,$scan_data);
 9124: 	}
 9125: 	
 9126:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9127:                                    \@mapresources,\%partids_by_symb,
 9128:                                    $bubbles_per_row,$randomorder,$randompick,
 9129:                                    \%respnumlookup,\%startline) 
 9130:             eq 'ssi_error') {
 9131:             $ssi_error = 0; # So end of handler error message does not trigger.
 9132:             $r->print("</form>");
 9133:             &ssi_print_error($r);
 9134:             &Apache::lonnet::remove_lock($lock);
 9135:             return '';      # Why return ''?  Beats me.
 9136:         }
 9137: 
 9138:         if (($scancode) && ($randomorder || $randompick)) {
 9139:             my $parmresult =
 9140:                 &Apache::lonparmset::storeparm_by_symb($symb,
 9141:                                                        '0_examcode',2,$scancode,
 9142:                                                        'string_examcode',$uname,
 9143:                                                        $udom);
 9144:         }
 9145: 	$completedstudents{$uname}={'line'=>$line};
 9146:         if ($env{'form.verifyrecord'}) {
 9147:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9148:             if ($randompick) {
 9149:                 if ($total) {
 9150:                     $lastpos = $total*$scantron_config{'Qlength'};
 9151:                 }
 9152:             }
 9153: 
 9154:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9155:             chomp($studentdata);
 9156:             $studentdata =~ s/\r$//;
 9157:             my $studentrecord = '';
 9158:             my $counter = -1;
 9159:             foreach my $resource (@mapresources) {
 9160:                 my $ressymb = $resource->symb();
 9161:                 ($counter,my $recording) =
 9162:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9163:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9164:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9165:                                              $randompick,\%respnumlookup,\%startline);
 9166:                 $studentrecord .= $recording;
 9167:             }
 9168:             if ($studentrecord ne $studentdata) {
 9169:                 &Apache::lonxml::clear_problem_counter();
 9170:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9171:                                            \@mapresources,\%partids_by_symb,
 9172:                                            $bubbles_per_row,$randomorder,$randompick,
 9173:                                            \%respnumlookup,\%startline) 
 9174:                     eq 'ssi_error') {
 9175:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9176:                     $r->print("</form>");
 9177:                     &ssi_print_error($r);
 9178:                     &Apache::lonnet::remove_lock($lock);
 9179:                     delete($completedstudents{$uname});
 9180:                     return '';
 9181:                 }
 9182:                 $counter = -1;
 9183:                 $studentrecord = '';
 9184:                 foreach my $resource (@mapresources) {
 9185:                     my $ressymb = $resource->symb();
 9186:                     ($counter,my $recording) =
 9187:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9188:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9189:                                                  \%scantron_config,\%lettdig,$numletts,
 9190:                                                  $randomorder,$randompick,\%respnumlookup,
 9191:                                                  \%startline);
 9192:                     $studentrecord .= $recording;
 9193:                 }
 9194:                 if ($studentrecord ne $studentdata) {
 9195:                     $r->print('<p><span class="LC_warning">');
 9196:                     if ($scancode eq '') {
 9197:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9198:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9199:                     } else {
 9200:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9201:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9202:                     }
 9203:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9204:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9205:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9206:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9207:                               &Apache::loncommon::start_data_table_row().
 9208:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9209:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9210:                               &Apache::loncommon::end_data_table_row().
 9211:                               &Apache::loncommon::start_data_table_row().
 9212:                               '<td>'.&mt('Stored submissions').'</td>'.
 9213:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9214:                               &Apache::loncommon::end_data_table_row().
 9215:                               &Apache::loncommon::end_data_table().'</p>');
 9216:                 } else {
 9217:                     $r->print('<br /><span class="LC_warning">'.
 9218:                              &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 />'.
 9219:                              &mt("As a consequence, this user's submission history records two tries.").
 9220:                                  '</span><br />');
 9221:                 }
 9222:             }
 9223:         }
 9224:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9225:     } continue {
 9226: 	&Apache::lonxml::clear_problem_counter();
 9227: 	&Apache::lonnet::delenv('scantron.');
 9228:     }
 9229:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9230:     &Apache::lonnet::remove_lock($lock);
 9231: #    my $lasttime = &Time::HiRes::time()-$start;
 9232: #    $r->print("<p>took $lasttime</p>");
 9233: 
 9234:     $r->print("</form>");
 9235:     return '';
 9236: }
 9237: 
 9238: sub graders_resources_pass {
 9239:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9240:         $bubbles_per_row) = @_;
 9241:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9242:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9243:         foreach my $resource (@{$resources}) {
 9244:             my $ressymb = $resource->symb();
 9245:             my ($analysis,$parts) =
 9246:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9247:                                           $env{'user.name'},$env{'user.domain'},
 9248:                                           1,$bubbles_per_row);
 9249:             $grader_partids_by_symb->{$ressymb} = $parts;
 9250:             if (ref($analysis) eq 'HASH') {
 9251:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9252:                     $grader_randomlists_by_symb->{$ressymb} =
 9253:                         $analysis->{'parts_withrandomlist'};
 9254:                 }
 9255:             }
 9256:         }
 9257:     }
 9258:     return;
 9259: }
 9260: 
 9261: =pod
 9262: 
 9263: =item users_order
 9264: 
 9265:   Returns array of resources in current map, ordered based on either CODE,
 9266:   if this is a CODEd exam, or based on student's identity if this is a 
 9267:   "NAMEd" exam.
 9268: 
 9269:   Should be used when randomorder and/or randompick applied when the 
 9270:   corresponding exam was printed, prior to students completing bubblesheets 
 9271:   for the version of the exam the student received.
 9272: 
 9273: =cut
 9274: 
 9275: sub users_order  {
 9276:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9277:     my @mapresources;
 9278:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9279:         return @mapresources;
 9280:     }
 9281:     if ($scancode) {
 9282:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9283:             @mapresources = @{$orderedforcode->{$scancode}};
 9284:         } else {
 9285:             $env{'form.CODE'} = $scancode;
 9286:             my $actual_seq =
 9287:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9288:                                                                $master_seq,
 9289:                                                                $user,$scancode,1);
 9290:             if (ref($actual_seq) eq 'ARRAY') {
 9291:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9292:                 if (ref($orderedforcode) eq 'HASH') {
 9293:                     if (@mapresources > 0) { 
 9294:                         $orderedforcode->{$scancode} = \@mapresources;
 9295:                     }
 9296:                 }
 9297:             }
 9298:             delete($env{'form.CODE'});
 9299:         }
 9300:     } else {
 9301:         my $actual_seq =
 9302:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9303:                                                            $master_seq,
 9304:                                                            $user,undef,1);
 9305:         if (ref($actual_seq) eq 'ARRAY') {
 9306:             @mapresources = 
 9307:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9308:         }
 9309:     }
 9310:     return @mapresources;
 9311: }
 9312: 
 9313: sub grade_student_bubbles {
 9314:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9315:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9316:     my $uselookup = 0;
 9317:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9318:         (ref($startline) eq 'HASH')) {
 9319:         $uselookup = 1;
 9320:     }
 9321: 
 9322:     if (ref($resources) eq 'ARRAY') {
 9323:         my $count = 0;
 9324:         foreach my $resource (@{$resources}) {
 9325:             my $ressymb = $resource->symb();
 9326:             my %form = ('submitted'      => 'scantron',
 9327:                         'grade_target'   => 'grade',
 9328:                         'grade_username' => $uname,
 9329:                         'grade_domain'   => $udom,
 9330:                         'grade_courseid' => $env{'request.course.id'},
 9331:                         'grade_symb'     => $ressymb,
 9332:                         'CODE'           => $scancode
 9333:                        );
 9334:             if ($bubbles_per_row ne '') {
 9335:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9336:             }
 9337:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9338:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9339:             }
 9340:             if (ref($parts) eq 'HASH') {
 9341:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9342:                     foreach my $part (@{$parts->{$ressymb}}) {
 9343:                         if ($uselookup) {
 9344:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9345:                         } else {
 9346:                             $form{'scantron_questnum_start.'.$part} =
 9347:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9348:                         }
 9349:                         $count++;
 9350:                     }
 9351:                 }
 9352:             }
 9353:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9354:             return 'ssi_error' if ($ssi_error);
 9355:             last if (&Apache::loncommon::connection_aborted($r));
 9356:         }
 9357:     }
 9358:     return;
 9359: }
 9360: 
 9361: sub scantron_upload_scantron_data {
 9362:     my ($r,$symb) = @_;
 9363:     my $dom = $env{'request.role.domain'};
 9364:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9365:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9366:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9367:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9368: 							  'domainid',
 9369: 							  'coursename',$dom);
 9370:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9371:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9372:     my $default_form_data=&defaultFormData($symb);
 9373:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9374:     &js_escape(\$nofile_alert);
 9375:     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.");
 9376:     &js_escape(\$nocourseid_alert);
 9377:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9378:     function checkUpload(formname) {
 9379: 	if (formname.upfile.value == "") {
 9380: 	    alert("'.$nofile_alert.'");
 9381: 	    return false;
 9382: 	}
 9383:         if (formname.courseid.value == "") {
 9384:             alert("'.$nocourseid_alert.'");
 9385:             return false;
 9386:         }
 9387: 	formname.submit();
 9388:     }
 9389: 
 9390:     function ToSyllabus() {
 9391:         var cdom = '."'$dom'".';
 9392:         var cnum = document.rules.courseid.value;
 9393:         if (cdom == "" || cdom == null) {
 9394:             return;
 9395:         }
 9396:         if (cnum == "" || cnum == null) {
 9397:            return;
 9398:         }
 9399:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9400:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9401:         return;
 9402:     }
 9403: 
 9404:     '.$formatjs.'
 9405: '));
 9406:     $r->print('
 9407: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9408: 
 9409: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9410: '.$default_form_data.
 9411:   &Apache::lonhtmlcommon::start_pick_box().
 9412:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9413:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9414:   &Apache::lonhtmlcommon::row_closure().
 9415:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9416:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9417:   &Apache::lonhtmlcommon::row_closure().
 9418:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9419:   '<input name="domainid" type="hidden" />'.$domdesc.
 9420:   &Apache::lonhtmlcommon::row_closure());
 9421:     if ($formatoptions) {
 9422:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9423:                   &Apache::lonhtmlcommon::row_closure());
 9424:     }
 9425:     $r->print(
 9426:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9427:   '<input type="file" name="upfile" size="50" />'.
 9428:   &Apache::lonhtmlcommon::row_closure(1).
 9429:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9430: 
 9431: <input name="command" value="scantronupload_save" type="hidden" />
 9432: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9433: </form>
 9434: ');
 9435:     return '';
 9436: }
 9437: 
 9438: sub scantron_upload_dataformat {
 9439:     my ($dom) = @_;
 9440:     my ($formatoptions,$formattitle,$formatjs);
 9441:     $formatjs = <<'END';
 9442: function toggleScantab(form) {
 9443:    return;
 9444: }
 9445: END
 9446:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9447:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9448:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9449:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9450:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9451:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9452:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9453:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9454:                             my ($onclick,$formatextra,$singleline);
 9455:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9456:                             my $count = 0;
 9457:                             foreach my $line (@lines) {
 9458:                                 next if ($line =~ /^#/);
 9459:                                 $singleline = $line;
 9460:                                 $count ++;
 9461:                             }
 9462:                             if ($count > 1) {
 9463:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9464:                                                '<span class="LC_nobreak">'.
 9465:                                                &mt('Bubblesheet type:').'&nbsp;'.
 9466:                                                &scantron_scantab().'</span></div>';
 9467:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9468:                                 $formatjs = <<"END";
 9469: function toggleScantab(form) {
 9470:     var divid = 'bubbletype';
 9471:     if (document.getElementById(divid)) {
 9472:         var radioname = 'fileformat';
 9473:         var num = form.elements[radioname].length;
 9474:         if (num) {
 9475:             for (var i=0; i<num; i++) {
 9476:                 if (form.elements[radioname][i].checked) {
 9477:                     var chosen = form.elements[radioname][i].value;
 9478:                     if (chosen == 'dat') {
 9479:                         document.getElementById(divid).style.display = 'none';
 9480:                     } else if (chosen == 'csv') {
 9481:                         document.getElementById(divid).style.display = 'block';
 9482:                     }
 9483:                 }
 9484:             }
 9485:         }
 9486:     }
 9487:     return;
 9488: }
 9489: 
 9490: END
 9491:                             } elsif ($count == 1) {
 9492:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9493:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9494:                             }
 9495:                             $formattitle = &mt('File format');
 9496:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9497:                                              &mt('Plain Text (no delimiters)').
 9498:                                              '</label>'.('&nbsp;'x2).
 9499:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9500:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9501:                         }
 9502:                     }
 9503:                 }
 9504:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9505:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9506:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9507:                         $formattitle = &mt('Bubblesheet type');
 9508:                         $formatoptions = &scantron_scantab();
 9509:                     }
 9510:                 }
 9511:             }
 9512:         }
 9513:     }
 9514:     return ($formatoptions,$formattitle,$formatjs);
 9515: }
 9516: 
 9517: sub scantron_upload_scantron_data_save {
 9518:     my ($r,$symb) = @_;
 9519:     my $doanotherupload=
 9520: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9521: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9522: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9523: 	'</form>'."\n";
 9524:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9525: 	!&Apache::lonnet::allowed('usc',
 9526: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9527:         !&Apache::lonnet::allowed('usc',
 9528:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9529: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9530: 	unless ($symb) {
 9531: 	    $r->print($doanotherupload);
 9532: 	}
 9533: 	return '';
 9534:     }
 9535:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9536:     my $uploadedfile;
 9537:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9538:     if (length($env{'form.upfile'}) < 2) {
 9539:         $r->print(
 9540:             &Apache::lonhtmlcommon::confirm_success(
 9541:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9542:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9543:     } else {
 9544:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9545:         my $parser;
 9546:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9547:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9548:                 my $is_csv;
 9549:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9550:                 if (@possibles > 1) {
 9551:                     if ($env{'form.fileformat'} eq 'csv') {
 9552:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9553:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9554:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9555:                                     $is_csv = 1;
 9556:                                 }
 9557:                             }
 9558:                         }
 9559:                     }
 9560:                 } elsif (@possibles == 1) {
 9561:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9562:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9563:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9564:                                 $is_csv = 1;
 9565:                             }
 9566:                         }
 9567:                     }
 9568:                 }
 9569:                 if ($is_csv) {
 9570:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9571:                 }
 9572:             }
 9573:         }
 9574:         my $result =
 9575:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9576:                                             $env{'form.courseid'},$env{'form.domainid'});
 9577:         if ($result =~ m{^/uploaded/}) {
 9578:             $r->print(
 9579:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9580:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9581:                         (length($env{'form.upfile'})-1),
 9582:                         '<span class="LC_filename">'.$result.'</span>'));
 9583:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9584:             if ($uploadedfile =~ /^scantron_orig_/) {
 9585:                 my $logname = $uploadedfile;
 9586:                 $logname =~ s/^scantron_orig_//;
 9587:                 if ($logname ne '') {
 9588:                     my $now = time;
 9589:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9590:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9591:                 }
 9592:             }
 9593:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9594:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9595:         } else {
 9596:             $r->print(
 9597:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9598:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9599:                           $result,
 9600: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9601: 	}
 9602:     }
 9603:     if ($symb) {
 9604: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9605:     } else {
 9606: 	$r->print($doanotherupload);
 9607:     }
 9608:     return '';
 9609: }
 9610: 
 9611: sub validate_uploaded_scantron_file {
 9612:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9613: 
 9614:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9615:     my @lines;
 9616:     if ($scanlines ne '-1') {
 9617:         @lines=split("\n",$scanlines,-1);
 9618:     }
 9619:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9620:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9621:     if ($context eq 'download') {
 9622:         $priv = 'mgr';
 9623:     } else {
 9624:         $priv = 'usc';
 9625:     }
 9626:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9627:             (($env{'request.course.id'}) &&
 9628:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9629:         if ($env{'request.course.sec'} ne '') {
 9630:             unless (&Apache::lonnet::allowed($priv,
 9631:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9632:                 unless ($context eq 'download') {
 9633:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9634:                 }
 9635:                 return $output;
 9636:             }
 9637:             ($checksec,@possibles)=&gradable_sections();
 9638:         }
 9639:     }
 9640:     if (@lines) {
 9641:         my (%counts,$max_match_format);
 9642:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9643:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9644:         my %idmap = &username_to_idmap($classlist);
 9645:         foreach my $key (keys(%idmap)) {
 9646:             my $lckey = lc($key);
 9647:             $idmap{$lckey} = $idmap{$key};
 9648:         }
 9649:         my %unique_formats;
 9650:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9651:         foreach my $line (@formatlines) {
 9652:             chomp($line);
 9653:             my @config = split(/:/,$line);
 9654:             my $idstart = $config[5];
 9655:             my $idlength = $config[6];
 9656:             if (($idstart ne '') && ($idlength > 0)) {
 9657:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9658:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9659:                 } else {
 9660:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9661:                 }
 9662:             }
 9663:         }
 9664:         foreach my $key (keys(%unique_formats)) {
 9665:             my ($idstart,$idlength) = split(':',$key);
 9666:             %{$counts{$key}} = (
 9667:                                'found'   => 0,
 9668:                                'total'   => 0,
 9669:                                'totalanysec' => 0,
 9670:                                'othersec' => 0,
 9671:                               );
 9672:             foreach my $line (@lines) {
 9673:                 next if ($line =~ /^#/);
 9674:                 next if ($line =~ /^[\s\cz]*$/);
 9675:                 my $id = substr($line,$idstart-1,$idlength);
 9676:                 $id = lc($id);
 9677:                 if (exists($idmap{$id})) {
 9678:                     if ($checksec ne '') {
 9679:                         $counts{$key}{'totalanysec'} ++;
 9680:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9681:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9682:                             if ($stusec ne $checksec) {
 9683:                                 if (@possibles) {
 9684:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9685:                                         $counts{$key}{'othersec'} ++;
 9686:                                         next;
 9687:                                     }
 9688:                                 } else {
 9689:                                     $counts{$key}{'othersec'} ++;
 9690:                                     next;
 9691:                                 }
 9692:                             }
 9693:                         }
 9694:                     }
 9695:                     $counts{$key}{'found'} ++;
 9696:                 }
 9697:                 $counts{$key}{'total'} ++;
 9698:             }
 9699:             if ($counts{$key}{'total'}) {
 9700:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9701:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9702:                     $max_match_pct = $percent_match;
 9703:                     $max_match_format = $key;
 9704:                     $found_match_count = $counts{$key}{'found'};
 9705:                     $max_match_count = $counts{$key}{'total'};
 9706:                 }
 9707:             }
 9708:         }
 9709:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9710:             my $format_descs;
 9711:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9712:             for (my $i=0; $i<$numwithformat; $i++) {
 9713:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9714:                 if ($i<$numwithformat-2) {
 9715:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9716:                 } elsif ($i==$numwithformat-2) {
 9717:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9718:                 } elsif ($i==$numwithformat-1) {
 9719:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9720:                 }
 9721:             }
 9722:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9723:             $output .= '<br />';
 9724:             if ($found_match_count == $max_match_count) {
 9725:                 # 100% matching entries
 9726:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9727:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9728:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9729:                 &mt('Comparison of student IDs in the uploaded file with'.
 9730:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9731:                     ' in the file (for the format defined for [_3]).',
 9732:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9733:             } else {
 9734:                 # Not all entries matching? -> Show warning and additional info
 9735:                 $output .=
 9736:                     &Apache::lonhtmlcommon::confirm_success(
 9737:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9738:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9739:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9740:                     &mt('Comparison of student IDs in the uploaded file with'.
 9741:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9742:                         ' in the file (for the format defined for [_3]).',
 9743:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9744:                     '<p class="LC_info">'.
 9745:                     &mt('A low percentage of matches results from one of the following:').
 9746:                     '</p><ul>'.
 9747:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9748:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9749:                                '<i>'.$cdom.'</i>').'</li>'.
 9750:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9751:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9752:                     '</ul>';
 9753:             }
 9754:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9755:                 if ($counts{$max_match_format}{'othersec'}) {
 9756:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9757:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9758:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9759:                     &js_escape(\$confirmdel);
 9760:                     $output .= '<p class="LC_warning">'.
 9761:                                &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',
 9762:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9763:                                '<br />'.
 9764:                                &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>').
 9765:                                '</p><p>'.
 9766:                                &mt('If you prefer to delete the file now, use: [_1]').
 9767:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9768:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9769:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9770:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9771:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9772:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9773:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9774:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9775:                                '</form></p>';
 9776:                 }
 9777:             }
 9778:         }
 9779:         if (($context eq 'download') && ($checksec ne '')) {
 9780:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9781:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9782:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9783:             }
 9784:         } 
 9785:     } elsif ($context ne 'download') {
 9786:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9787:     }
 9788:     return $output;
 9789: }
 9790: 
 9791: sub gradable_sections {
 9792:     my $checksec = $env{'request.course.sec'};
 9793:     my @oksecs;
 9794:     if ($checksec) {
 9795:         my %availablesecs = &sections_grade_privs();
 9796:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9797:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9798:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9799:                     push(@oksecs,$sec);
 9800:                 }
 9801:             }
 9802:             if (grep(/^all$/,@oksecs)) {
 9803:                 undef($checksec);
 9804:             }
 9805:         }
 9806:     }
 9807:     return($checksec,@oksecs);
 9808: }
 9809: 
 9810: sub sections_grade_privs {
 9811:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9812:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9813:     my %availablesecs = (
 9814:                           mgr => [],
 9815:                           vgr => [],
 9816:                           usc => [],
 9817:                         );
 9818:     my $ccrole = 'cc';
 9819:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9820:         $ccrole = 'co';
 9821:     }
 9822:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9823:                                                      'userroles',['active'],
 9824:                                                      [$ccrole,'in','cr'],$cdom,1);
 9825:     my $crsid = $cnum.':'.$cdom;
 9826:     foreach my $item (keys(%crsroleshash)) {
 9827:         next unless ($item =~ /^$crsid\:/);
 9828:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9829:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9830:         if ($sec ne '') {
 9831:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9832:         }
 9833:         if (($role eq $ccrole) || ($role eq 'in')) {
 9834:             foreach my $priv ('mgr','vgr','usc') { 
 9835:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9836:                     if ($sec eq '') {
 9837:                         $availablesecs{$priv} = ['all'];
 9838:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9839:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9840:                             push(@{$availablesecs{$priv}},$sec);
 9841:                         }
 9842:                     }
 9843:                 }
 9844:             }
 9845:         } elsif ($role =~ m{^cr/}) {
 9846:             foreach my $priv ('mgr','vgr','usc') {
 9847:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9848:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9849:                         if ($sec eq '') {
 9850:                             $availablesecs{$priv} = ['all'];
 9851:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9852:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9853:                                 push(@{$availablesecs{$priv}},$sec);
 9854:                             }
 9855:                         }
 9856:                     }
 9857:                 }
 9858:             }
 9859:         }
 9860:     }
 9861:     return %availablesecs;
 9862: }
 9863: 
 9864: sub scantron_upload_delete {
 9865:     my ($r,$symb) = @_;
 9866:     my $filename = $env{'form.uploadedfile'};
 9867:     if ($filename =~ /^scantron_orig_/) {
 9868:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9869:             &Apache::lonnet::allowed('usc',
 9870:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9871:             &Apache::lonnet::allowed('usc',
 9872:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9873:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9874:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9875:             if ($retrieval eq '-1') {
 9876:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9877:                           &mt('File requested for deletion not found.'));
 9878:             } else {
 9879:                 $filename =~ s/^scantron_orig_//;
 9880:                 if ($filename ne '') {
 9881:                     my ($is_valid,$numleft);
 9882:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9883:                     if (keys(%info)) {
 9884:                         if (ref($info{$filename}) eq 'HASH') {
 9885:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9886:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9887:                                     $is_valid = 1;
 9888:                                     delete($info{$filename}{$timestamp}); 
 9889:                                 }
 9890:                             }
 9891:                             $numleft = scalar(keys(%{$info{$filename}}));
 9892:                         }
 9893:                     }
 9894:                     if ($is_valid) {
 9895:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
 9896:                         if ($result eq 'ok') {
 9897:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
 9898:                             if ($numleft) {
 9899:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9900:                             } else {
 9901:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9902:                             }
 9903:                         } else {
 9904:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9905:                                       &mt('Result was [_1]',$result));
 9906:                         }
 9907:                     } else {
 9908:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9909:                                   &mt('File requested for deletion was uploaded by a different user.'));
 9910:                     }
 9911:                 } else {
 9912:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9913:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9914:                 }
 9915:             }
 9916:         } else {
 9917:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
 9918:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
 9919:         }
 9920:     } else {
 9921:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9922:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9923:     }
 9924:     return;
 9925: }
 9926: 
 9927: sub valid_file {
 9928:     my ($requested_file)=@_;
 9929:     foreach my $filename (sort(&scantron_filenames())) {
 9930: 	if ($requested_file eq $filename) { return 1; }
 9931:     }
 9932:     return 0;
 9933: }
 9934: 
 9935: sub scantron_download_scantron_data {
 9936:     my ($r,$symb) = @_;
 9937:     my $default_form_data=&defaultFormData($symb);
 9938:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9939:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9940:     my $file=$env{'form.scantron_selectfile'};
 9941:     if (! &valid_file($file)) {
 9942: 	$r->print('
 9943: 	<p>
 9944: 	    '.&mt('The requested filename was invalid.').'
 9945:         </p>
 9946: ');
 9947: 	return;
 9948:     }
 9949:     my (%uploader,$is_owner,%counts,$percent);
 9950:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
 9951:     if (ref($uploader{$file}) eq 'HASH') {
 9952:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
 9953:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9954:                 $is_owner = 1;
 9955:                 last;
 9956:             }
 9957:         }
 9958:     }
 9959:     unless ($is_owner) {
 9960:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
 9961:         if ($counts{'totalanysec'}) {
 9962:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
 9963:             if ($percent_othersec >= 10) {
 9964:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
 9965:                 $r->print('<p class="LC_warning">'.
 9966:                           &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).
 9967:                           '</p>');
 9968:                 return;
 9969:             }
 9970:         }
 9971:     }
 9972:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9973:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9974:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9975:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9976:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9977:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9978:     $r->print('
 9979:     <p>
 9980: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9981: 	      '<a href="'.$orig.'">','</a>').'
 9982:     </p>
 9983:     <p>
 9984: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9985: 	      '<a href="'.$corrected.'">','</a>').'
 9986:     </p>
 9987:     <p>
 9988: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9989: 	      '<a href="'.$skipped.'">','</a>').'
 9990:     </p>
 9991: ');
 9992:     return '';
 9993: }
 9994: 
 9995: sub checkscantron_results {
 9996:     my ($r,$symb) = @_;
 9997:     if (!$symb) {return '';}
 9998:     my $cid = $env{'request.course.id'};
 9999:     my %lettdig = &Apache::lonnet::letter_to_digits();
10000:     my $numletts = scalar(keys(%lettdig));
10001:     my $cnum = $env{'course.'.$cid.'.num'};
10002:     my $cdom = $env{'course.'.$cid.'.domain'};
10003:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10004:     my %record;
10005:     my %scantron_config =
10006:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10007:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10008:     my ($scanlines,$scan_data)=&scantron_getfile();
10009:     my $classlist=&Apache::loncoursedata::get_classlist();
10010:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10011:     my $navmap=Apache::lonnavmaps::navmap->new();
10012:     unless (ref($navmap)) {
10013:         $r->print(&navmap_errormsg());
10014:         return '';
10015:     }
10016:     my $map=$navmap->getResourceByUrl($sequence);
10017:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10018:         %grader_randomlists_by_symb,%orderedforcode);
10019:     if (ref($map)) { 
10020:         $randomorder=$map->randomorder();
10021:         $randompick=$map->randompick();
10022:     }
10023:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10024:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10025:     if ($nav_error) {
10026:         $r->print(&navmap_errormsg());
10027:         return '';
10028:     }
10029:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10030:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10031:     my ($uname,$udom);
10032:     my (%scandata,%lastname,%bylast);
10033:     $r->print('
10034: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10035: 
10036:     my @delayqueue;
10037:     my %completedstudents;
10038: 
10039:     my $count=&get_todo_count($scanlines,$scan_data);
10040:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10041:     my ($username,$domain,$started);
10042:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10043:     if ($nav_error) {
10044:         $r->print(&navmap_errormsg());
10045:         return '';
10046:     }
10047: 
10048:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10049:     my $start=&Time::HiRes::time();
10050:     my $i=-1;
10051: 
10052:     while ($i<$scanlines->{'count'}) {
10053:         ($username,$domain,$uname)=('','','');
10054:         $i++;
10055:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10056:         if ($line=~/^[\s\cz]*$/) { next; }
10057:         if ($started) {
10058:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10059:         }
10060:         $started=1;
10061:         my $scan_record=
10062:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10063:                                                      $scan_data);
10064:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10065:                                               \%idmap,$i)) {
10066:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10067:                                 'Unable to find a student that matches',1);
10068:             next;
10069:         }
10070:         if (exists $completedstudents{$uname}) {
10071:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10072:                                 'Student '.$uname.' has multiple sheets',2);
10073:             next;
10074:         }
10075:         my $pid = $scan_record->{'scantron.ID'};
10076:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10077:         push(@{$bylast{$lastname{$pid}}},$pid);
10078:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10079:         my $user = $uname.':'.$usec;
10080:         ($username,$domain)=split(/:/,$uname);
10081: 
10082:         my $scancode;
10083:         if ((exists($scan_record->{'scantron.CODE'})) &&
10084:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10085:             $scancode = $scan_record->{'scantron.CODE'};
10086:         } else {
10087:             $scancode = '';
10088:         }
10089: 
10090:         my @mapresources = @resources;
10091:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10092:         my %respnumlookup=();
10093:         my %startline=();
10094:         if ($randomorder || $randompick) {
10095:             @mapresources =
10096:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10097:                              \%orderedforcode);
10098:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10099:                                              $scan_record,\@master_seq,\%symb_to_resource,
10100:                                              \%grader_partids_by_symb,\%orderedforcode,
10101:                                              \%respnumlookup,\%startline);
10102:             if ($randompick && $total) {
10103:                 $lastpos = $total*$scantron_config{'Qlength'};
10104:             }
10105:         }
10106:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10107:         chomp($scandata{$pid});
10108:         $scandata{$pid} =~ s/\r$//;
10109: 
10110:         my $counter = -1;
10111:         foreach my $resource (@mapresources) {
10112:             my $parts;
10113:             my $ressymb = $resource->symb();
10114:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10115:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10116:                 my $currcode;
10117:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10118:                     $currcode = $scancode;
10119:                 }
10120:                 (my $analysis,$parts) =
10121:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10122:                                               $username,$domain,undef,
10123:                                               $bubbles_per_row,$currcode);
10124:             } else {
10125:                 $parts = $grader_partids_by_symb{$ressymb};
10126:             }
10127:             ($counter,my $recording) =
10128:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10129:                                          $scandata{$pid},$parts,
10130:                                          \%scantron_config,\%lettdig,$numletts,
10131:                                          $randomorder,$randompick,
10132:                                          \%respnumlookup,\%startline);
10133:             $record{$pid} .= $recording;
10134:         }
10135:     }
10136:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10137:     $r->print('<br />');
10138:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10139:     $passed = 0;
10140:     $failed = 0;
10141:     $numstudents = 0;
10142:     foreach my $last (sort(keys(%bylast))) {
10143:         if (ref($bylast{$last}) eq 'ARRAY') {
10144:             foreach my $pid (sort(@{$bylast{$last}})) {
10145:                 my $showscandata = $scandata{$pid};
10146:                 my $showrecord = $record{$pid};
10147:                 $showscandata =~ s/\s/&nbsp;/g;
10148:                 $showrecord =~ s/\s/&nbsp;/g;
10149:                 if ($scandata{$pid} eq $record{$pid}) {
10150:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10151:                     $okstudents .= '<tr class="'.$css_class.'">'.
10152: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10153: '</tr>'."\n".
10154: '<tr class="'.$css_class.'">'."\n".
10155: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10156:                     $passed ++;
10157:                 } else {
10158:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10159:                     $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".
10160: '</tr>'."\n".
10161: '<tr class="'.$css_class.'">'."\n".
10162: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10163: '</tr>'."\n";
10164:                     $failed ++;
10165:                 }
10166:                 $numstudents ++;
10167:             }
10168:         }
10169:     }
10170:     $r->print(
10171:         '<p>'
10172:        .&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).',
10173:             '<b>',
10174:             $numstudents,
10175:             '</b>',
10176:             $env{'form.scantron_maxbubble'})
10177:        .'</p>'
10178:     );
10179:     $r->print('<p>'
10180:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10181:              .'<br />'
10182:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10183:              .'</p>'
10184:     );
10185:     if ($passed) {
10186:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10187:         $r->print(&Apache::loncommon::start_data_table()."\n".
10188:                  &Apache::loncommon::start_data_table_header_row()."\n".
10189:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10190:                  &Apache::loncommon::end_data_table_header_row()."\n".
10191:                  $okstudents."\n".
10192:                  &Apache::loncommon::end_data_table().'<br />');
10193:     }
10194:     if ($failed) {
10195:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10196:         $r->print(&Apache::loncommon::start_data_table()."\n".
10197:                  &Apache::loncommon::start_data_table_header_row()."\n".
10198:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10199:                  &Apache::loncommon::end_data_table_header_row()."\n".
10200:                  $badstudents."\n".
10201:                  &Apache::loncommon::end_data_table()).'<br />'.
10202:                  &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.');  
10203:     }
10204:     $r->print('</form><br />');
10205:     return;
10206: }
10207: 
10208: sub verify_scantron_grading {
10209:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10210:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10211:         $respnumlookup,$startline) = @_;
10212:     my ($record,%expected,%startpos);
10213:     return ($counter,$record) if (!ref($resource));
10214:     return ($counter,$record) if (!$resource->is_problem());
10215:     my $symb = $resource->symb();
10216:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10217:     foreach my $part_id (@{$partids}) {
10218:         $counter ++;
10219:         $expected{$part_id} = 0;
10220:         my $respnum = $counter;
10221:         if ($randomorder || $randompick) {
10222:             $respnum = $respnumlookup->{$counter};
10223:             $startpos{$part_id} = $startline->{$counter} + 1;
10224:         } else {
10225:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10226:         }
10227:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10228:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10229:             foreach my $item (@sub_lines) {
10230:                 $expected{$part_id} += $item;
10231:             }
10232:         } else {
10233:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10234:         }
10235:     }
10236:     if ($symb) {
10237:         my %recorded;
10238:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10239:         if ($returnhash{'version'}) {
10240:             my %lasthash=();
10241:             my $version;
10242:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10243:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10244:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10245:                 }
10246:             }
10247:             foreach my $key (keys(%lasthash)) {
10248:                 if ($key =~ /\.scantron$/) {
10249:                     my $value = &unescape($lasthash{$key});
10250:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10251:                     if ($value eq '') {
10252:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10253:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10254:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10255:                             }
10256:                         }
10257:                     } else {
10258:                         my @tocheck;
10259:                         my @items = split(//,$value);
10260:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10261:                             ($scantron_config->{'Qon'} eq 'number')) {
10262:                             if (@items < $expected{$part_id}) {
10263:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10264:                                 my @singles = split(//,$fragment);
10265:                                 foreach my $pos (@singles) {
10266:                                     if ($pos eq ' ') {
10267:                                         push(@tocheck,$pos);
10268:                                     } else {
10269:                                         my $next = shift(@items);
10270:                                         push(@tocheck,$next);
10271:                                     }
10272:                                 }
10273:                             } else {
10274:                                 @tocheck = @items;
10275:                             }
10276:                             foreach my $letter (@tocheck) {
10277:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10278:                                     if ($letter !~ /^[A-J]$/) {
10279:                                         $letter = $scantron_config->{'Qoff'};
10280:                                     }
10281:                                     $recorded{$part_id} .= $letter;
10282:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10283:                                     my $digit;
10284:                                     if ($letter !~ /^[A-J]$/) {
10285:                                         $digit = $scantron_config->{'Qoff'};
10286:                                     } else {
10287:                                         $digit = $lettdig->{$letter};
10288:                                     }
10289:                                     $recorded{$part_id} .= $digit;
10290:                                 }
10291:                             }
10292:                         } else {
10293:                             @tocheck = @items;
10294:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10295:                                 my $curr_sub = shift(@tocheck);
10296:                                 my $digit;
10297:                                 if ($curr_sub =~ /^[A-J]$/) {
10298:                                     $digit = $lettdig->{$curr_sub}-1;
10299:                                 }
10300:                                 if ($curr_sub eq 'J') {
10301:                                     $digit += scalar($numletts);
10302:                                 }
10303:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10304:                                     if ($j == $digit) {
10305:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10306:                                     } else {
10307:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10308:                                     }
10309:                                 }
10310:                             }
10311:                         }
10312:                     }
10313:                 }
10314:             }
10315:         }
10316:         foreach my $part_id (@{$partids}) {
10317:             if ($recorded{$part_id} eq '') {
10318:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10319:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10320:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10321:                     }
10322:                 }
10323:             }
10324:             $record .= $recorded{$part_id};
10325:         }
10326:     }
10327:     return ($counter,$record);
10328: }
10329: 
10330: #-------- end of section for handling grading scantron forms -------
10331: #
10332: #-------------------------------------------------------------------
10333: 
10334: #-------------------------- Menu interface -------------------------
10335: #
10336: #--- Href with symb and command ---
10337: 
10338: sub href_symb_cmd {
10339:     my ($symb,$cmd)=@_;
10340:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10341: }
10342: 
10343: sub grading_menu {
10344:     my ($request,$symb) = @_;
10345:     if (!$symb) {return '';}
10346: 
10347:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10348:                   'command'=>'individual');
10349:     
10350:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10351: 
10352:     $fields{'command'}='ungraded';
10353:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10354: 
10355:     $fields{'command'}='table';
10356:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10357: 
10358:     $fields{'command'}='all_for_one';
10359:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10360: 
10361:     $fields{'command'}='downloadfilesselect';
10362:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10363: 
10364:     $fields{'command'} = 'csvform';
10365:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10366:     
10367:     $fields{'command'} = 'processclicker';
10368:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10369:     
10370:     $fields{'command'} = 'scantron_selectphase';
10371:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10372: 
10373:     $fields{'command'} = 'initialverifyreceipt';
10374:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10375:     
10376:     my @menu = ({	categorytitle=>'Hand Grading',
10377:             items =>[
10378:                         {	linktext => 'Select individual students to grade',
10379:                     		url => $url1a,
10380:                     		permission => 'F',
10381:                     		icon => 'grade_students.png',
10382:                     		linktitle => 'Grade current resource for a selection of students.'
10383:                         }, 
10384:                         {       linktext => 'Grade ungraded submissions',
10385:                                 url => $url1b,
10386:                                 permission => 'F',
10387:                                 icon => 'ungrade_sub.png',
10388:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10389:                         },
10390: 
10391:                         {       linktext => 'Grading table',
10392:                                 url => $url1c,
10393:                                 permission => 'F',
10394:                                 icon => 'grading_table.png',
10395:                                 linktitle => 'Grade current resource for all students.'
10396:                         },
10397:                         {       linktext => 'Grade page/folder for one student',
10398:                                 url => $url1d,
10399:                                 permission => 'F',
10400:                                 icon => 'grade_PageFolder.png',
10401:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10402:                         },
10403:                         {       linktext => 'Download submissions',
10404:                                 url => $url1e,
10405:                                 permission => 'F',
10406:                                 icon => 'download_sub.png',
10407:                                 linktitle => 'Download all students submissions.'
10408:                         }]},
10409:                          { categorytitle=>'Automated Grading',
10410:                items =>[
10411: 
10412:                 	    {	linktext => 'Upload Scores',
10413:                     		url => $url2,
10414:                     		permission => 'F',
10415:                     		icon => 'uploadscores.png',
10416:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10417:                 	    },
10418:                 	    {	linktext => 'Process Clicker',
10419:                     		url => $url3,
10420:                     		permission => 'F',
10421:                     		icon => 'addClickerInfoFile.png',
10422:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10423:                 	    },
10424:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10425:                     		url => $url4,
10426:                     		permission => 'F',
10427:                     		icon => 'bubblesheet.png',
10428:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10429:                 	    },
10430:                             {   linktext => 'Verify Receipt Number',
10431:                                 url => $url5,
10432:                                 permission => 'F',
10433:                                 icon => 'receipt_number.png',
10434:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10435:                             }
10436: 
10437:                     ]
10438:             });
10439: 
10440:     # Create the menu
10441:     my $Str;
10442:     $Str .= '<form method="post" action="" name="gradingMenu">';
10443:     $Str .= '<input type="hidden" name="command" value="" />'.
10444:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10445: 
10446:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10447:     return $Str;    
10448: }
10449: 
10450: sub ungraded {
10451:     my ($request)=@_;
10452:     &submit_options($request);
10453: }
10454: 
10455: sub submit_options_sequence {
10456:     my ($request,$symb) = @_;
10457:     if (!$symb) {return '';}
10458:     &commonJSfunctions($request);
10459:     my $result;
10460: 
10461:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10462:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10463:     $result.=&selectfield(0).
10464:             '<input type="hidden" name="command" value="pickStudentPage" />
10465:             <div>
10466:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10467:             </div>
10468:         </div>
10469:   </form>';
10470:     return $result;
10471: }
10472: 
10473: sub submit_options_table {
10474:     my ($request,$symb) = @_;
10475:     if (!$symb) {return '';}
10476:     &commonJSfunctions($request);
10477:     my $is_tool = ($symb =~ /ext\.tool$/);
10478:     my $result;
10479: 
10480:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10481:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10482: 
10483:     $result.=&selectfield(1,$is_tool).
10484:             '<input type="hidden" name="command" value="viewgrades" />
10485:             <div>
10486:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10487:             </div>
10488:         </div>
10489:   </form>';
10490:     return $result;
10491: }
10492: 
10493: sub submit_options_download {
10494:     my ($request,$symb) = @_;
10495:     if (!$symb) {return '';}
10496: 
10497:     my $res_error;
10498:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10499:         &response_type($symb,\$res_error);
10500:     if ($res_error) {
10501:         $request->print(&mt('An error occurred retrieving response types'));
10502:         return;
10503:     }
10504:     unless ($numessay) {
10505:         $request->print(&mt('No essayresponse items found'));
10506:         return;
10507:     }
10508:     my $table;
10509:     if (ref($partlist) eq 'ARRAY') {
10510:         if (scalar(@$partlist) > 1 ) {
10511:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10512:         }
10513:     }
10514: 
10515:     my $is_tool = ($symb =~ /ext\.tool$/);
10516:     &commonJSfunctions($request);
10517: 
10518:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10519:                $table."\n".
10520:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10521:     $result.='
10522: <h2>
10523:   '.&mt('Select Students for whom to Download Submissions').'
10524: </h2>'.&selectfield(1,$is_tool).'
10525:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10526:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10527:             </div>
10528:           </div>
10529: 
10530: 
10531:   </form>';
10532:     return $result;
10533: }
10534: 
10535: #--- Displays the submissions first page -------
10536: sub submit_options {
10537:     my ($request,$symb) = @_;
10538:     if (!$symb) {return '';}
10539: 
10540:     my $is_tool = ($symb =~ /ext\.tool$/);
10541:     &commonJSfunctions($request);
10542:     my $result;
10543: 
10544:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10545: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10546:     $result.=&selectfield(1,$is_tool).'
10547:                 <input type="hidden" name="command" value="submission" /> 
10548: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10549:             </div>
10550:           </div>
10551:   </form>';
10552:     return $result;
10553: }
10554: 
10555: sub selectfield {
10556:    my ($full,$is_tool)=@_;
10557:    my %options;
10558:    if ($is_tool) {
10559:        %options =
10560:            (&transtatus_options,
10561:             'select_form_order' => ['yes','incorrect','all']);
10562:    } else {
10563:        %options = 
10564:            (&substatus_options,
10565:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10566:    }
10567:    my $result='<div class="LC_columnSection">
10568:   
10569:     <fieldset>
10570:       <legend>
10571:        '.&mt('Sections').'
10572:       </legend>
10573:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10574:     </fieldset>
10575:   
10576:     <fieldset>
10577:       <legend>
10578:         '.&mt('Groups').'
10579:       </legend>
10580:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10581:     </fieldset>
10582:   
10583:     <fieldset>
10584:       <legend>
10585:         '.&mt('Access Status').'
10586:       </legend>
10587:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10588:     </fieldset>';
10589:     if ($full) {
10590:         my $heading = &mt('Submission Status');
10591:         if ($is_tool) {
10592:             $heading = &mt('Transaction Status');
10593:         }
10594:         $result.='
10595:     <fieldset>
10596:       <legend>
10597:         '.$heading.'
10598:       </legend>'.
10599:        &Apache::loncommon::select_form('all','submitonly',\%options).
10600:    '</fieldset>';
10601:     }
10602:     $result.='</div><br />';
10603:     return $result;
10604: }
10605: 
10606: sub substatus_options {
10607:     return &Apache::lonlocal::texthash(
10608:                                       'yes'       => 'with submissions',
10609:                                       'queued'    => 'in grading queue',
10610:                                       'graded'    => 'with ungraded submissions',
10611:                                       'incorrect' => 'with incorrect submissions',
10612:                                       'all'       => 'with any status',
10613:                                       );
10614: }
10615: 
10616: sub transtatus_options {
10617:     return &Apache::lonlocal::texthash(
10618:                                        'yes'       => 'with score transactions',
10619:                                        'incorrect' => 'with less than full credit',
10620:                                        'all'       => 'with any status',
10621:                                       );
10622: }
10623: 
10624: sub reset_perm {
10625:     undef(%perm);
10626: }
10627: 
10628: sub init_perm {
10629:     &reset_perm();
10630:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10631: 
10632: 	my $scope = $env{'request.course.id'};
10633: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10634: 
10635: 	    $scope .= '/'.$env{'request.course.sec'};
10636: 	    if ( $perm{$test_perm}=
10637: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10638: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10639: 	    } else {
10640: 		delete($perm{$test_perm});
10641: 	    }
10642: 	}
10643:     }
10644: }
10645: 
10646: sub init_old_essays {
10647:     my ($symb,$apath,$adom,$aname) = @_;
10648:     if ($symb ne '') {
10649:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10650:         if (keys(%essays) > 0) {
10651:             $old_essays{$symb} = \%essays;
10652:         }
10653:     }
10654:     return;
10655: }
10656: 
10657: sub reset_old_essays {
10658:     undef(%old_essays);
10659: }
10660: 
10661: sub gather_clicker_ids {
10662:     my %clicker_ids;
10663: 
10664:     my $classlist = &Apache::loncoursedata::get_classlist();
10665: 
10666:     # Set up a couple variables.
10667:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10668:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10669:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10670: 
10671:     foreach my $student (keys(%$classlist)) {
10672:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10673:         my $username = $classlist->{$student}->[$username_idx];
10674:         my $domain   = $classlist->{$student}->[$domain_idx];
10675:         my $clickers =
10676: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10677:         foreach my $id (split(/\,/,$clickers)) {
10678:             $id=~s/^[\#0]+//;
10679:             $id=~s/[\-\:]//g;
10680:             if (exists($clicker_ids{$id})) {
10681: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10682:             } else {
10683: 		$clicker_ids{$id}=$username.':'.$domain;
10684:             }
10685:         }
10686:     }
10687:     return %clicker_ids;
10688: }
10689: 
10690: sub gather_adv_clicker_ids {
10691:     my %clicker_ids;
10692:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10693:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10694:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10695:     foreach my $element (sort(keys(%coursepersonnel))) {
10696:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10697:             my ($puname,$pudom)=split(/\:/,$person);
10698:             my $clickers =
10699: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10700:             foreach my $id (split(/\,/,$clickers)) {
10701: 		$id=~s/^[\#0]+//;
10702:                 $id=~s/[\-\:]//g;
10703: 		if (exists($clicker_ids{$id})) {
10704: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10705: 		} else {
10706: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10707: 		}
10708:             }
10709:         }
10710:     }
10711:     return %clicker_ids;
10712: }
10713: 
10714: sub clicker_grading_parameters {
10715:     return ('gradingmechanism' => 'scalar',
10716:             'upfiletype' => 'scalar',
10717:             'specificid' => 'scalar',
10718:             'pcorrect' => 'scalar',
10719:             'pincorrect' => 'scalar');
10720: }
10721: 
10722: sub process_clicker {
10723:     my ($r,$symb)=@_;
10724:     if (!$symb) {return '';}
10725:     my $result=&checkforfile_js();
10726:     $result.=&Apache::loncommon::start_data_table().
10727:              &Apache::loncommon::start_data_table_header_row().
10728:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10729:              &Apache::loncommon::end_data_table_header_row().
10730:              &Apache::loncommon::start_data_table_row()."<td>\n";
10731: # Attempt to restore parameters from last session, set defaults if not present
10732:     my %Saveable_Parameters=&clicker_grading_parameters();
10733:     &Apache::loncommon::restore_course_settings('grades_clicker',
10734:                                                  \%Saveable_Parameters);
10735:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10736:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10737:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10738:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10739: 
10740:     my %checked;
10741:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10742:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10743:           $checked{$gradingmechanism}=' checked="checked"';
10744:        }
10745:     }
10746: 
10747:     my $upload=&mt("Evaluate File");
10748:     my $type=&mt("Type");
10749:     my $attendance=&mt("Award points just for participation");
10750:     my $personnel=&mt("Correctness determined from response by course personnel");
10751:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10752:     my $given=&mt("Correctness determined from given list of answers").' '.
10753:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10754:     my $pcorrect=&mt("Percentage points for correct solution");
10755:     my $pincorrect=&mt("Percentage points for incorrect solution");
10756:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10757: 						   {'iclicker' => 'i>clicker',
10758:                                                     'interwrite' => 'interwrite PRS',
10759:                                                     'turning' => 'Turning Technologies'});
10760:     $symb = &Apache::lonenc::check_encrypt($symb);
10761:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10762: function sanitycheck() {
10763: // Accept only integer percentages
10764:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10765:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10766: // Find out grading choice
10767:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10768:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10769:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10770:       }
10771:    }
10772: // By default, new choice equals user selection
10773:    newgradingchoice=gradingchoice;
10774: // Not good to give more points for false answers than correct ones
10775:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10776:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10777:    }
10778: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10779:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10780:       document.forms.gradesupload.pcorrect.value=100;
10781:       document.forms.gradesupload.pincorrect.value=100;
10782:    }
10783: // If the values are different, cannot be attendance only
10784:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10785:        (gradingchoice=='attendance')) {
10786:        newgradingchoice='personnel';
10787:    }
10788: // Change grading choice to new one
10789:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10790:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10791:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10792:       } else {
10793:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10794:       }
10795:    }
10796: // Remember the old state
10797:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10798: }
10799: ENDUPFORM
10800:     $result.= <<ENDUPFORM;
10801: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10802: <input type="hidden" name="symb" value="$symb" />
10803: <input type="hidden" name="command" value="processclickerfile" />
10804: <input type="file" name="upfile" size="50" />
10805: <br /><label>$type: $selectform</label>
10806: ENDUPFORM
10807:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10808:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10809:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10810: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10811: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10812: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10813: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10814: <br />&nbsp;&nbsp;&nbsp;
10815: <input type="text" name="givenanswer" size="50" />
10816: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10817: ENDGRADINGFORM
10818:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10819:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10820:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10821: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10822: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10823: </form>
10824: ENDPERCFORM
10825:     $result.='</td>'.
10826:              &Apache::loncommon::end_data_table_row().
10827:              &Apache::loncommon::end_data_table();
10828:     return $result;
10829: }
10830: 
10831: sub process_clicker_file {
10832:     my ($r,$symb) = @_;
10833:     if (!$symb) {return '';}
10834: 
10835:     my %Saveable_Parameters=&clicker_grading_parameters();
10836:     &Apache::loncommon::store_course_settings('grades_clicker',
10837:                                               \%Saveable_Parameters);
10838:     my $result='';
10839:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10840: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10841: 	return $result;
10842:     }
10843:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10844:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10845:         return $result;
10846:     }
10847:     my $foundgiven=0;
10848:     if ($env{'form.gradingmechanism'} eq 'given') {
10849:         $env{'form.givenanswer'}=~s/^\s*//gs;
10850:         $env{'form.givenanswer'}=~s/\s*$//gs;
10851:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10852:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10853:         my @answers=split(/\,/,$env{'form.givenanswer'});
10854:         $foundgiven=$#answers+1;
10855:     }
10856:     my %clicker_ids=&gather_clicker_ids();
10857:     my %correct_ids;
10858:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10859: 	%correct_ids=&gather_adv_clicker_ids();
10860:     }
10861:     if ($env{'form.gradingmechanism'} eq 'specific') {
10862: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10863: 	   $correct_id=~tr/a-z/A-Z/;
10864: 	   $correct_id=~s/\s//gs;
10865: 	   $correct_id=~s/^[\#0]+//;
10866:            $correct_id=~s/[\-\:]//g;
10867:            if ($correct_id) {
10868: 	      $correct_ids{$correct_id}='specified';
10869:            }
10870:         }
10871:     }
10872:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10873: 	$result.=&mt('Score based on attendance only');
10874:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10875:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10876:     } else {
10877: 	my $number=0;
10878: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10879: 	foreach my $id (sort(keys(%correct_ids))) {
10880: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10881: 	    if ($correct_ids{$id} eq 'specified') {
10882: 		$result.=&mt('specified');
10883: 	    } else {
10884: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10885: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10886: 	    }
10887: 	    $number++;
10888: 	}
10889:         $result.="</p>\n";
10890:         if ($number==0) {
10891:             $result .=
10892:                  &Apache::lonhtmlcommon::confirm_success(
10893:                      &mt('No IDs found to determine correct answer'),1);
10894:             return $result;
10895:         }
10896:     }
10897:     if (length($env{'form.upfile'}) < 2) {
10898:         $result .=
10899:             &Apache::lonhtmlcommon::confirm_success(
10900:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10901:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10902:         return $result;
10903:     }
10904:     my $mimetype;
10905:     if ($env{'form.upfiletype'} eq 'iclicker') {
10906:         my $mm = new File::MMagic;
10907:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10908:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10909:             $result.= '<p>'.
10910:                 &Apache::lonhtmlcommon::confirm_success(
10911:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10912:             return $result;
10913:         }
10914:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10915:         $result .= '<p>'.
10916:             &Apache::lonhtmlcommon::confirm_success(
10917:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10918:         return $result;
10919:     }
10920: 
10921: # Were able to get all the info needed, now analyze the file
10922: 
10923:     $result.=&Apache::loncommon::studentbrowser_javascript();
10924:     $symb = &Apache::lonenc::check_encrypt($symb);
10925:     $result.=&Apache::loncommon::start_data_table().
10926:              &Apache::loncommon::start_data_table_header_row().
10927:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10928:              &Apache::loncommon::end_data_table_header_row().
10929:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10930: <td>
10931: <form method="post" action="/adm/grades" name="clickeranalysis">
10932: <input type="hidden" name="symb" value="$symb" />
10933: <input type="hidden" name="command" value="assignclickergrades" />
10934: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10935: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10936: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10937: ENDHEADER
10938:     if ($env{'form.gradingmechanism'} eq 'given') {
10939:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10940:     } 
10941:     my %responses;
10942:     my @questiontitles;
10943:     my $errormsg='';
10944:     my $number=0;
10945:     if ($env{'form.upfiletype'} eq 'iclicker') {
10946:         if ($mimetype eq 'text/plain') {
10947:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10948:         } elsif ($mimetype eq 'text/html') {
10949:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10950:         }
10951:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10952:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10953:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10954:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10955:     }
10956:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10957:              '<input type="hidden" name="number" value="'.$number.'" />'.
10958:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10959:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10960:              '<br />';
10961:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10962:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10963:        return $result;
10964:     } 
10965: # Remember Question Titles
10966: # FIXME: Possibly need delimiter other than ":"
10967:     for (my $i=0;$i<$number;$i++) {
10968:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10969:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10970:     }
10971:     my $correct_count=0;
10972:     my $student_count=0;
10973:     my $unknown_count=0;
10974: # Match answers with usernames
10975: # FIXME: Possibly need delimiter other than ":"
10976:     foreach my $id (keys(%responses)) {
10977:        if ($correct_ids{$id}) {
10978:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10979:           $correct_count++;
10980:        } elsif ($clicker_ids{$id}) {
10981:           if ($clicker_ids{$id}=~/\,/) {
10982: # More than one user with the same clicker!
10983:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10984:                            &Apache::loncommon::start_data_table_row()."<td>".
10985:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10986:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10987:                            "<select name='multi".$id."'>";
10988:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10989:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10990:              }
10991:              $result.='</select>';
10992:              $unknown_count++;
10993:           } else {
10994: # Good: found one and only one user with the right clicker
10995:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10996:              $student_count++;
10997:           }
10998:        } else {
10999:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11000:                            &Apache::loncommon::start_data_table_row()."<td>".
11001:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11002:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11003:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11004:                    "\n".&mt("Domain").": ".
11005:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11006:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11007:           $unknown_count++;
11008:        }
11009:     }
11010:     $result.='<hr />'.
11011:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11012:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11013:        if ($correct_count==0) {
11014:           $errormsg.="Found no correct answers for grading!";
11015:        } elsif ($correct_count>1) {
11016:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11017:        }
11018:     }
11019:     if ($number<1) {
11020:        $errormsg.="Found no questions.";
11021:     }
11022:     if ($errormsg) {
11023:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11024:     } else {
11025:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11026:     }
11027:     $result.='</form></td>'.
11028:              &Apache::loncommon::end_data_table_row().
11029:              &Apache::loncommon::end_data_table();
11030:     return $result;
11031: }
11032: 
11033: sub iclicker_eval {
11034:     my ($questiontitles,$responses)=@_;
11035:     my $number=0;
11036:     my $errormsg='';
11037:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11038:         my %components=&Apache::loncommon::record_sep($line);
11039:         my @entries=map {$components{$_}} (sort(keys(%components)));
11040: 	if ($entries[0] eq 'Question') {
11041: 	    for (my $i=3;$i<$#entries;$i+=6) {
11042: 		$$questiontitles[$number]=$entries[$i];
11043: 		$number++;
11044: 	    }
11045: 	}
11046: 	if ($entries[0]=~/^\#/) {
11047: 	    my $id=$entries[0];
11048: 	    my @idresponses;
11049: 	    $id=~s/^[\#0]+//;
11050: 	    for (my $i=0;$i<$number;$i++) {
11051: 		my $idx=3+$i*6;
11052:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11053: 		push(@idresponses,$entries[$idx]);
11054: 	    }
11055: 	    $$responses{$id}=join(',',@idresponses);
11056: 	}
11057:     }
11058:     return ($errormsg,$number);
11059: }
11060: 
11061: sub iclickerxml_eval {
11062:     my ($questiontitles,$responses)=@_;
11063:     my $number=0;
11064:     my $errormsg='';
11065:     my @state;
11066:     my %respbyid;
11067:     my $p = HTML::Parser->new
11068:     (
11069:         xml_mode => 1,
11070:         start_h =>
11071:             [sub {
11072:                  my ($tagname,$attr) = @_;
11073:                  push(@state,$tagname);
11074:                  if ("@state" eq "ssn p") {
11075:                      my $title = $attr->{qn};
11076:                      $title =~ s/(^\s+|\s+$)//g;
11077:                      $questiontitles->[$number]=$title;
11078:                  } elsif ("@state" eq "ssn p v") {
11079:                      my $id = $attr->{id};
11080:                      my $entry = $attr->{ans};
11081:                      $id=~s/^[\#0]+//;
11082:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11083:                      $respbyid{$id}[$number] = $entry;
11084:                  }
11085:             }, "tagname, attr"],
11086:          end_h =>
11087:                [sub {
11088:                    my ($tagname) = @_;
11089:                    if ("@state" eq "ssn p") {
11090:                        $number++;
11091:                    }
11092:                    pop(@state);
11093:                 }, "tagname"],
11094:     );
11095: 
11096:     $p->parse($env{'form.upfile'});
11097:     $p->eof;
11098:     foreach my $id (keys(%respbyid)) {
11099:         $responses->{$id}=join(',',@{$respbyid{$id}});
11100:     }
11101:     return ($errormsg,$number);
11102: }
11103: 
11104: sub interwrite_eval {
11105:     my ($questiontitles,$responses)=@_;
11106:     my $number=0;
11107:     my $errormsg='';
11108:     my $skipline=1;
11109:     my $questionnumber=0;
11110:     my %idresponses=();
11111:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11112:         my %components=&Apache::loncommon::record_sep($line);
11113:         my @entries=map {$components{$_}} (sort(keys(%components)));
11114:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11115:         if ($entries[1] eq 'Response') { $skipline=1; }
11116:         next if $skipline;
11117:         if ($entries[0]!=$questionnumber) {
11118:            $questionnumber=$entries[0];
11119:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11120:            $number++;
11121:         }
11122:         my $id=$entries[4];
11123:         $id=~s/^[\#0]+//;
11124:         $id=~s/^v\d*\://i;
11125:         $id=~s/[\-\:]//g;
11126:         $idresponses{$id}[$number]=$entries[6];
11127:     }
11128:     foreach my $id (keys(%idresponses)) {
11129:        $$responses{$id}=join(',',@{$idresponses{$id}});
11130:        $$responses{$id}=~s/^\s*\,//;
11131:     }
11132:     return ($errormsg,$number);
11133: }
11134: 
11135: sub turning_eval {
11136:     my ($questiontitles,$responses)=@_;
11137:     my $number=0;
11138:     my $errormsg='';
11139:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11140:         my %components=&Apache::loncommon::record_sep($line);
11141:         my @entries=map {$components{$_}} (sort(keys(%components)));
11142:         if ($#entries>$number) { $number=$#entries; }
11143:         my $id=$entries[0];
11144:         my @idresponses;
11145:         $id=~s/^[\#0]+//;
11146:         unless ($id) { next; }
11147:         for (my $idx=1;$idx<=$#entries;$idx++) {
11148:             $entries[$idx]=~s/\,/\;/g;
11149:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11150:             push(@idresponses,$entries[$idx]);
11151:         }
11152:         $$responses{$id}=join(',',@idresponses);
11153:     }
11154:     for (my $i=1; $i<=$number; $i++) {
11155:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11156:     }
11157:     return ($errormsg,$number);
11158: }
11159: 
11160: 
11161: sub assign_clicker_grades {
11162:     my ($r,$symb) = @_;
11163:     if (!$symb) {return '';}
11164: # See which part we are saving to
11165:     my $res_error;
11166:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11167:     if ($res_error) {
11168:         return &navmap_errormsg();
11169:     }
11170: # FIXME: This should probably look for the first handgradeable part
11171:     my $part=$$partlist[0];
11172: # Start screen output
11173:     my $result = &Apache::loncommon::start_data_table().
11174:                  &Apache::loncommon::start_data_table_header_row().
11175:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11176:                  &Apache::loncommon::end_data_table_header_row().
11177:                  &Apache::loncommon::start_data_table_row().'<td>';
11178: # Get correct result
11179: # FIXME: Possibly need delimiter other than ":"
11180:     my @correct=();
11181:     my $gradingmechanism=$env{'form.gradingmechanism'};
11182:     my $number=$env{'form.number'};
11183:     if ($gradingmechanism ne 'attendance') {
11184:        foreach my $key (keys(%env)) {
11185:           if ($key=~/^form\.correct\:/) {
11186:              my @input=split(/\,/,$env{$key});
11187:              for (my $i=0;$i<=$#input;$i++) {
11188:                  if (($correct[$i]) && ($input[$i]) &&
11189:                      ($correct[$i] ne $input[$i])) {
11190:                     $result.='<br /><span class="LC_warning">'.
11191:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11192:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11193:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11194:                     $correct[$i]=$input[$i];
11195:                  }
11196:              }
11197:           }
11198:        }
11199:        for (my $i=0;$i<$number;$i++) {
11200:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11201:              $result.='<br /><span class="LC_error">'.
11202:                       &mt('No correct result given for question "[_1]"!',
11203:                           $env{'form.question:'.$i}).'</span>';
11204:           }
11205:        }
11206:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11207:     }
11208: # Start grading
11209:     my $pcorrect=$env{'form.pcorrect'};
11210:     my $pincorrect=$env{'form.pincorrect'};
11211:     my $storecount=0;
11212:     my %users=();
11213:     foreach my $key (keys(%env)) {
11214:        my $user='';
11215:        if ($key=~/^form\.student\:(.*)$/) {
11216:           $user=$1;
11217:        }
11218:        if ($key=~/^form\.unknown\:(.*)$/) {
11219:           my $id=$1;
11220:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11221:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11222:           } elsif ($env{'form.multi'.$id}) {
11223:              $user=$env{'form.multi'.$id};
11224:           }
11225:        }
11226:        if ($user) {
11227:           if ($users{$user}) {
11228:              $result.='<br /><span class="LC_warning">'.
11229:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11230:                       '</span><br />';
11231:           }
11232:           $users{$user}=1; 
11233:           my @answer=split(/\,/,$env{$key});
11234:           my $sum=0;
11235:           my $realnumber=$number;
11236:           for (my $i=0;$i<$number;$i++) {
11237:              if  ($correct[$i] eq '-') {
11238:                 $realnumber--;
11239:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11240:                 if ($gradingmechanism eq 'attendance') {
11241:                    $sum+=$pcorrect;
11242:                 } elsif ($correct[$i] eq '*') {
11243:                    $sum+=$pcorrect;
11244:                 } else {
11245: # We actually grade if correct or not
11246:                    my $increment=$pincorrect;
11247: # Special case: numerical answer "0"
11248:                    if ($correct[$i] eq '0') {
11249:                       if ($answer[$i]=~/^[0\.]+$/) {
11250:                          $increment=$pcorrect;
11251:                       }
11252: # General numerical answer, both evaluate to something non-zero
11253:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11254:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11255:                          $increment=$pcorrect;
11256:                       }
11257: # Must be just alphanumeric
11258:                    } elsif ($answer[$i] eq $correct[$i]) {
11259:                       $increment=$pcorrect;
11260:                    }
11261:                    $sum+=$increment;
11262:                 }
11263:              }
11264:           }
11265:           my $ave=$sum/(100*$realnumber);
11266: # Store
11267:           my ($username,$domain)=split(/\:/,$user);
11268:           my %grades=();
11269:           $grades{"resource.$part.solved"}='correct_by_override';
11270:           $grades{"resource.$part.awarded"}=$ave;
11271:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11272:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11273:                                                  $env{'request.course.id'},
11274:                                                  $domain,$username);
11275:           if ($returncode ne 'ok') {
11276:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11277:           } else {
11278:              $storecount++;
11279:           }
11280:        }
11281:     }
11282: # We are done
11283:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11284:              '</td>'.
11285:              &Apache::loncommon::end_data_table_row().
11286:              &Apache::loncommon::end_data_table();
11287:     return $result;
11288: }
11289: 
11290: sub navmap_errormsg {
11291:     return '<div class="LC_error">'.
11292:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11293:            &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>').
11294:            '</div>';
11295: }
11296: 
11297: sub startpage {
11298:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
11299:     my %args;
11300:     if ($onload) {
11301:          my %loaditems = (
11302:                         'onload' => $onload,
11303:                       );
11304:          $args{'add_entries'} = \%loaditems;
11305:     }
11306:     if ($nomenu) {
11307:         $args{'only_body'} = 1; 
11308:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
11309:     } else {
11310:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11311:         $args{'bread_crumbs'} = $crumbs;
11312:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
11313:         if ($env{'request.course.id'}) {
11314:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11315:         }
11316:     }
11317:     unless ($nodisplayflag) {
11318:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11319:     }
11320: }
11321: 
11322: sub select_problem {
11323:     my ($r)=@_;
11324:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11325:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11326:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11327:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11328: }
11329: 
11330: sub handler {
11331:     my $request=$_[0];
11332:     &reset_caches();
11333:     if ($request->header_only) {
11334:         &Apache::loncommon::content_type($request,'text/html');
11335:         $request->send_http_header;
11336:         return OK;
11337:     }
11338:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11339: 
11340: # see what command we need to execute
11341: 
11342:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11343:     my $command=$commands[0];
11344: 
11345:     &init_perm();
11346:     if (!$env{'request.course.id'}) {
11347:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11348:                 ($command =~ /^scantronupload/)) {
11349:             # Not in a course.
11350:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11351:             return HTTP_NOT_ACCEPTABLE;
11352:         }
11353:     } elsif (!%perm) {
11354:         $request->internal_redirect('/adm/quickgrades');
11355:         return OK;
11356:     }
11357:     &Apache::loncommon::content_type($request,'text/html');
11358:     $request->send_http_header;
11359: 
11360:     if ($#commands > 0) {
11361: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11362:     }
11363: 
11364: # see what the symb is
11365: 
11366:     my $symb=$env{'form.symb'};
11367:     unless ($symb) {
11368:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11369:        $symb=&Apache::lonnet::symbread($url);
11370:     }
11371:     &Apache::lonenc::check_decrypt(\$symb);
11372: 
11373:     $ssi_error = 0;
11374:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11375: #
11376: # Not called from a resource, but inside a course
11377: #    
11378:         &startpage($request,undef,[],1,1);
11379:         &select_problem($request);
11380:     } else {
11381: 	if ($command eq 'submission' && $perm{'vgr'}) {
11382:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11383:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11384:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11385:                     &choose_task_version_form($symb,$env{'form.student'},
11386:                                               $env{'form.userdom'});
11387:             }
11388:             my $divforres;
11389:             if ($env{'form.student'} eq '') {
11390:                 $js .= &part_selector_js();
11391:                 $onload = "toggleParts('gradesub');";
11392:             } else {
11393:                 $divforres = 1;
11394:             }
11395:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
11396:             if ($versionform) {
11397:                 $request->print($versionform);
11398:             }
11399: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11400:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11401:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11402:                 &choose_task_version_form($symb,$env{'form.student'},
11403:                                           $env{'form.userdom'},
11404:                                           $env{'form.inhibitmenu'});
11405:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
11406:             if ($versionform) {
11407:                 $request->print($versionform);
11408:             }
11409:             $request->print('<br clear="all" />');
11410:             $request->print(&show_previous_task_version($request,$symb));
11411: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11412:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11413:                                        {href=>'',text=>'Select student'}],1,1);
11414: 	    &pickStudentPage($request,$symb);
11415: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11416:             &startpage($request,$symb,
11417:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11418:                                        {href=>'',text=>'Select student'},
11419:                                        {href=>'',text=>'Grade student'}],1,1);
11420: 	    &displayPage($request,$symb);
11421: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11422:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11423:                                        {href=>'',text=>'Select student'},
11424:                                        {href=>'',text=>'Grade student'},
11425:                                        {href=>'',text=>'Store grades'}],1,1);
11426: 	    &updateGradeByPage($request,$symb);
11427: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11428:             &startpage($request,$symb,[{href=>'',text=>'...'},
11429:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
11430: 	    &processGroup($request,$symb);
11431: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11432:             &startpage($request,$symb);
11433: 	    $request->print(&grading_menu($request,$symb));
11434: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11435:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11436: 	    $request->print(&submit_options($request,$symb));
11437:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11438:             my $js = &part_selector_js();
11439:             my $onload = "toggleParts('gradesub');";
11440:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11441:                        undef,undef,undef,undef,undef,$js,$onload);
11442:             $request->print(&listStudents($request,$symb,'graded'));
11443:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11444:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11445:             $request->print(&submit_options_table($request,$symb));
11446:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11447:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11448:             $request->print(&submit_options_sequence($request,$symb));
11449: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11450:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11451: 	    $request->print(&viewgrades($request,$symb));
11452: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11453:             &startpage($request,$symb,[{href=>'',text=>'...'},
11454:                                        {href=>'',text=>'Store grades'}]);
11455: 	    $request->print(&processHandGrade($request,$symb));
11456: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11457:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11458:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11459:                                                                              text=>"Modify grades"},
11460:                                        {href=>'', text=>"Store grades"}]);
11461: 	    $request->print(&editgrades($request,$symb));
11462:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11463:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11464:             $request->print(&initialverifyreceipt($request,$symb));
11465: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11466:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11467:                                        {href=>'',text=>'Verification Result'}]);
11468: 	    $request->print(&verifyreceipt($request,$symb));
11469:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11470:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11471:             $request->print(&process_clicker($request,$symb));
11472:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11473:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11474:                                        {href=>'', text=>'Process clicker file'}]);
11475:             $request->print(&process_clicker_file($request,$symb));
11476:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11477:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11478:                                        {href=>'', text=>'Process clicker file'},
11479:                                        {href=>'', text=>'Store grades'}]);
11480:             $request->print(&assign_clicker_grades($request,$symb));
11481: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11482:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11483: 	    $request->print(&upcsvScores_form($request,$symb));
11484: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11485:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11486: 	    $request->print(&csvupload($request,$symb));
11487: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11488:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11489: 	    $request->print(&csvuploadmap($request,$symb));
11490: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11491: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11492:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11493: 		$request->print(&csvuploadoptions($request,$symb));
11494: 	    } else {
11495: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11496: 		    $env{'form.upfile_associate'} = 'reverse';
11497: 		} else {
11498: 		    $env{'form.upfile_associate'} = 'forward';
11499: 		}
11500:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11501: 		$request->print(&csvuploadmap($request,$symb));
11502: 	    }
11503: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11504:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11505: 	    $request->print(&csvuploadassign($request,$symb));
11506: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11507:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11508:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11509: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11510:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11511:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11512:  	    $request->print(&scantron_do_warning($request,$symb));
11513: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11514:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11515: 	    $request->print(&scantron_validate_file($request,$symb));
11516: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11517:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11518: 	    $request->print(&scantron_process_students($request,$symb));
11519:  	} elsif ($command eq 'scantronupload' && 
11520:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11521:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11522:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11523:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11524:  	} elsif ($command eq 'scantronupload_save' &&
11525:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11526:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11527:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11528:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11529:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11530:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11531:         } elsif ($command eq 'scantronupload_delete' &&
11532:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11533:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11534:             &scantron_upload_delete($request,$symb);
11535:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11536:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11537:             $request->print(&checkscantron_results($request,$symb));
11538:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11539:             my $js = &part_selector_js();
11540:             my $onload = "toggleParts('gradingMenu');";
11541:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11542:                        undef,undef,undef,undef,undef,$js,$onload);
11543:             $request->print(&submit_options_download($request,$symb));
11544:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11545:             &startpage($request,$symb,
11546:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11547:     {href=>'', text=>'Download submitted files'}],
11548:                undef,undef,undef,undef,undef,undef,undef,1);
11549:             &submit_download_link($request,$symb);
11550: 	} elsif ($command) {
11551:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11552: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11553: 	}
11554:     }
11555:     if ($ssi_error) {
11556: 	&ssi_print_error($request);
11557:     }
11558:     if ($env{'form.inhibitmenu'}) {
11559:         $request->print(&Apache::loncommon::end_page());
11560:     } elsif ($env{'request.course.id'}) {
11561:         &Apache::lonquickgrades::endGradeScreen($request);
11562:     }
11563:     &reset_caches();
11564:     return OK;
11565: }
11566: 
11567: 1;
11568: 
11569: __END__;
11570: 
11571: 
11572: =head1 NAME
11573: 
11574: Apache::grades
11575: 
11576: =head1 SYNOPSIS
11577: 
11578: Handles the viewing of grades.
11579: 
11580: This is part of the LearningOnline Network with CAPA project
11581: described at http://www.lon-capa.org.
11582: 
11583: =head1 OVERVIEW
11584: 
11585: Do an ssi with retries:
11586: While I'd love to factor out this with the version in lonprintout,
11587: 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
11588: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11589: 
11590: At least the logic that drives this has been pulled out into loncommon.
11591: 
11592: 
11593: 
11594: ssi_with_retries - Does the server side include of a resource.
11595:                      if the ssi call returns an error we'll retry it up to
11596:                      the number of times requested by the caller.
11597:                      If we still have a problem, no text is appended to the
11598:                      output and we set some global variables.
11599:                      to indicate to the caller an SSI error occurred.  
11600:                      All of this is supposed to deal with the issues described
11601:                      in LON-CAPA BZ 5631 see:
11602:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11603:                      by informing the user that this happened.
11604: 
11605: Parameters:
11606:   resource   - The resource to include.  This is passed directly, without
11607:                interpretation to lonnet::ssi.
11608:   form       - The form hash parameters that guide the interpretation of the resource
11609:                
11610:   retries    - Number of retries allowed before giving up completely.
11611: Returns:
11612:   On success, returns the rendered resource identified by the resource parameter.
11613: Side Effects:
11614:   The following global variables can be set:
11615:    ssi_error                - If an unrecoverable error occurred this becomes true.
11616:                               It is up to the caller to initialize this to false
11617:                               if desired.
11618:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11619:                               of the resource that could not be rendered by the ssi
11620:                               call.
11621:    ssi_error_message   - The error string fetched from the ssi response
11622:                               in the event of an error.
11623: 
11624: 
11625: =head1 HANDLER SUBROUTINE
11626: 
11627: ssi_with_retries()
11628: 
11629: =head1 SUBROUTINES
11630: 
11631: =over
11632: 
11633: =head1 Routines to display previous version of a Task for a specific student
11634: 
11635: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11636: can receive another opportunity. Access to tasks is slot-based. If a slot
11637: requires a proctor to check-in the student, a new version of the Task will
11638: be created when the student is checked in to the new opportunity.
11639: 
11640: If a particular student has tried two or more versions of a particular task,
11641: the submission screen provides a user with vgr privileges (e.g., a Course
11642: Coordinator) the ability to display a previous version worked on by the
11643: student.  By default, the current version is displayed. If a previous version
11644: has been selected for display, submission data are only shown that pertain
11645: to that particular version, and the interface to submit grades is not shown.
11646: 
11647: =over 4
11648: 
11649: =item show_previous_task_version()
11650: 
11651: Displays a specified version of a student's Task, as the student sees it.
11652: 
11653: Inputs: 2
11654:         request - request object
11655:         symb    - unique symb for current instance of resource
11656: 
11657: Output: None.
11658: 
11659: Side Effects: calls &show_problem() to print version of Task, with
11660:               version contained in form item: $env{'form.previousversion'}
11661: 
11662: =item choose_task_version_form()
11663: 
11664: Displays a web form used to select which version of a student's view of a
11665: Task should be displayed.  Either launches a pop-up window, or replaces
11666: content in existing pop-up, or replaces page in main window.
11667: 
11668: Inputs: 4
11669:         symb    - unique symb for current instance of resource
11670:         uname   - username of student
11671:         udom    - domain of student
11672:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11673:                   breadcrumbs etc., are displayed
11674: 
11675: Output: 4
11676:         current   - student's current version
11677:         displayed - student's version being displayed
11678:         result    - scalar containing HTML for web form used to switch to
11679:                     a different version (or a link to close window, if pop-up).
11680:         js        - javascript for processing selection in versions web form
11681: 
11682: Side Effects: None.
11683: 
11684: =item previous_display_javascript()
11685: 
11686: Inputs: 2
11687:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11688:                   breadcrumbs etc., are displayed.
11689:         current - student's current version number.
11690: 
11691: Output: 1
11692:         js      - javascript for processing selection in versions web form.
11693: 
11694: Side Effects: None.
11695: 
11696: =back
11697: 
11698: =head1 Routines to process bubblesheet data.
11699: 
11700: =over 4
11701: 
11702: =item scantron_get_correction() : 
11703: 
11704:    Builds the interface screen to interact with the operator to fix a
11705:    specific error condition in a specific scanline
11706: 
11707:  Arguments:
11708:     $r           - Apache request object
11709:     $i           - number of the current scanline
11710:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11711:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11712:     $line        - full contents of the current scanline
11713:     $error       - error condition, valid values are
11714:                    'incorrectCODE', 'duplicateCODE',
11715:                    'doublebubble', 'missingbubble',
11716:                    'duplicateID', 'incorrectID'
11717:     $arg         - extra information needed
11718:        For errors:
11719:          - duplicateID   - paper number that this studentID was seen before on
11720:          - duplicateCODE - array ref of the paper numbers this CODE was
11721:                            seen on before
11722:          - incorrectCODE - current incorrect CODE 
11723:          - doublebubble  - array ref of the bubble lines that have double
11724:                            bubble errors
11725:          - missingbubble - array ref of the bubble lines that have missing
11726:                            bubble errors
11727: 
11728:    $randomorder - True if exam folder has randomorder set
11729:    $randompick  - True if exam folder has randompick set
11730:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11731:                      for current line to question number used for same question
11732:                      in "Master Seqence" (as seen by Course Coordinator).
11733:    $startline   - Reference to hash where key is question number (0 is first)
11734:                   and value is number of first bubble line for current student
11735:                   or code-based randompick and/or randomorder.
11736: 
11737: 
11738: 
11739: =item  scantron_get_maxbubble() : 
11740: 
11741:    Arguments:
11742:        $nav_error  - Reference to scalar which is a flag to indicate a
11743:                       failure to retrieve a navmap object.
11744:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11745:        calling routine should trap the error condition and display the warning
11746:        found in &navmap_errormsg().
11747: 
11748:        $scantron_config - Reference to bubblesheet format configuration hash.
11749: 
11750:    Returns the maximum number of bubble lines that are expected to
11751:    occur. Does this by walking the selected sequence rendering the
11752:    resource and then checking &Apache::lonxml::get_problem_counter()
11753:    for what the current value of the problem counter is.
11754: 
11755:    Caches the results to $env{'form.scantron_maxbubble'},
11756:    $env{'form.scantron.bubble_lines.n'}, 
11757:    $env{'form.scantron.first_bubble_line.n'} and
11758:    $env{"form.scantron.sub_bubblelines.n"}
11759:    which are the total number of bubble lines, the number of bubble
11760:    lines for response n and number of the first bubble line for response n,
11761:    and a comma separated list of numbers of bubble lines for sub-questions
11762:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11763: 
11764: 
11765: =item  scantron_validate_missingbubbles() : 
11766: 
11767:    Validates all scanlines in the selected file to not have any
11768:     answers that don't have bubbles that have not been verified
11769:     to be bubble free.
11770: 
11771: =item  scantron_process_students() : 
11772: 
11773:    Routine that does the actual grading of the bubblesheet information.
11774: 
11775:    The parsed scanline hash is added to %env 
11776: 
11777:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11778:    foreach resource , with the form data of
11779: 
11780: 	'submitted'     =>'scantron' 
11781: 	'grade_target'  =>'grade',
11782: 	'grade_username'=> username of student
11783: 	'grade_domain'  => domain of student
11784: 	'grade_courseid'=> of course
11785: 	'grade_symb'    => symb of resource to grade
11786: 
11787:     This triggers a grading pass. The problem grading code takes care
11788:     of converting the bubbled letter information (now in %env) into a
11789:     valid submission.
11790: 
11791: =item  scantron_upload_scantron_data() :
11792: 
11793:     Creates the screen for adding a new bubblesheet data file to a course.
11794: 
11795: =item  scantron_upload_scantron_data_save() : 
11796: 
11797:    Adds a provided bubble information data file to the course if user
11798:    has the correct privileges to do so.
11799: 
11800: = item scantron_upload_delete() :
11801: 
11802:    Deletes a previously uploaded bubble information data file, if user
11803:    was the one who uploaded the file, and has the privileges to do so.
11804: 
11805: =item  valid_file() :
11806: 
11807:    Validates that the requested bubble data file exists in the course.
11808: 
11809: =item  scantron_download_scantron_data() : 
11810: 
11811:    Shows a list of the three internal files (original, corrected,
11812:    skipped) for a specific bubblesheet data file that exists in the
11813:    course.
11814: 
11815: =item  scantron_validate_ID() : 
11816: 
11817:    Validates all scanlines in the selected file to not have any
11818:    invalid or underspecified student/employee IDs
11819: 
11820: =item navmap_errormsg() :
11821: 
11822:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11823:    Should be called whenever the request to instantiate a navmap object fails.
11824: 
11825: =back
11826: 
11827: =back
11828: 
11829: =cut

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