Annotation of loncom/homework/grades.pm, revision 1.596.2.12.2.60.2.5

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.596.2.12.2.  0.2.5(ra    4:ep-23): # $Id: grades.pm,v 1.596.2.12.2.60.2.4 2023/07/05 23:49:18 raeburn Exp $
1.17      albertel    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: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.596.2.4  raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.596.2.12.2.  1(raebur   46:0): use Apache::lonstathelpers;
1.596.2.4  raeburn    47: use Apache::bridgetask();
1.596.2.12.2.  4(raebur   48:8): use Apache::lontexconvert();
          0.2.4(ra   49:ul-23): use String::Similarity;
          7(raebur   50:9): use HTML::Parser();
                     51:9): use File::MMagic;
1.359     www        52: use LONCAPA;
                     53: 
1.315     bowersj2   54: use POSIX qw(floor);
1.87      www        55: 
1.435     foxr       56: 
1.513     foxr       57: 
1.435     foxr       58: my %perm=();
1.596.2.12.2.  (raeburn   59:): my %old_essays=();
1.447     foxr       60: 
1.513     foxr       61: #  These variables are used to recover from ssi errors
                     62: 
                     63: my $ssi_retries = 5;
                     64: my $ssi_error;
                     65: my $ssi_error_resource;
                     66: my $ssi_error_message;
                     67: 
                     68: 
                     69: sub ssi_with_retries {
                     70:     my ($resource, $retries, %form) = @_;
                     71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     72:     if ($response->is_error) {
                     73: 	$ssi_error          = 1;
                     74: 	$ssi_error_resource = $resource;
                     75: 	$ssi_error_message  = $response->code . " " . $response->message;
                     76:     }
                     77: 
                     78:     return $content;
                     79: 
                     80: }
                     81: #
                     82: #  Prodcuces an ssi retry failure error message to the user:
                     83: #
                     84: 
                     85: sub ssi_print_error {
                     86:     my ($r) = @_;
1.516     raeburn    87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     88:     $r->print('
                     89: <br />
                     90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     91: <p>
                     92: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     94: '.&mt('Error:').' '.$ssi_error_message.'
                     95: </p>
                     96: <p>'.
                     97: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     99: '</p>');
                    100:     return;
1.513     foxr      101: }
                    102: 
1.44      ng        103: #
1.146     albertel  104: # --- Retrieve the parts from the metadata file.---
1.596.2.12.2.  1(raebur  105:0): # Returns an array of everything that the resources stores away
                    106:0): #
                    107:0): 
1.44      ng        108: sub getpartlist {
1.582     raeburn   109:     my ($symb,$errorref) = @_;
1.439     albertel  110: 
                    111:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   112:     unless (ref($navmap)) {
                    113:         if (ref($errorref)) { 
                    114:             $$errorref = 'navmap';
                    115:             return;
                    116:         }
                    117:     }
1.439     albertel  118:     my $res      = $navmap->getBySymb($symb);
                    119:     my $partlist = $res->parts();
                    120:     my $url      = $res->src();
1.596.2.12.2.  0.2.4(ra  121:ul-23):     my $toolsymb;
                    122:ul-23):     if ($url =~ /ext\.tool$/) {
                    123:ul-23):         $toolsymb = $symb;
                    124:ul-23):     }
                    125:ul-23):     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  126: 
1.146     albertel  127:     my @stores;
1.439     albertel  128:     foreach my $part (@{ $partlist }) {
1.146     albertel  129: 	foreach my $key (@metakeys) {
                    130: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    131: 	}
                    132:     }
                    133:     return @stores;
1.2       albertel  134: }
                    135: 
1.129     ng        136: #--- Format fullname, username:domain if different for display
                    137: #--- Use anywhere where the student names are listed
                    138: sub nameUserString {
                    139:     my ($type,$fullname,$uname,$udom) = @_;
                    140:     if ($type eq 'header') {
1.485     albertel  141: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        142:     } else {
1.398     albertel  143: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    144: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        145:     }
                    146: }
                    147: 
1.44      ng        148: #--- Get the partlist and the response type for a given problem. ---
                    149: #--- Indicate if a response type is coded handgraded or not. ---
1.596.2.12.2.  1(raebur  150:0): #--- Count responseIDs, essayresponse items, and dropbox items ---
                    151:0): #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        152: sub response_type {
1.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.596.2.12.2.  1(raebur  168:0):     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  169:     my %vPart = 
                    170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  171:     my (%response_types,%handgrade);
                    172:     foreach my $part (@{ $partlist }) {
1.392     albertel  173: 	next if (%vPart && !exists($vPart{$part}));
                    174: 
1.377     albertel  175: 	my @types = $res->responseType($part);
                    176: 	my @ids = $res->responseIds($part);
                    177: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.596.2.12.2.  1(raebur  178:0):             $numresp ++;
1.377     albertel  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.596.2.12.2.  1(raebur  180:0):             if ($types[$i] eq 'essay') {
                    181:0):                 $numessay ++;
                    182:0):                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    183:0):                     $numdropbox ++;
                    184:0):                 }
                    185:0):             }
1.377     albertel  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    188: 				     '.handgrade',$symb);
1.41      ng        189: 	}
                    190:     }
1.596.2.12.2.  1(raebur  191:0):     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        192: }
                    193: 
1.375     albertel  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: 
1.207     albertel  206: sub get_display_part {
1.324     albertel  207:     my ($partID,$symb)=@_;
1.207     albertel  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    209:     if (defined($display) and $display ne '') {
1.577     bisitz    210:         $display.= ' (<span class="LC_internal_info">'
                    211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  212:     } else {
                    213: 	$display=$partID;
                    214:     }
                    215:     return $display;
                    216: }
1.269     raeburn   217: 
1.596.2.12.2.  1(raebur  218:0): #--- Show parts and response type
1.118     ng        219: sub showResourceInfo {
1.596.2.12.2.  1(raebur  220:0):     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    221:0):     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    222:0):         return '<br clear="all">';
                    223:0):     }
                    224:0):     my $coltitle = &mt('Problem Part Shown');
                    225:0):     if ($checkboxes) {
                    226:0):         $coltitle = &mt('Problem Part');
                    227:0):     } else {
                    228:0):         my $checkedparts = 0;
                    229:0):         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    230:0):             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    231:0):                 $checkedparts ++;
                    232:0):             }
                    233:0):         }
                    234:0):         if ($checkedparts == scalar(@{$partlist})) {
                    235:0):             return '<br clear="all">';
                    236:0):         }
                    237:0):         if ($uploads) {
                    238:0):             $coltitle = &mt('Problem Part Selected');
1.582     raeburn   239:         }
                    240:     }
1.596.2.12.2.  1(raebur  241:0):     my $result = '<div class="LC_left_float" style="display:inline-block;">';
1.584     bisitz    242:     if ($checkboxes) {
1.596.2.12.2.  1(raebur  243:0):         my $legend = &mt('Parts to display');
                    244:0):         if ($uploads) {
                    245:0):             $legend = &mt('Part(s) with dropbox');
                    246:0):         }
                    247:0):         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    248:0):                    '<span class="LC_nobreak">'.
                    249:0):                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    250:0):                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    251:0):                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    252:0):                    &mt('Selected parts').'</label></span>'.
                    253:0):                    '<div id="LC_partselector" style="display:none">';
1.584     bisitz    254:     }
1.596.2.12.2.  1(raebur  255:0):     $result .= &Apache::loncommon::start_data_table()
                    256:0):               .&Apache::loncommon::start_data_table_header_row();
                    257:0):     if ($checkboxes) {
                    258:0):         $result .= '<th>'.&mt('Display?').'</th>';
                    259:0):     }
                    260:0):     $result .= '<th>'.$coltitle.'</th>'
                    261:0):               .'<th>'.&mt('Res. ID').'</th>'
                    262:0):               .'<th>'.&mt('Type').'</th>'
                    263:0):               .&Apache::loncommon::end_data_table_header_row();
1.154     albertel  264:     my %partsseen;
1.524     raeburn   265:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    267:             my $responsetype = $responseType->{$partID}->{$resID};
1.596.2.12.2.  1(raebur  268:0):             if ($uploads) {
                    269:0):                 next unless ($responsetype eq 'essay');
                    270:0):                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    271:0):             }
                    272:0):             my $display_part=&get_display_part($partID,$symb);
                    273:0):             if (exists($partsseen{$partID})) {
                    274:0):                 $result.=&Apache::loncommon::continue_data_table_row();
                    275:0):             } else {
                    276:0):                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    277:0):                 $result.=&Apache::loncommon::start_data_table_row().
                    278:0):                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    279:0):                 if ($checkboxes) {
                    280:0):                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    281:0):                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
1.584     bisitz    282:                 } else {
1.596.2.12.2.  1(raebur  283:0):                     $result.=$display_part.'</td>';
1.584     bisitz    284:                 }
                    285:             }
1.596.2.12.2.  1(raebur  286:0):             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
1.584     bisitz    287:                     .'<td>'.&mt($responsetype).'</td>'
                    288:                     .&Apache::loncommon::end_data_table_row();
                    289:         }
1.118     ng        290:     }
1.584     bisitz    291:     $result.=&Apache::loncommon::end_data_table();
1.596.2.12.2.  1(raebur  292:0):     if ($checkboxes) {
                    293:0):         $result .= '</div></fieldset>';
                    294:0):     }
                    295:0):     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
          2(raebur  296:0):     if (!keys(%partsseen)) {
                    297:0):         $result = '';
                    298:0):         if ($uploads) {
                    299:0):             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    300:0):                    '<p class="LC_info">'.
                    301:0):                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    302:0):                    '</p>';
                    303:0):         } else {
                    304:0):             return '<br clear="all" />';
                    305:0):         }
          0.2.4(ra  306:ul-23):     }
          1(raebur  307:0):     return $result;
                    308:0): }
                    309:0): 
                    310:0): sub part_selector_js {
                    311:0):     my $js = <<"END";
                    312:0): function toggleParts(formname) {
                    313:0):     if (document.getElementById('LC_partselector')) {
                    314:0):         var index = '';
                    315:0):         if (document.forms.length) {
                    316:0):             for (var i=0; i<document.forms.length; i++) {
                    317:0):                 if (document.forms[i].name == formname) {
                    318:0):                     index = i;
                    319:0):                     break;
                    320:0):                 }
                    321:0):             }
                    322:0):         }
                    323:0):         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    324:0):             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    325:0):                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    326:0):                    var val = document.forms[index].elements['chooseparts'][i].value;
                    327:0):                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    328:0):                         document.getElementById('LC_partselector').style.display = 'block';
                    329:0):                     } else {
                    330:0):                         document.getElementById('LC_partselector').style.display = 'none';
                    331:0):                     }
                    332:0):                 }
                    333:0):             }
                    334:0):         }
                    335:0):     }
                    336:0): }
                    337:0): END
                    338:0):     return &Apache::lonhtmlcommon::scripttag($js);
1.118     ng        339: }
                    340: 
1.434     albertel  341: sub reset_caches {
                    342:     &reset_analyze_cache();
                    343:     &reset_perm();
1.596.2.12.2.  (raeburn  344:):     &reset_old_essays();
1.434     albertel  345: }
                    346: 
                    347: {
                    348:     my %analyze_cache;
1.557     raeburn   349:     my %analyze_cache_formkeys;
1.148     albertel  350: 
1.434     albertel  351:     sub reset_analyze_cache {
                    352: 	undef(%analyze_cache);
1.557     raeburn   353:         undef(%analyze_cache_formkeys);
1.434     albertel  354:     }
                    355: 
                    356:     sub get_analyze {
1.596.2.12.2.  (raeburn  357:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  358: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   359:         if ($type eq 'randomizetry') {
                    360:             if ($trial ne '') {
                    361:                 $key .= "\0".$trial;
                    362:             }
                    363:         }
1.557     raeburn   364: 	if (exists($analyze_cache{$key})) {
                    365:             my $getupdate = 0;
                    366:             if (ref($add_to_hash) eq 'HASH') {
                    367:                 foreach my $item (keys(%{$add_to_hash})) {
                    368:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    369:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    370:                             $getupdate = 1;
                    371:                             last;
                    372:                         }
                    373:                     } else {
                    374:                         $getupdate = 1;
                    375:                     }
                    376:                 }
                    377:             }
                    378:             if (!$getupdate) {
                    379:                 return $analyze_cache{$key};
                    380:             }
                    381:         }
1.434     albertel  382: 
                    383: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    384: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   385:         my %form = ('grade_target'      => 'analyze',
                    386:                     'grade_domain'      => $udom,
                    387:                     'grade_symb'        => $symb,
                    388:                     'grade_courseid'    =>  $env{'request.course.id'},
                    389:                     'grade_username'    => $uname,
                    390:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  391:):         if ($bubbles_per_row ne '') {
                    392:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    393:):         }
1.596.2.2  raeburn   394:         if ($type eq 'randomizetry') {
                    395:             $form{'grade_questiontype'} = $type;
                    396:             if ($rndseed ne '') {
                    397:                 $form{'grade_rndseed'} = $rndseed;
                    398:             }
                    399:         }
1.557     raeburn   400:         if (ref($add_to_hash)) {
                    401:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   402:         }
1.557     raeburn   403: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  404: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   406:         if (ref($add_to_hash) eq 'HASH') {
                    407:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    408:         } else {
                    409:             $analyze_cache_formkeys{$key} = {};
                    410:         }
1.434     albertel  411: 	return $analyze_cache{$key} = \%analyze;
                    412:     }
                    413: 
                    414:     sub get_order {
1.596.2.2  raeburn   415: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    416: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  417: 	return $analyze->{"$partid.$respid.shown"};
                    418:     }
                    419: 
                    420:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   421: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    422: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    423:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   424:         if (ref($foils) eq 'ARRAY') {
                    425: 	    foreach my $foil (@{$foils}) {
                    426: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    427: 		    return $foil;
                    428: 	        }
1.434     albertel  429: 	    }
                    430: 	}
                    431:     }
1.554     raeburn   432: 
                    433:     sub scantron_partids_tograde {
1.596.2.12.2.  1(raebur  434:7):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   435:         my (%analysis,@parts);
                    436:         if (ref($resource)) {
                    437:             my $symb = $resource->symb();
1.557     raeburn   438:             my $add_to_form;
                    439:             if ($check_for_randomlist) {
                    440:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    441:             }
1.596.2.12.2.  1(raebur  442:7):             if ($scancode) {
                    443:7):                 if (ref($add_to_form) eq 'HASH') {
                    444:7):                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    445:7):                 } else {
                    446:7):                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    447:7):                 }
                    448:7):             }
          (raeburn  449:):             my $analyze =
                    450:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    451:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   452:             if (ref($analyze) eq 'HASH') {
                    453:                 %analysis = %{$analyze};
                    454:             }
                    455:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    456:                 foreach my $part (@{$analysis{'parts'}}) {
                    457:                     my ($id,$respid) = split(/\./,$part);
                    458:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    459:                         push(@parts,$part);
                    460:                     }
                    461:                 }
                    462:             }
                    463:         }
                    464:         return (\%analysis,\@parts);
                    465:     }
                    466: 
1.148     albertel  467: }
1.434     albertel  468: 
1.118     ng        469: #--- Clean response type for display
1.335     albertel  470: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    471: #        response types only.
1.118     ng        472: sub cleanRecord {
1.336     albertel  473:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   474: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  475:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  476:     if ($response =~ /^(option|rank)$/) {
                    477: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  478:4):         my @answer = %answer;
                    479:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  480: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    481: 	my ($toprow,$bottomrow);
                    482: 	foreach my $foil (@$order) {
                    483: 	    if ($grading{$foil} == 1) {
                    484: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    485: 	    } else {
                    486: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    487: 	    }
1.398     albertel  488: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  489: 	}
                    490: 	return '<blockquote><table border="1">'.
1.466     albertel  491: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    492: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   493: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  494:     } elsif ($response eq 'match') {
                    495: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  496:4):         my @answer = %answer;
                    497:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  498: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    499: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    500: 	my ($toprow,$middlerow,$bottomrow);
                    501: 	foreach my $foil (@$order) {
                    502: 	    my $item=shift(@items);
                    503: 	    if ($grading{$foil} == 1) {
                    504: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  505: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  506: 	    } else {
                    507: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  508: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  509: 	    }
1.398     albertel  510: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        511: 	}
1.126     ng        512: 	return '<blockquote><table border="1">'.
1.466     albertel  513: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    514: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  515: 	    $middlerow.'</tr>'.
1.466     albertel  516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   517: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  518:     } elsif ($response eq 'radiobutton') {
                    519: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  1(raebur  520:0):         my @answer = %answer;
                    521:0):         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  522: 	my ($toprow,$bottomrow);
1.434     albertel  523: 	my $correct = 
1.596.2.2  raeburn   524: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  525: 	foreach my $foil (@$order) {
1.148     albertel  526: 	    if (exists($answer{$foil})) {
1.434     albertel  527: 		if ($foil eq $correct) {
1.466     albertel  528: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  529: 		} else {
1.466     albertel  530: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  531: 		}
                    532: 	    } else {
1.466     albertel  533: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  534: 	    }
1.398     albertel  535: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  536: 	}
                    537: 	return '<blockquote><table border="1">'.
1.466     albertel  538: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    539: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   540: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  541:     } elsif ($response eq 'essay') {
1.257     albertel  542: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        543: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  544: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    545: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        546: 
1.257     albertel  547: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    548: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    549: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    550: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    551: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    552: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        553: 	}
1.596.2.12.2.  4(raebur  554:8):         $answer = &Apache::lontexconvert::msgtexconverted($answer);
          2(raebur  555:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  556:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  557:4):         my $result=&mt('Smile representation: [_1]',
                    558:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  559: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    560: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    561: 	return $result;
1.335     albertel  562:     } elsif ( $response eq 'Task') {
                    563: 	if ( $answer eq 'SUBMITTED') {
                    564: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  565: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  566: 	    return $result;
                    567: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    568: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    569: 			       keys(%{$record}));
                    570: 	    return join('<br />',($version,@matches));
                    571: 			       
                    572: 			       
                    573: 	} else {
                    574: 	    my $result =
                    575: 		'<p>'
                    576: 		.&mt('Overall result: [_1]',
                    577: 		     $record->{$version."resource.$respid.$partid.status"})
                    578: 		.'</p>';
                    579: 	    
                    580: 	    $result .= '<ul>';
                    581: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    582: 			     keys(%{$record}));
                    583: 	    foreach my $grade (sort(@grade)) {
                    584: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    585: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    586: 				     $dim, $record->{$grade}).
                    587: 			  '</li>';
                    588: 	    }
                    589: 	    $result.='</ul>';
                    590: 	    return $result;
                    591: 	}
1.596.2.12.2.  8(raebur  592:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
          0.2.4(ra  593:ul-23):         # Respect multiple input fields, see Bug #5409
1.440     albertel  594: 	$answer = 
                    595: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    596: 							      $answer);
1.596.2.12.2.  1(raebur  597:0): 	return $answer;
1.122     ng        598:     }
1.596.2.12.2.  8(raebur  599:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        600: }
                    601: 
                    602: #-- A couple of common js functions
                    603: sub commonJSfunctions {
                    604:     my $request = shift;
1.596.2.12.2.  1(raebur  605:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        606:     function radioSelection(radioButton) {
                    607: 	var selection=null;
                    608: 	if (radioButton.length > 1) {
                    609: 	    for (var i=0; i<radioButton.length; i++) {
                    610: 		if (radioButton[i].checked) {
                    611: 		    return radioButton[i].value;
                    612: 		}
                    613: 	    }
                    614: 	} else {
                    615: 	    if (radioButton.checked) return radioButton.value;
                    616: 	}
                    617: 	return selection;
                    618:     }
                    619: 
                    620:     function pullDownSelection(selectOne) {
                    621: 	var selection="";
                    622: 	if (selectOne.length > 1) {
                    623: 	    for (var i=0; i<selectOne.length; i++) {
                    624: 		if (selectOne[i].selected) {
                    625: 		    return selectOne[i].value;
                    626: 		}
                    627: 	    }
                    628: 	} else {
1.138     albertel  629:             // only one value it must be the selected one
                    630: 	    return selectOne.value;
1.118     ng        631: 	}
                    632:     }
                    633: COMMONJSFUNCTIONS
                    634: }
                    635: 
1.44      ng        636: #--- Dumps the class list with usernames,list of sections,
                    637: #--- section, ids and fullnames for each user.
                    638: sub getclasslist {
1.596.2.12.2.  1(raebur  639:0):     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  640:     my @getsec;
1.450     banghart  641:     my @getgroup;
1.442     banghart  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  643:     if (!ref($getsec)) {
                    644: 	if ($getsec ne '' && $getsec ne 'all') {
                    645: 	    @getsec=($getsec);
                    646: 	}
                    647:     } else {
                    648: 	@getsec=@{$getsec};
                    649:     }
                    650:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  651:     if (!ref($getgroup)) {
                    652: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    653: 	    @getgroup=($getgroup);
                    654: 	}
                    655:     } else {
                    656: 	@getgroup=@{$getgroup};
                    657:     }
                    658:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  659: 
1.449     banghart  660:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  661:     # Bail out if we were unable to get the classlist
1.56      matthew   662:     return if (! defined($classlist));
1.449     banghart  663:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   664:     #
                    665:     my %sections;
                    666:     my %fullnames;
1.596.2.12.2.  1(raebur  667:0):     my ($cdom,$cnum,$partlist);
                    668:0):     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    669:0):         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    670:0):         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    671:0):         my $res_error;
                    672:0):         ($partlist) = &response_type($symb,\$res_error);
                    673:0):     }
1.205     matthew   674:     foreach my $student (keys(%$classlist)) {
                    675:         my $end      = 
                    676:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    677:         my $start    = 
                    678:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    679:         my $id       = 
                    680:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    681:         my $section  = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    683:         my $fullname = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    685:         my $status   = 
                    686:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  687:         my $group   = 
                    688:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        689: 	# filter students according to status selected
1.596.2.12.2.  1(raebur  690:0): 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  691: 	    if (!($stu_status =~ $status)) {
1.450     banghart  692: 		delete($classlist->{$student});
1.76      ng        693: 		next;
                    694: 	    }
                    695: 	}
1.450     banghart  696: 	# filter students according to groups selected
1.453     banghart  697: 	my @stu_groups = split(/,/,$group);
1.450     banghart  698: 	if (@getgroup) {
                    699: 	    my $exclude = 1;
1.454     banghart  700: 	    foreach my $grp (@getgroup) {
                    701: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  702: 	            if ($stu_group eq $grp) {
                    703: 	                $exclude = 0;
                    704:     	            } 
1.450     banghart  705: 	        }
1.453     banghart  706:     	        if (($grp eq 'none') && !$group) {
1.596.2.12.2.  1(raebur  707:0):         	    $exclude = 0;
1.453     banghart  708:         	}
1.450     banghart  709: 	    }
                    710: 	    if ($exclude) {
                    711: 	        delete($classlist->{$student});
1.596.2.12.2.  1(raebur  712:0): 		next;
1.450     banghart  713: 	    }
                    714: 	}
1.596.2.12.2.  1(raebur  715:0):         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    716:0):             my $udom =
                    717:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    718:0):             my $uname =
                    719:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    720:0):             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    721:0):                 if ($submitonly eq 'queued') {
                    722:0):                     my %queue_status =
                    723:0):                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    724:0):                                                                 $udom,$uname);
                    725:0):                     if (!defined($queue_status{'gradingqueue'})) {
                    726:0):                         delete($classlist->{$student});
                    727:0):                         next;
                    728:0):                     }
                    729:0):                 } else {
                    730:0):                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    731:0):                     my $submitted = 0;
                    732:0):                     my $graded = 0;
                    733:0):                     my $incorrect = 0;
                    734:0):                     foreach (keys(%status)) {
                    735:0):                         $submitted = 1 if ($status{$_} ne 'nothing');
                    736:0):                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    737:0):                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    738:0): 
                    739:0):                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    740:0):                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    741:0):                             $submitted = 0;
                    742:0):                         }
                    743:0):                     }
                    744:0):                     if (!$submitted && ($submitonly eq 'yes' ||
                    745:0):                                         $submitonly eq 'incorrect' ||
                    746:0):                                         $submitonly eq 'graded')) {
                    747:0):                         delete($classlist->{$student});
                    748:0):                         next;
                    749:0):                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    750:0):                         delete($classlist->{$student});
                    751:0):                         next;
                    752:0):                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    753:0):                         delete($classlist->{$student});
                    754:0):                         next;
                    755:0):                     }
                    756:0):                 }
                    757:0):             }
                    758:0):         }
1.205     matthew   759: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  760: 	if (&canview($section)) {
1.291     albertel  761: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  762: 		$sections{$section}++;
1.450     banghart  763: 		if ($classlist->{$student}) {
                    764: 		    $fullnames{$student}=$fullname;
                    765: 		}
1.103     albertel  766: 	    } else {
1.205     matthew   767: 		delete($classlist->{$student});
1.103     albertel  768: 	    }
                    769: 	} else {
1.205     matthew   770: 	    delete($classlist->{$student});
1.103     albertel  771: 	}
1.44      ng        772:     }
1.56      matthew   773:     my @sections = sort(keys(%sections));
                    774:     return ($classlist,\@sections,\%fullnames);
1.44      ng        775: }
                    776: 
1.103     albertel  777: sub canmodify {
                    778:     my ($sec)=@_;
                    779:     if ($perm{'mgr'}) {
                    780: 	if (!defined($perm{'mgr_section'})) {
                    781: 	    # can modify whole class
                    782: 	    return 1;
                    783: 	} else {
                    784: 	    if ($sec eq $perm{'mgr_section'}) {
                    785: 		#can modify the requested section
                    786: 		return 1;
                    787: 	    } else {
1.596.2.12.2.  1(raebur  788:0): 		# can't modify the requested section
1.103     albertel  789: 		return 0;
                    790: 	    }
                    791: 	}
                    792:     }
                    793:     #can't modify
                    794:     return 0;
                    795: }
                    796: 
                    797: sub canview {
                    798:     my ($sec)=@_;
                    799:     if ($perm{'vgr'}) {
                    800: 	if (!defined($perm{'vgr_section'})) {
1.596.2.12.2.  1(raebur  801:0): 	    # can view whole class
1.103     albertel  802: 	    return 1;
                    803: 	} else {
                    804: 	    if ($sec eq $perm{'vgr_section'}) {
1.596.2.12.2.  1(raebur  805:0): 		#can view the requested section
1.103     albertel  806: 		return 1;
                    807: 	    } else {
1.596.2.12.2.  1(raebur  808:0): 		# can't view the requested section
1.103     albertel  809: 		return 0;
                    810: 	    }
                    811: 	}
                    812:     }
1.596.2.12.2.  1(raebur  813:0):     #can't view
1.103     albertel  814:     return 0;
                    815: }
                    816: 
1.44      ng        817: #--- Retrieve the grade status of a student for all the parts
                    818: sub student_gradeStatus {
1.324     albertel  819:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  820:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        821:     my %partstatus = ();
                    822:     foreach (@$partlist) {
1.128     ng        823: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        824: 	$status              = 'nothing' if ($status eq '');
                    825: 	$partstatus{$_}      = $status;
                    826: 	my $subkey           = "resource.$_.submitted_by";
                    827: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    828:     }
                    829:     return %partstatus;
                    830: }
                    831: 
1.45      ng        832: # hidden form and javascript that calls the form
                    833: # Use by verifyscript and viewgrades
                    834: # Shows a student's view of problem and submission
                    835: sub jscriptNform {
1.324     albertel  836:     my ($symb) = @_;
1.442     banghart  837:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  1(raebur  838:0):     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        839: 	'    function viewOneStudent(user,domain) {'."\n".
                    840: 	'	document.onestudent.student.value = user;'."\n".
                    841: 	'	document.onestudent.userdom.value = domain;'."\n".
                    842: 	'	document.onestudent.submit();'."\n".
                    843: 	'    }'."\n".
1.596.2.12.2.  1(raebur  844:0): 	"\n");
1.45      ng        845:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  846: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  847: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        848: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    849: 	'<input type="hidden" name="student" value="" />'."\n".
                    850: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    851: 	'</form>'."\n";
                    852:     return $jscript;
                    853: }
1.39      ng        854: 
1.447     foxr      855: 
                    856: 
1.315     bowersj2  857: # Given the score (as a number [0-1] and the weight) what is the final
                    858: # point value? This function will round to the nearest tenth, third,
                    859: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  860: sub compute_points {
1.315     bowersj2  861:     my ($score, $weight) = @_;
                    862:     
                    863:     my $tolerance = .00001;
                    864:     my $points = $score * $weight;
                    865: 
                    866:     # Check for nearness to 1/x.
                    867:     my $check_for_nearness = sub {
                    868:         my ($factor) = @_;
                    869:         my $num = ($points * $factor) + $tolerance;
                    870:         my $floored_num = floor($num);
1.316     albertel  871:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  872:             return $floored_num / $factor;
                    873:         }
                    874:         return $points;
                    875:     };
                    876: 
                    877:     $points = $check_for_nearness->(10);
                    878:     $points = $check_for_nearness->(3);
                    879:     $points = $check_for_nearness->(4);
                    880:     
                    881:     return $points;
                    882: }
                    883: 
1.44      ng        884: #------------------ End of general use routines --------------------
1.87      www       885: 
                    886: #
                    887: # Find most similar essay
                    888: #
                    889: 
                    890: sub most_similar {
1.596.2.12.2.  (raeburn  891:):     my ($uname,$udom,$symb,$uessay)=@_;
                    892:): 
                    893:):     unless ($symb) { return ''; }
                    894:): 
                    895:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       896: 
                    897: # ignore spaces and punctuation
                    898: 
                    899:     $uessay=~s/\W+/ /gs;
                    900: 
1.282     www       901: # ignore empty submissions (occuring when only files are sent)
                    902: 
1.596.2.4  raeburn   903:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       904: 
1.87      www       905: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       906:     my $limit=0.6;
1.87      www       907:     my $sname='';
                    908:     my $sdom='';
                    909:     my $scrsid='';
                    910:     my $sessay='';
                    911: # go through all essays ...
1.596.2.12.2.  (raeburn  912:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  913: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       914: # ... except the same student
1.426     albertel  915:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  916:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  917: 	$tessay=~s/\W+/ /gs;
1.87      www       918: # String similarity gives up if not even limit
1.426     albertel  919: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       920: # Found one
1.426     albertel  921: 	if ($tsimilar>$limit) {
                    922: 	    $limit=$tsimilar;
                    923: 	    $sname=$tname;
                    924: 	    $sdom=$tdom;
                    925: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  926:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  927: 	}
1.87      www       928:     }
1.88      www       929:     if ($limit>0.6) {
1.87      www       930:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    931:     } else {
                    932:        return ('','','','',0);
                    933:     }
                    934: }
                    935: 
1.44      ng        936: #-------------------------------------------------------------------
                    937: 
                    938: #------------------------------------ Receipt Verification Routines
1.45      ng        939: #
1.596.2.12.2.  1(raebur  940:0): 
                    941:0): sub initialverifyreceipt {
                    942:0):    my ($request,$symb) = @_;
                    943:0):    &commonJSfunctions($request);
                    944:0):    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
                    945:0):         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    946:0):         '-<input type="text" name="receipt" size="4" />'.
                    947:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    948:0):         '<input type="hidden" name="command" value="verify" />'.
                    949:0):         "</form>\n";
                    950:0): }
                    951:0): 
1.44      ng        952: #--- Check whether a receipt number is valid.---
                    953: sub verifyreceipt {
1.596.2.12.2.  1(raebur  954:0):     my ($request,$symb) = @_;
1.44      ng        955: 
1.257     albertel  956:     my $courseid = $env{'request.course.id'};
1.184     www       957:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  958: 	$env{'form.receipt'};
1.44      ng        959:     $receipt     =~ s/[^\-\d]//g;
                    960: 
1.596.2.12.2.  1(raebur  961:0):     my $title =
1.487     albertel  962: 	'<h3><span class="LC_info">'.
1.596.2.12.2.  1(raebur  963:0): 	&mt('Verifying Receipt Number [_1]',$receipt).
                    964:0): 	'</span></h3>'."\n";
1.44      ng        965: 
                    966:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   967:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  968:     
                    969:     my $receiptparts=0;
1.390     albertel  970:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    971: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  972:     my $parts=['0'];
1.582     raeburn   973:     if ($receiptparts) {
                    974:         my $res_error; 
                    975:         ($parts)=&response_type($symb,\$res_error);
                    976:         if ($res_error) {
                    977:             return &navmap_errormsg();
                    978:         } 
                    979:     }
1.486     albertel  980:     
                    981:     my $header = 
                    982: 	&Apache::loncommon::start_data_table().
                    983: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  984: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    985: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    986: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  987:     if ($receiptparts) {
1.487     albertel  988: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  989:     }
                    990:     $header.=
                    991: 	&Apache::loncommon::end_data_table_header_row();
                    992: 
1.294     albertel  993:     foreach (sort 
                    994: 	     {
                    995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    997: 		 }
                    998: 		 return $a cmp $b;
                    999: 	     } (keys(%$fullname))) {
1.44      ng       1000: 	my ($uname,$udom)=split(/\:/);
1.177     albertel 1001: 	foreach my $part (@$parts) {
                   1002: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel 1003: 		$contents.=
                   1004: 		    &Apache::loncommon::start_data_table_row().
                   1005: 		    '<td>&nbsp;'."\n".
1.177     albertel 1006: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1007: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1008: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1009: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1010: 		if ($receiptparts) {
                   1011: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1012: 		}
1.486     albertel 1013: 		$contents.= 
                   1014: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1015: 		
                   1016: 		$matches++;
                   1017: 	    }
1.44      ng       1018: 	}
                   1019:     }
                   1020:     if ($matches == 0) {
1.584     bisitz   1021:         $string = $title
                   1022:                  .'<p class="LC_warning">'
                   1023:                  .&mt('No match found for the above receipt number.')
                   1024:                  .'</p>';
1.44      ng       1025:     } else {
1.324     albertel 1026: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1027: 	    '<p>'.
1.584     bisitz   1028: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1029: 	    '</p>'.
1.486     albertel 1030: 	    $header.
                   1031: 	    $contents.
                   1032: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1033:     }
1.596.2.12.2.  1(raebur 1034:0):     return $string;
1.44      ng       1035: }
                   1036: 
                   1037: #--- This is called by a number of programs.
                   1038: #--- Called from the Grading Menu - View/Grade an individual student
                   1039: #--- Also called directly when one clicks on the subm button 
                   1040: #    on the problem page.
1.30      ng       1041: sub listStudents {
1.596.2.12.2.  1(raebur 1042:0):     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1043: 
1.596.2.12.2.  0.2.4(ra 1044:ul-23):     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1045:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1046:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1047:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1048:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.596.2.12.2.  1(raebur 1049:0):     unless ($submitonly) {
                   1050:0):         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   1051:0):     }
                   1052:0): 
                   1053:0):     my $result='';
                   1054:0):     my $res_error;
                   1055:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
1.118     ng       1056: 
1.596.2.12.2.  1(raebur 1057:0):     my $table;
                   1058:0):     if (ref($partlist) eq 'ARRAY') {
                   1059:0):         if (scalar(@$partlist) > 1 ) {
                   1060:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1061:0):         } elsif ($divforres) {
                   1062:0):             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1063:0):         } else {
                   1064:0):             $table = '<br clear="all" />';
                   1065:0):         }
                   1066:0):     }
1.49      albertel 1067: 
1.596.2.12.2.  6(raebur 1068:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1069: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1070: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1071: 	     );
1.596.2.12.2.  6(raebur 1072:6):     &js_escape(\%js_lt);
          1(raebur 1073:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1074:     function checkSelect(checkBox) {
                   1075: 	var ctr=0;
                   1076: 	var sense="";
                   1077: 	if (checkBox.length > 1) {
                   1078: 	    for (var i=0; i<checkBox.length; i++) {
                   1079: 		if (checkBox[i].checked) {
                   1080: 		    ctr++;
                   1081: 		}
                   1082: 	    }
1.596.2.12.2.  6(raebur 1083:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng       1084: 	} else {
                   1085: 	    if (checkBox.checked) {
                   1086: 		ctr = 1;
                   1087: 	    }
1.596.2.12.2.  6(raebur 1088:6): 	    sense = '$js_lt{'single'}';
1.110     ng       1089: 	}
                   1090: 	if (ctr == 0) {
1.485     albertel 1091: 	    alert(sense);
1.110     ng       1092: 	    return false;
                   1093: 	}
                   1094: 	document.gradesub.submit();
                   1095:     }
                   1096: 
                   1097:     function reLoadList(formname) {
1.112     ng       1098: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1099: 	formname.command.value = 'submission';
                   1100: 	formname.submit();
                   1101:     }
1.45      ng       1102: LISTJAVASCRIPT
                   1103: 
1.118     ng       1104:     &commonJSfunctions($request);
1.41      ng       1105:     $request->print($result);
1.39      ng       1106: 
1.154     albertel 1107:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel 1108: 	"\n".$table;
1.596.2.12.2.  1(raebur 1109:0): 
1.561     bisitz   1110:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.596.2.12.2.  0.2.4(ra 1111:ul-23):     unless ($is_tool) {
                   1112:ul-23):         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1113:ul-23):                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1114:ul-23):                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1115:ul-23):                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1116:ul-23):                       .&Apache::lonhtmlcommon::row_closure();
                   1117:ul-23):         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1118:ul-23):                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1119:ul-23):                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1120:ul-23):                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1121:ul-23):                       .&Apache::lonhtmlcommon::row_closure();
                   1122:ul-23):     }
1.485     albertel 1123: 
1.442     banghart 1124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1125:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1126:     $env{'form.Status'} = $saveStatus;
1.596.2.12.2.  0.2.4(ra 1127:ul-23):     my %optiontext;
                   1128:ul-23):     if ($is_tool) {
                   1129:ul-23):         %optiontext = &Apache::lonlocal::texthash (
                   1130:ul-23):                           lastonly => 'last transaction',
                   1131:ul-23):                           last     => 'last transaction with details',
                   1132:ul-23):                           datesub  => 'all transactions',
                   1133:ul-23):                           all      => 'all transactions with details',
                   1134:ul-23):                       );
                   1135:ul-23):     } else {
                   1136:ul-23):         %optiontext = &Apache::lonlocal::texthash (
          1(raebur 1137:0):                           lastonly => 'last submission',
                   1138:0):                           last     => 'last submission with details',
                   1139:0):                           datesub  => 'all submissions',
                   1140:0):                           all      => 'all submissions with details',
                   1141:0):                       );
          0.2.4(ra 1142:ul-23):     }
          1(raebur 1143:0):     my $submission_options =
1.592     bisitz   1144:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1145:0):         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
                   1146:0):         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1147:         '<span class="LC_nobreak">'.
                   1148:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.596.2.12.2.  1(raebur 1149:0):         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1150:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1151:0):         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
                   1152:0):         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1153:         '<span class="LC_nobreak">'.
                   1154:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.596.2.12.2.  1(raebur 1155:0):         $optiontext{'all'}.'</label></span>';
          0.2.4(ra 1156:ul-23):     my $viewtitle;
                   1157:ul-23):     if ($is_tool) {
                   1158:ul-23):         $viewtitle = &mt('View Transactions');
                   1159:ul-23):     } else {
                   1160:ul-23):         $viewtitle = &mt('View Submissions');
                   1161:ul-23):     }
          1(raebur 1162:0):     my ($compmsg,$nocompmsg);
                   1163:0):     $nocompmsg = ' checked="checked"';
                   1164:0):     if ($numessay) {
                   1165:0):         $compmsg = $nocompmsg;
                   1166:0):         $nocompmsg = '';
                   1167:0):     }
          0.2.4(ra 1168:ul-23):     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
          6(raebur 1169:1):                   .$submission_options;
                   1170:1): # Check if any gradable
                   1171:1):     my $showmore;
                   1172:1):     if ($perm{'mgr'}) {
                   1173:1):         my @sections;
                   1174:1):         if ($env{'request.course.sec'} ne '') {
                   1175:1):             @sections = ($env{'request.course.sec'});
          7(raebur 1176:1):         } elsif ($env{'form.section'} eq '') {
                   1177:1):             @sections = ('all');
          6(raebur 1178:1):         } else {
                   1179:1):             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1180:1):         }
                   1181:1):         if (grep(/^all$/,@sections)) {
                   1182:1):             $showmore = 1;
                   1183:1):         } else {
                   1184:1):             foreach my $sec (@sections) {
                   1185:1):                 if (&canmodify($sec)) {
                   1186:1):                     $showmore = 1;
                   1187:1):                     last;
                   1188:1):                 }
                   1189:1):             }
                   1190:1):         }
                   1191:1):     }
                   1192:1): 
                   1193:1):     if ($showmore) {
                   1194:1):         $gradeTable .=
                   1195:1):                    &Apache::lonhtmlcommon::row_closure()
          1(raebur 1196:0):                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1197:0):                   .'<span class="LC_nobreak">'
                   1198:0):                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1199:0):                   .&mt('No').('&nbsp;'x2).'</label>'
                   1200:0):                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1201:0):                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1202:                   .&Apache::lonhtmlcommon::row_closure();
                   1203: 
1.596.2.12.2.  6(raebur 1204:1):         $gradeTable .= 
                   1205:1):                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1206:                   .'<select name="increment">'
                   1207:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1208:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1209:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1210:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.596.2.12.2.  1(raebur 1211:0):                   .'</select>';
          6(raebur 1212:1):     }
1.485     albertel 1213:     $gradeTable .= 
1.432     banghart 1214:         &build_section_inputs().
1.45      ng       1215: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1216: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1217: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.596.2.12.2.  1(raebur 1218:0):     if (exists($env{'form.Status'})) {
          7(raebur 1219:1): 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       1220:     } else {
1.596.2.12.2.  1(raebur 1221:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1222:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1223:                       .&Apache::lonhtmlcommon::StatusOptions(
1.596.2.12.2.  1(raebur 1224:0):                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1225:     }
1.596.2.12.2.  1(raebur 1226:0):     if ($numessay) {
                   1227:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1228:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1229:0):                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
                   1230:0):     }
                   1231:0):     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
1.561     bisitz   1232:                   .&Apache::lonhtmlcommon::end_pick_box();
1.596.2.12.2.  0.2.4(ra 1233:ul-23):     my $regrademsg;
                   1234:ul-23):     if ($is_tool) {
                   1235:ul-23):         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   1236:ul-23):     } else {
                   1237:ul-23):         $regrademsg = &mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   1238:ul-23):     }
1.561     bisitz   1239:     $gradeTable .= '<p>'
1.596.2.12.2.  0.2.4(ra 1240:ul-23):                   .$regrademsg."\n"
1.561     bisitz   1241:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1242:                   .'</p>';
1.249     albertel 1243: 
                   1244: # checkall buttons
                   1245:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1246:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1247:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1248:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1249:     $gradeTable.=&check_buttons();
1.450     banghart 1250:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1251:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1252: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1253:     my $loop = 0;
                   1254:     while ($loop < 2) {
1.485     albertel 1255: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1256: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.596.2.12.2.  1(raebur 1257:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1258: 	    foreach my $part (sort(@$partlist)) {
                   1259: 		my $display_part=
                   1260: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1261: 		$gradeTable.=
                   1262: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1263: 	    }
1.301     albertel 1264: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1265: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1266: 	}
                   1267: 	$loop++;
1.126     ng       1268: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1269:     }
1.474     albertel 1270:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1271: 
1.45      ng       1272:     my $ctr = 0;
1.294     albertel 1273:     foreach my $student (sort 
                   1274: 			 {
                   1275: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1276: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1277: 			     }
                   1278: 			     return $a cmp $b;
                   1279: 			 }
                   1280: 			 (keys(%$fullname))) {
1.41      ng       1281: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1282: 
1.110     ng       1283: 	my %status = ();
1.301     albertel 1284: 
                   1285: 	if ($submitonly eq 'queued') {
                   1286: 	    my %queue_status = 
                   1287: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1288: 							$udom,$uname);
                   1289: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1290: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1291: 	}
                   1292: 
1.596.2.12.2.  1(raebur 1293:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1294: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1295: 	    my $submitted = 0;
1.164     albertel 1296: 	    my $graded = 0;
1.248     albertel 1297: 	    my $incorrect = 0;
1.110     ng       1298: 	    foreach (keys(%status)) {
1.145     albertel 1299: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1300: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1301: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1302: 		
1.110     ng       1303: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1304: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1305: 		    $submitted = 0;
1.150     albertel 1306: 		    my ($part)=split(/\./,$partid);
1.110     ng       1307: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1308: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1309: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1310: 		}
1.41      ng       1311: 	    }
1.248     albertel 1312: 	    
1.156     albertel 1313: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1314: 				     $submitonly eq 'incorrect' ||
                   1315: 				     $submitonly eq 'graded'));
1.248     albertel 1316: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1317: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1318: 	}
1.34      ng       1319: 
1.45      ng       1320: 	$ctr++;
1.249     albertel 1321: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1322:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1323: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1324: 	    if ($ctr%2 ==1) {
                   1325: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1326: 	    }
1.126     ng       1327: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1328:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1329:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1330: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1331: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1332: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1333: 
1.596.2.12.2.  1(raebur 1334:0): 	    if ($submitonly ne 'all') {
1.524     raeburn  1335: 		foreach (sort(keys(%status))) {
1.485     albertel 1336: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1337: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1338: 		}
1.41      ng       1339: 	    }
1.126     ng       1340: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1341: 	    if ($ctr%2 ==0) {
                   1342: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1343: 	    }
1.41      ng       1344: 	}
                   1345:     }
1.110     ng       1346:     if ($ctr%2 ==1) {
1.126     ng       1347: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.596.2.12.2.  1(raebur 1348:0): 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1349: 		foreach (@$partlist) {
                   1350: 		    $gradeTable.='<td>&nbsp;</td>';
                   1351: 		}
1.301     albertel 1352: 	    } elsif ($submitonly eq 'queued') {
                   1353: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1354: 	    }
1.474     albertel 1355: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1356:     }
                   1357: 
1.474     albertel 1358:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1359:         '<input type="button" '.
                   1360:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1361:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1362:     if ($ctr == 0) {
1.96      albertel 1363: 	my $num_students=(scalar(keys(%$fullname)));
                   1364: 	if ($num_students eq 0) {
1.485     albertel 1365: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1366: 	} else {
1.171     albertel 1367: 	    my $submissions='submissions';
                   1368: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1369: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1370: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1371: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1372:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1373: 		    $num_students).
                   1374: 		'</span><br />';
1.96      albertel 1375: 	}
1.46      ng       1376:     } elsif ($ctr == 1) {
1.474     albertel 1377: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1378:     }
                   1379:     $request->print($gradeTable);
1.44      ng       1380:     return '';
1.10      ng       1381: }
                   1382: 
1.44      ng       1383: #---- Called from the listStudents routine
1.249     albertel 1384: 
                   1385: sub check_script {
1.596.2.12.2.  1(raebur 1386:0):     my ($form,$type) = @_;
                   1387:0):     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1388:     function checkall() {
                   1389:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1390:             ele = document.forms.'.$form.'.elements[i];
                   1391:             if (ele.name == "'.$type.'") {
                   1392:             document.forms.'.$form.'.elements[i].checked=true;
                   1393:                                        }
                   1394:         }
                   1395:     }
                   1396: 
                   1397:     function checksec() {
                   1398:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1399:             ele = document.forms.'.$form.'.elements[i];
                   1400:            string = document.forms.'.$form.'.chksec.value;
                   1401:            if
                   1402:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1403:               document.forms.'.$form.'.elements[i].checked=true;
                   1404:             }
                   1405:         }
                   1406:     }
                   1407: 
                   1408: 
                   1409:     function uncheckall() {
                   1410:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1411:             ele = document.forms.'.$form.'.elements[i];
                   1412:             if (ele.name == "'.$type.'") {
                   1413:             document.forms.'.$form.'.elements[i].checked=false;
                   1414:                                        }
                   1415:         }
                   1416:     }
                   1417: 
1.596.2.12.2.  1(raebur 1418:0): '."\n");
1.249     albertel 1419:     return $chkallscript;
                   1420: }
                   1421: 
                   1422: sub check_buttons {
1.485     albertel 1423:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1424:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1425:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1426:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1427:     return $buttons;
                   1428: }
                   1429: 
1.44      ng       1430: #     Displays the submissions for one student or a group of students
1.34      ng       1431: sub processGroup {
1.596.2.12.2.  1(raebur 1432:0):     my ($request,$symb) = @_;
1.41      ng       1433:     my $ctr        = 0;
1.155     albertel 1434:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1435:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1436: 
1.396     banghart 1437:     foreach my $student (@stuchecked) {
                   1438: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1439: 	$env{'form.student'}        = $uname;
                   1440: 	$env{'form.userdom'}        = $udom;
                   1441: 	$env{'form.fullname'}       = $fullname;
1.596.2.12.2.  1(raebur 1442:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       1443: 	$ctr++;
                   1444:     }
                   1445:     return '';
1.35      ng       1446: }
1.34      ng       1447: 
1.44      ng       1448: #------------------------------------------------------------------------------------
                   1449: #
                   1450: #-------------------------- Next few routines handles grading by student, essentially
                   1451: #                           handles essay response type problem/part
                   1452: #
                   1453: #--- Javascript to handle the submission page functionality ---
                   1454: sub sub_page_js {
                   1455:     my $request = shift;
1.596.2.12.2.  6(raebur 1456:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1457:6):     &js_escape(\$alertmsg);
          1(raebur 1458:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1459:     function updateRadio(formname,id,weight) {
1.125     ng       1460: 	var gradeBox = formname["GD_BOX"+id];
                   1461: 	var radioButton = formname["RADVAL"+id];
                   1462: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1463: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1464: 	gradeBox.value = pts;
                   1465: 	var resetbox = false;
                   1466: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1467: 	    alert("$alertmsg"+pts);
1.71      ng       1468: 	    for (var i=0; i<radioButton.length; i++) {
                   1469: 		if (radioButton[i].checked) {
                   1470: 		    gradeBox.value = i;
                   1471: 		    resetbox = true;
                   1472: 		}
                   1473: 	    }
                   1474: 	    if (!resetbox) {
                   1475: 		formtextbox.value = "";
                   1476: 	    }
                   1477: 	    return;
1.44      ng       1478: 	}
1.71      ng       1479: 
                   1480: 	if (pts > weight) {
                   1481: 	    var resp = confirm("You entered a value ("+pts+
                   1482: 			       ") greater than the weight for the part. Accept?");
                   1483: 	    if (resp == false) {
1.125     ng       1484: 		gradeBox.value = oldpts;
1.71      ng       1485: 		return;
                   1486: 	    }
1.44      ng       1487: 	}
1.13      albertel 1488: 
1.71      ng       1489: 	for (var i=0; i<radioButton.length; i++) {
                   1490: 	    radioButton[i].checked=false;
                   1491: 	    if (pts == i && pts != "") {
                   1492: 		radioButton[i].checked=true;
                   1493: 	    }
                   1494: 	}
                   1495: 	updateSelect(formname,id);
1.125     ng       1496: 	formname["stores"+id].value = "0";
1.41      ng       1497:     }
1.5       albertel 1498: 
1.72      ng       1499:     function writeBox(formname,id,pts) {
1.125     ng       1500: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1501: 	if (checkSolved(formname,id) == 'update') {
                   1502: 	    gradeBox.value = pts;
                   1503: 	} else {
1.125     ng       1504: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1505: 	    gradeBox.value = oldpts;
1.125     ng       1506: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1507: 	    for (var i=0; i<radioButton.length; i++) {
                   1508: 		radioButton[i].checked=false;
1.72      ng       1509: 		if (i == oldpts) {
1.71      ng       1510: 		    radioButton[i].checked=true;
                   1511: 		}
                   1512: 	    }
1.41      ng       1513: 	}
1.125     ng       1514: 	formname["stores"+id].value = "0";
1.71      ng       1515: 	updateSelect(formname,id);
                   1516: 	return;
1.41      ng       1517:     }
1.44      ng       1518: 
1.71      ng       1519:     function clearRadBox(formname,id) {
                   1520: 	if (checkSolved(formname,id) == 'noupdate') {
                   1521: 	    updateSelect(formname,id);
                   1522: 	    return;
                   1523: 	}
1.125     ng       1524: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1525: 	for (var i=0; i<gradeSelect.length; i++) {
                   1526: 	    if (gradeSelect[i].selected) {
                   1527: 		var selectx=i;
                   1528: 	    }
                   1529: 	}
1.125     ng       1530: 	var stores = formname["stores"+id];
1.71      ng       1531: 	if (selectx == stores.value) { return };
1.125     ng       1532: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1533: 	gradeBox.value = "";
1.125     ng       1534: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1535: 	for (var i=0; i<radioButton.length; i++) {
                   1536: 	    radioButton[i].checked=false;
                   1537: 	}
                   1538: 	stores.value = selectx;
                   1539:     }
1.5       albertel 1540: 
1.71      ng       1541:     function checkSolved(formname,id) {
1.125     ng       1542: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1543: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1544: 	    if (!reply) {return "noupdate";}
1.120     ng       1545: 	    formname.overRideScore.value = 'yes';
1.41      ng       1546: 	}
1.71      ng       1547: 	return "update";
1.13      albertel 1548:     }
1.71      ng       1549: 
                   1550:     function updateSelect(formname,id) {
1.125     ng       1551: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1552: 	return;
1.41      ng       1553:     }
1.33      ng       1554: 
1.121     ng       1555: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1556:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1557: 	formname.gradeOpt.value = val;
1.71      ng       1558: 	if (val == "Save & Next") {
                   1559: 	    for (i=0;i<=total;i++) {
                   1560: 		for (j=0;j<parttot;j++) {
1.125     ng       1561: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1562: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1563: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1564: 			if (points == "") {
1.125     ng       1565: 			    var name = formname["name"+i].value;
1.129     ng       1566: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1567: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1568: 					       ", part "+partid+". Continue?");
1.71      ng       1569: 			    if (resp == false) {
1.125     ng       1570: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1571: 				return false;
                   1572: 			    }
                   1573: 			}
                   1574: 		    }
                   1575: 		}
                   1576: 	    }
                   1577: 	}
1.120     ng       1578: 	formname.submit();
                   1579:     }
                   1580: 
1.71      ng       1581: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1582:     function checkSubmitPage(formname,total) {
                   1583: 	noscore = new Array(100);
                   1584: 	var ptr = 0;
                   1585: 	for (i=1;i<total;i++) {
1.125     ng       1586: 	    var partid = formname["q_"+i].value;
1.127     ng       1587: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1588: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1589: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1590: 		if (points == "" && status != "correct_by_student") {
                   1591: 		    noscore[ptr] = i;
                   1592: 		    ptr++;
                   1593: 		}
                   1594: 	    }
                   1595: 	}
                   1596: 	if (ptr != 0) {
                   1597: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1598: 	    var prolist = "";
                   1599: 	    if (ptr == 1) {
                   1600: 		prolist = noscore[0];
                   1601: 	    } else {
                   1602: 		var i = 0;
                   1603: 		while (i < ptr-1) {
                   1604: 		    prolist += noscore[i]+", ";
                   1605: 		    i++;
                   1606: 		}
                   1607: 		prolist += "and "+noscore[i];
                   1608: 	    }
                   1609: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1610: 	    if (resp == false) {
                   1611: 		return false;
                   1612: 	    }
                   1613: 	}
1.45      ng       1614: 
1.71      ng       1615: 	formname.submit();
                   1616:     }
                   1617: SUBJAVASCRIPT
                   1618: }
1.45      ng       1619: 
1.596.2.12.2.  1(raebur 1620:0): #--- javascript for grading message center
                   1621:0): sub sub_grademessage_js {
1.71      ng       1622:     my $request = shift;
1.80      ng       1623:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1624:     &commonJSfunctions($request);
1.350     albertel 1625: 
1.596.2.12.2.  1(raebur 1626:0):     my $inner_js_msg_central= (<<INNERJS);
                   1627:0): <script type="text/javascript">
1.350     albertel 1628:     function checkInput() {
                   1629:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1630:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1631:       var usrctr = document.msgcenter.usrctr.value;
                   1632:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1633:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1634: 
                   1635:       var msgchk = "";
                   1636:       if (document.msgcenter.subchk.checked) {
                   1637:          msgchk = "msgsub,";
                   1638:       }
                   1639:       var includemsg = 0;
                   1640:       for (var i=1; i<=nmsg; i++) {
                   1641:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1642:           var frmmsg = document.msgcenter["msg"+i];
                   1643:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1644:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1645:           showflg.value = "1";
                   1646:           var chkbox = document.msgcenter["msgn"+i];
                   1647:           if (chkbox.checked) {
                   1648:              msgchk += "savemsg"+i+",";
                   1649:              includemsg = 1;
                   1650:           }
                   1651:       }
                   1652:       if (document.msgcenter.newmsgchk.checked) {
                   1653:          msgchk += "newmsg"+usrctr;
                   1654:          includemsg = 1;
                   1655:       }
                   1656:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1657:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1658:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1659:       includemsg.value = msgchk;
                   1660: 
                   1661:       self.close()
                   1662: 
                   1663:     }
1.351     albertel 1664: </script>
                   1665: INNERJS
                   1666: 
1.596.2.12.2.  1(raebur 1667:0):     my $start_page_msg_central =
1.351     albertel 1668:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1669: 				       {'js_ready'  => 1,
                   1670: 					'only_body' => 1,
                   1671: 					'bgcolor'   =>'#FFFFFF',});
1.596.2.12.2.  1(raebur 1672:0):     my $end_page_msg_central =
1.351     albertel 1673: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1674: 
1.219     www      1675:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1676:     $docopen=~s/^document\.//;
1.596.2.12.2.  1(raebur 1677:0): 
          6(raebur 1678:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1679:                 comp => 'Compose Message for: ',
                   1680:                 incl => 'Include',
                   1681:                 type => 'Type',
                   1682:                 subj => 'Subject',
                   1683:                 mesa => 'Message',
                   1684:                 new  => 'New',
                   1685:                 save => 'Save',
                   1686:                 canc => 'Cancel',
                   1687:              );
1.596.2.12.2.  6(raebur 1688:6):     &html_escape(\%html_js_lt);
                   1689:6):     &js_escape(\%html_js_lt);
          1(raebur 1690:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.44      ng       1691: 
                   1692: //===================== Script to view submitted by ==================
                   1693:   function viewSubmitter(submitter) {
                   1694:     document.SCORE.refresh.value = "on";
                   1695:     document.SCORE.NCT.value = "1";
                   1696:     document.SCORE.unamedom0.value = submitter;
                   1697:     document.SCORE.submit();
                   1698:     return;
                   1699:   }
                   1700: 
                   1701: //====================== Script for composing message ==============
1.80      ng       1702:    // preload images
                   1703:    img1 = new Image();
                   1704:    img1.src = "$iconpath/mailbkgrd.gif";
                   1705:    img2 = new Image();
                   1706:    img2.src = "$iconpath/mailto.gif";
                   1707: 
1.44      ng       1708:   function msgCenter(msgform,usrctr,fullname) {
                   1709:     var Nmsg  = msgform.savemsgN.value;
                   1710:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1711:     var subject = msgform.msgsub.value;
1.127     ng       1712:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1713:     re = /msgsub/;
                   1714:     var shwsel = "";
                   1715:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1716:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1717:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1718:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1719: 	var testmsg = "savemsg"+i+",";
                   1720: 	re = new RegExp(testmsg,"g");
1.44      ng       1721: 	shwsel = "";
                   1722: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1723: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1724: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1725: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1726: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1727:     }
1.125     ng       1728:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1729:     shwsel = "";
                   1730:     re = /newmsg/;
                   1731:     if (re.test(msgchk)) { shwsel = "checked" }
                   1732:     newMsg(newmsg,shwsel);
                   1733:     msgTail(); 
                   1734:     return;
                   1735:   }
                   1736: 
1.123     ng       1737:   function checkEntities(strx) {
                   1738:     if (strx.length == 0) return strx;
                   1739:     var orgStr = ["&", "<", ">", '"']; 
                   1740:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1741:     var counter = 0;
                   1742:     while (counter < 4) {
                   1743: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1744: 	counter++;
                   1745:     }
                   1746:     return strx;
                   1747:   }
                   1748: 
                   1749:   function strReplace(strx, orgStr, newStr) {
                   1750:     return strx.split(orgStr).join(newStr);
                   1751:   }
                   1752: 
1.44      ng       1753:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1754:     var height = 70*Nmsg+250;
1.44      ng       1755:     if (height > 600) {
                   1756: 	height = 600;
                   1757:     }
1.118     ng       1758:     var xpos = (screen.width-600)/2;
                   1759:     xpos = (xpos < 0) ? '0' : xpos;
                   1760:     var ypos = (screen.height-height)/2-30;
                   1761:     ypos = (ypos < 0) ? '0' : ypos;
                   1762: 
1.596.2.12.2.  (raeburn 1763:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1764:     pWin.focus();
                   1765:     pDoc = pWin.document;
1.219     www      1766:     pDoc.$docopen;
1.351     albertel 1767:     pDoc.write('$start_page_msg_central');
1.76      ng       1768: 
                   1769:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1770:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  1(raebur 1771:0):     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1772: 
1.596.2.12.2.  1(raebur 1773:0):     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1774:0):     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>");
1.44      ng       1775: }
                   1776:     function displaySubject(msg,shwsel) {
1.76      ng       1777:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1778:0):     pDoc.write("<tr>");
1.465     albertel 1779:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1780:0):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
                   1781:0):     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1782: }
                   1783: 
1.72      ng       1784:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1785:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1786:0):     pDoc.write("<tr>");
1.465     albertel 1787:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1788:0):     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1.465     albertel 1789:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1790: }
                   1791: 
                   1792:   function newMsg(newmsg,shwsel) {
1.76      ng       1793:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1794:0):     pDoc.write("<tr>");
1.465     albertel 1795:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1796:0):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1797:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1798: }
                   1799: 
                   1800:   function msgTail() {
1.76      ng       1801:     pDoc = pWin.document;
1.465     albertel 1802:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1803:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1804:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1805:     pDoc.write("<\\/form>");
1.351     albertel 1806:     pDoc.write('$end_page_msg_central');
1.128     ng       1807:     pDoc.close();
1.44      ng       1808: }
                   1809: 
1.596.2.12.2.  1(raebur 1810:0): SUBJAVASCRIPT
                   1811:0): }
                   1812:0): 
                   1813:0): #--- javascript for essay type problem --
                   1814:0): sub sub_page_kw_js {
                   1815:0):     my $request = shift;
                   1816:0): 
                   1817:0):     unless ($env{'form.compmsg'}) {
                   1818:0):         &commonJSfunctions($request);
                   1819:0):     }
                   1820:0): 
                   1821:0):     my $inner_js_highlight_central= (<<INNERJS);
                   1822:0): <script type="text/javascript">
                   1823:0):     function updateChoice(flag) {
                   1824:0):       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1825:0):       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1826:0):       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1827:0):       opener.document.SCORE.refresh.value = "on";
                   1828:0):       if (opener.document.SCORE.keywords.value!=""){
                   1829:0):          opener.document.SCORE.submit();
                   1830:0):       }
                   1831:0):       self.close()
                   1832:0):     }
                   1833:0): </script>
                   1834:0): INNERJS
                   1835:0): 
                   1836:0):     my $start_page_highlight_central =
                   1837:0):         &Apache::loncommon::start_page('Highlight Central',
                   1838:0):                                        $inner_js_highlight_central,
                   1839:0):                                        {'js_ready'  => 1,
                   1840:0):                                         'only_body' => 1,
                   1841:0):                                         'bgcolor'   =>'#FFFFFF',});
                   1842:0):     my $end_page_highlight_central =
                   1843:0):         &Apache::loncommon::end_page({'js_ready' => 1});
                   1844:0): 
                   1845:0):     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1846:0):     $docopen=~s/^document\.//;
                   1847:0): 
                   1848:0):     my %js_lt = &Apache::lonlocal::texthash(
                   1849:0):                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1850:0):                 plse => 'Please select a word or group of words from document and then click this link.',
                   1851:0):                 adds => 'Add selection to keyword list? Edit if desired.',
                   1852:0):                 col1 => 'red',
                   1853:0):                 col2 => 'green',
                   1854:0):                 col3 => 'blue',
                   1855:0):                 siz1 => 'normal',
                   1856:0):                 siz2 => '+1',
                   1857:0):                 siz3 => '+2',
                   1858:0):                 sty1 => 'normal',
                   1859:0):                 sty2 => 'italic',
                   1860:0):                 sty3 => 'bold',
                   1861:0):              );
                   1862:0):     my %html_js_lt = &Apache::lonlocal::texthash(
                   1863:0):                 save => 'Save',
                   1864:0):                 canc => 'Cancel',
                   1865:0):                 kehi => 'Keyword Highlight Options',
                   1866:0):                 txtc => 'Text Color',
                   1867:0):                 font => 'Font Size',
                   1868:0):                 fnst => 'Font Style',
                   1869:0):              );
                   1870:0):     &js_escape(\%js_lt);
                   1871:0):     &html_escape(\%html_js_lt);
                   1872:0):     &js_escape(\%html_js_lt);
                   1873:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1874:0): 
                   1875:0): //===================== Show list of keywords ====================
                   1876:0):   function keywords(formname) {
                   1877:0):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1878:0):     if (nret==null) return;
                   1879:0):     formname.keywords.value = nret;
                   1880:0): 
                   1881:0):     if (formname.keywords.value != "") {
                   1882:0):         formname.refresh.value = "on";
                   1883:0):         formname.submit();
                   1884:0):     }
                   1885:0):     return;
                   1886:0):   }
                   1887:0): 
                   1888:0): //===================== Script to add keyword(s) ==================
                   1889:0):   function getSel() {
                   1890:0):     if (document.getSelection) txt = document.getSelection();
                   1891:0):     else if (document.selection) txt = document.selection.createRange().text;
                   1892:0):     else return;
                   1893:0):     if (typeof(txt) != 'string') {
                   1894:0):         txt = String(txt);
                   1895:0):     }
                   1896:0):     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1897:0):     if (cleantxt=="") {
                   1898:0):         alert("$js_lt{'plse'}");
                   1899:0):         return;
                   1900:0):     }
                   1901:0):     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1902:0):     if (nret==null) return;
                   1903:0):     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1904:0):     if (document.SCORE.keywords.value != "") {
                   1905:0):         document.SCORE.refresh.value = "on";
                   1906:0):         document.SCORE.submit();
                   1907:0):     }
                   1908:0):     return;
                   1909:0):   }
                   1910:0): 
1.44      ng       1911: //====================== Script for keyword highlight options ==============
                   1912:   function kwhighlight() {
                   1913:     var kwclr    = document.SCORE.kwclr.value;
                   1914:     var kwsize   = document.SCORE.kwsize.value;
                   1915:     var kwstyle  = document.SCORE.kwstyle.value;
                   1916:     var redsel = "";
                   1917:     var grnsel = "";
                   1918:     var blusel = "";
1.596.2.12.2.  6(raebur 1919:6):     var txtcol1 = "$js_lt{'col1'}";
                   1920:6):     var txtcol2 = "$js_lt{'col2'}";
                   1921:6):     var txtcol3 = "$js_lt{'col3'}";
                   1922:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1923:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1924:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1925:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1926:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1927:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1928:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1929:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1930:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1931:     var sznsel = "";
                   1932:     var sz1sel = "";
                   1933:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1934:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1935:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1936:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1937:     var synsel = "";
                   1938:     var syisel = "";
                   1939:     var sybsel = "";
1.596.2.12.2.  8(raebur 1940:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1941:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1942:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1943:     highlightCentral();
1.596.2.12.2.  8(raebur 1944:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1945:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1946:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1947:     highlightend();
                   1948:     return;
                   1949:   }
                   1950: 
                   1951:   function highlightCentral() {
1.76      ng       1952: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1953:     var xpos = (screen.width-400)/2;
                   1954:     xpos = (xpos < 0) ? '0' : xpos;
                   1955:     var ypos = (screen.height-330)/2-30;
                   1956:     ypos = (ypos < 0) ? '0' : ypos;
                   1957: 
1.206     albertel 1958:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1959:     hwdWin.focus();
                   1960:     var hDoc = hwdWin.document;
1.219     www      1961:     hDoc.$docopen;
1.351     albertel 1962:     hDoc.write('$start_page_highlight_central');
1.76      ng       1963:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1964:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1965: 
1.596.2.12.2.  8(raebur 1966:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1967:6):     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1968:   }
                   1969: 
                   1970:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1971:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1972:4):     hDoc.write("<tr>");
1.76      ng       1973:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1974:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1975:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1976:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1977:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1978:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1979:     hDoc.write("<\\/tr>");
1.44      ng       1980:   }
                   1981: 
                   1982:   function highlightend() { 
1.76      ng       1983:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1984:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1985:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1986:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1987:     hDoc.write("<\\/form>");
1.351     albertel 1988:     hDoc.write('$end_page_highlight_central');
1.128     ng       1989:     hDoc.close();
1.44      ng       1990:   }
                   1991: 
                   1992: SUBJAVASCRIPT
                   1993: }
                   1994: 
1.349     albertel 1995: sub get_increment {
1.348     bowersj2 1996:     my $increment = $env{'form.increment'};
                   1997:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1998:         $increment != .1) {
                   1999:         $increment = 1;
                   2000:     }
                   2001:     return $increment;
                   2002: }
                   2003: 
1.585     bisitz   2004: sub gradeBox_start {
                   2005:     return (
                   2006:         &Apache::loncommon::start_data_table()
                   2007:        .&Apache::loncommon::start_data_table_header_row()
                   2008:        .'<th>'.&mt('Part').'</th>'
                   2009:        .'<th>'.&mt('Points').'</th>'
                   2010:        .'<th>&nbsp;</th>'
                   2011:        .'<th>'.&mt('Assign Grade').'</th>'
                   2012:        .'<th>'.&mt('Weight').'</th>'
                   2013:        .'<th>'.&mt('Grade Status').'</th>'
                   2014:        .&Apache::loncommon::end_data_table_header_row()
                   2015:     );
                   2016: }
                   2017: 
                   2018: sub gradeBox_end {
                   2019:     return (
                   2020:         &Apache::loncommon::end_data_table()
                   2021:     );
                   2022: }
1.71      ng       2023: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   2024: sub gradeBox {
1.322     albertel 2025:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 2026:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2027: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2028:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2029:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2030:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2031:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2032:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2033: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 2034:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2035:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2036:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2037: 				       [$partid]);
                   2038:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2039:     if ($last_resets{$partid}) {
                   2040:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2041:     }
1.596.2.12.2.  8(raebur 2042:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2043:     my $ctr = 0;
1.348     bowersj2 2044:     my $thisweight = 0;
1.349     albertel 2045:     my $increment = &get_increment();
1.485     albertel 2046: 
                   2047:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2048:     while ($thisweight<=$wgt) {
1.532     bisitz   2049: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2050:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2051: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2052: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2053: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2054:         $thisweight += $increment;
1.71      ng       2055: 	$ctr++;
                   2056:     }
1.485     albertel 2057:     $radio.='</tr></table>';
                   2058: 
                   2059:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2060: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2061: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2062: 	$wgt.')" /></td>'."\n";
1.485     albertel 2063:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2064: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2065: 	' </td>'."\n";
                   2066:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2067: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2068:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2069: 	$line.='<option></option>'.
                   2070: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2071:     } else {
1.485     albertel 2072: 	$line.='<option selected="selected"></option>'.
                   2073: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2074:     }
1.485     albertel 2075:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2076: 
                   2077: 
                   2078:     $result .= 
1.596.2.12.2.  8(raebur 2079:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
          1(raebur 2080:0):     $result.=&Apache::loncommon::end_data_table_row();
                   2081:0):     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2082:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2083: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2084: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2085: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2086:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2087:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2088:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2089:         $aggtries.'" />'."\n";
1.582     raeburn  2090:     my $res_error;
                   2091:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 2092:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2093:     if ($res_error) {
                   2094:         return &navmap_errormsg();
                   2095:     }
1.318     banghart 2096:     return $result;
                   2097: }
1.322     albertel 2098: 
                   2099: sub handback_box {
1.596.2.12.2.  1(raebur 2100:0):     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   2101:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2102:0):     return unless ($numessay);
1.323     banghart 2103:     my (@respids);
1.596.2.4  raeburn  2104:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2105:     foreach my $part_response_id (@part_response_id) {
                   2106:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2107:         if ($part eq $partid) {
1.375     albertel 2108:             push(@respids,$resp);
1.323     banghart 2109:         }
                   2110:     }
1.318     banghart 2111:     my $result;
1.323     banghart 2112:     foreach my $respid (@respids) {
1.322     albertel 2113: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2114: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2115: 	next if (!@$files);
1.596.2.4  raeburn  2116: 	my $file_counter = 0;
1.313     banghart 2117: 	foreach my $file (@$files) {
1.368     banghart 2118: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  2119:                 $file_counter++;
1.368     banghart 2120:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   2121:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   2122:     	        $file_disp = "$name.$ext";
                   2123:     	        $file = $file_path.$file_disp;
                   2124:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2125:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2126:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  2127:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2128: 	    }
1.322     albertel 2129: 	}
1.596.2.4  raeburn  2130:         if ($file_counter) {
                   2131:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2132:                        '<span class="LC_info">'.
                   2133:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2134:         }
1.313     banghart 2135:     }
1.318     banghart 2136:     return $result;    
1.71      ng       2137: }
1.44      ng       2138: 
1.58      albertel 2139: sub show_problem {
1.382     albertel 2140:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2141:     my $rendered;
1.382     albertel 2142:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2143:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2144:     if ($mode eq 'both' or $mode eq 'text') {
                   2145: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2146: 						       $env{'request.course.id'},
                   2147: 						       undef,\%form);
1.144     albertel 2148:     }
1.58      albertel 2149:     if ($removeform) {
                   2150: 	$rendered=~s|<form(.*?)>||g;
                   2151: 	$rendered=~s|</form>||g;
1.374     albertel 2152: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2153:     }
1.144     albertel 2154:     my $companswer;
                   2155:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2156: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2157: 	$companswer=
                   2158: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2159: 						    $env{'request.course.id'},
                   2160: 						    %form);
1.144     albertel 2161:     }
1.58      albertel 2162:     if ($removeform) {
                   2163: 	$companswer=~s|<form(.*?)>||g;
                   2164: 	$companswer=~s|</form>||g;
1.144     albertel 2165: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2166:     }
1.596.2.12.2.  (raeburn 2167:):     my $renderheading = &mt('View of the problem');
                   2168:):     my $answerheading = &mt('Correct answer');
                   2169:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2170:):         my $stu_fullname = $env{'form.fullname'};
                   2171:):         if ($stu_fullname eq '') {
                   2172:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2173:):         }
                   2174:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2175:):         if ($forwhom ne '') {
                   2176:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2177:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2178:):         }
                   2179:):     }
1.468     albertel 2180:     $rendered=
1.588     bisitz   2181:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2182:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2183:        .$rendered
                   2184:        .'</div>';
1.468     albertel 2185:     $companswer=
1.588     bisitz   2186:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2187:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2188:        .$companswer
                   2189:        .'</div>';
1.468     albertel 2190:     my $result;
1.144     albertel 2191:     if ($mode eq 'both') {
1.588     bisitz   2192:         $result=$rendered.$companswer;
1.144     albertel 2193:     } elsif ($mode eq 'text') {
1.588     bisitz   2194:         $result=$rendered;
1.144     albertel 2195:     } elsif ($mode eq 'answer') {
1.588     bisitz   2196:         $result=$companswer;
1.144     albertel 2197:     }
1.71      ng       2198:     return $result;
1.58      albertel 2199: }
1.397     albertel 2200: 
1.396     banghart 2201: sub files_exist {
                   2202:     my ($r, $symb) = @_;
                   2203:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2204:     foreach my $student (@students) {
                   2205:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2206:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2207: 					      $udom,$uname);
1.596.2.12.2.  0.2.2(ra 2208:ar-23):         my ($string)= &get_last_submission(\%record);
1.397     albertel 2209:         foreach my $submission (@$string) {
                   2210:             my ($partid,$respid) =
                   2211: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2212:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2213: 					   \%record);
                   2214:             return 1 if (@$files);
1.396     banghart 2215:         }
                   2216:     }
1.397     albertel 2217:     return 0;
1.396     banghart 2218: }
1.397     albertel 2219: 
1.394     banghart 2220: sub download_all_link {
                   2221:     my ($r,$symb) = @_;
1.596.2.12.2.  1(raebur 2222:0):     unless (&files_exist($r, $symb)) {
                   2223:0):         $r->print(&mt('There are currently no submitted documents.'));
                   2224:0):         return;
                   2225:0):     }
1.395     albertel 2226:     my $all_students = 
                   2227: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2228: 
                   2229:     my $parts =
                   2230: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2231: 
1.394     banghart 2232:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2233:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2234:                              'cgi.'.$identifier.'.symb' => $symb,
                   2235:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2236:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2237: 	      &mt('Download All Submitted Documents').'</a>');
1.596.2.12.2.  1(raebur 2238:0):     return;
                   2239:0): }
                   2240:0): 
                   2241:0): sub submit_download_link {
                   2242:0):     my ($request,$symb) = @_;
                   2243:0):     if (!$symb) { return ''; }
                   2244:0):     my $res_error;
                   2245:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2246:0):         &response_type($symb,\$res_error);
                   2247:0):     if ($res_error) {
                   2248:0):         $request->print(&mt('An error occurred retrieving response types'));
                   2249:0):         return;
                   2250:0):     }
                   2251:0):     unless ($numessay) {
                   2252:0):         $request->print(&mt('No essayresponse items found'));
                   2253:0):         return;
                   2254:0):     }
                   2255:0):     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2256:0):     if (@chosenparts) {
                   2257:0):         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2258:0):                                           undef,undef,1));
                   2259:0):     }
                   2260:0):     if ($numessay) {
                   2261:0):         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2262:0):         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2263:0):         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2264:0):         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2265:0):         if (ref($fullname) eq 'HASH') {
                   2266:0):             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2267:0):             if (@students) {
                   2268:0):                 @{$env{'form.stuinfo'}} = @students;
                   2269:0):                 if ($numdropbox) {
                   2270:0):                     &download_all_link($request,$symb);
                   2271:0):                 } else {
                   2272:0):                     $request->print(&mt('No essayrespose items with dropbox found'));
                   2273:0):                 }
                   2274:0): # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
                   2275:0): # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2276:0):             } else {
                   2277:0):                 $request->print(&mt('No students match the criteria you selected'));
                   2278:0):             }
                   2279:0):         } else {
                   2280:0):             $request->print(&mt('Could not retrieve student information'));
                   2281:0):         }
                   2282:0):     } else {
                   2283:0):         $request->print(&mt('No essayresponse items found'));
                   2284:0):     }
                   2285:0):     return;
1.394     banghart 2286: }
1.395     albertel 2287: 
1.432     banghart 2288: sub build_section_inputs {
                   2289:     my $section_inputs;
                   2290:     if ($env{'form.section'} eq '') {
                   2291:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2292:     } else {
                   2293:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2294:         foreach my $section (@sections) {
1.432     banghart 2295:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2296:         }
                   2297:     }
                   2298:     return $section_inputs;
                   2299: }
                   2300: 
1.44      ng       2301: # --------------------------- show submissions of a student, option to grade 
                   2302: sub submission {
1.596.2.12.2.  1(raebur 2303:0):     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2304:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2305:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2306:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2307:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  1(raebur 2308:0): 
1.324     albertel 2309:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.596.2.12.2.  1(raebur 2310:0):     my $probtitle=&Apache::lonnet::gettitle($symb);
          0.2.4(ra 2311:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          5(raebur 2312:9):     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2313: 
                   2314:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2315:4):         $request->print(
                   2316:4):             '<span class="LC_warning">'.
                   2317:4):             &mt('Unable to view requested student.').
                   2318:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2319:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2320:4):             '</span>');
1.104     albertel 2321: 	return;
                   2322:     }
                   2323: 
1.596.2.12.2.  1(raebur 2324:0):     my $res_error;
                   2325:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2326:0):         &response_type($symb,\$res_error);
                   2327:0):     if ($res_error) {
                   2328:0):         $request->print(&navmap_errormsg());
                   2329:0):         return;
                   2330:0):     }
                   2331:0): 
1.257     albertel 2332:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.596.2.12.2.  0.2.4(ra 2333:ul-23):     unless ($is_tool) {
                   2334:ul-23):         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2335:ul-23):         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2336:ul-23):     }
          1(raebur 2337:0):     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2338:0):         $env{'form.compmsg'} = 1;
                   2339:0):     }
1.257     albertel 2340:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2341:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2342: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2343: 	'/check.gif" height="16" border="0" />';
1.41      ng       2344: 
                   2345:     # header info
                   2346:     if ($counter == 0) {
1.596.2.12.2.  1(raebur 2347:0):         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2348:0):         if (@chosenparts) {
                   2349:0):             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2350:0):         } elsif ($divforres) {
                   2351:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2352:0):         } else {
                   2353:0):             $request->print('<br clear="all" />');
                   2354:0):         }
1.41      ng       2355: 	&sub_page_js($request);
1.596.2.12.2.  1(raebur 2356:0):         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2357:0): 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2358: 
1.44      ng       2359: 	# option to display problem, only once else it cause problems 
                   2360:         # with the form later since the problem has a form.
1.257     albertel 2361: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2362: 	    my $mode;
1.257     albertel 2363: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2364: 		$mode='both';
1.257     albertel 2365: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2366: 		$mode='text';
1.257     albertel 2367: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2368: 		$mode='answer';
                   2369: 	    }
1.329     albertel 2370: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2371: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2372: 	}
1.441     www      2373: 
1.41      ng       2374: 	my %keyhash = ();
1.596.2.12.2.  1(raebur 2375:0): 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2376: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2377: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2378: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.596.2.12.2.  1(raebur 2379:0): 	}
                   2380:0): 	# kwclr is the only variable that is guaranteed not to be blank
                   2381:0): 	# if this subroutine has been called once.
                   2382:0): 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2383: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2384: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2385: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2386: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2387: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.596.2.12.2.  1(raebur 2388:0): 	}
                   2389:0): 	if ($env{'form.compmsg'}) {
                   2390:0): 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
                   2391:0): 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2392: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2393: 	}
1.596.2.12.2.  1(raebur 2394:0): 
1.257     albertel 2395: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2396: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2397: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2398: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2399: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2400: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2401: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2402: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2403: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2404: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2405: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2406: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2407: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2408:0): 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2409: 			&build_section_inputs().
1.326     albertel 2410: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2411: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2412: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.596.2.12.2.  1(raebur 2413:0): 	if ($env{'form.compmsg'}) {
                   2414:0): 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2415:0): 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2416:0): 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2417:0): 	}
                   2418:0): 	if ($numessay) {
1.257     albertel 2419: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2420: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2421: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2422:0): 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2423: 	}
1.596.2.12.2.  1(raebur 2424:0): 
1.41      ng       2425: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2426: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2427: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2428: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2429: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2430: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2431: 		'" />'."\n".
                   2432: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2433: 	    $cts++;
                   2434: 	}
                   2435: 	$request->print($prnmsg);
1.32      ng       2436: 
1.596.2.12.2.  1(raebur 2437:0): 	if ($numessay) {
1.596.2.4  raeburn  2438: 
                   2439:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2440:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2441:                           keyw => 'Keyword Options',
                   2442:                           list => 'List',
                   2443:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2444:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2445:                      );
1.88      www      2446: #
                   2447: # Print out the keyword options line
                   2448: #
1.596.2.12.2.  1(raebur 2449:0): 	    $request->print(
          8(raebur 2450:4):                 '<div class="LC_columnSection">'
                   2451:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2452:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2453:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2454:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2455:4):  class="page">'.$lt{'past'}.'</a>',
                   2456:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2457:4):                     {legend => $lt{'keyw'}})
                   2458:4):                .'</fieldset></div>'
                   2459:4):             );
                   2460:4): 
1.88      www      2461: #
                   2462: # Load the other essays for similarity check
                   2463: #
1.596.2.12.2.  5(raebur 2464:9):             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2465:9):             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2466:9):                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2467:9):                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2468:9):                 if ($cdom ne '' && $cnum ne '') {
                   2469:9):                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2470:9):                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2471:9):                         my $apath = $1.'_'.$id;
                   2472:9):                         $apath=~s/\W/\_/gs;
                   2473:9):                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2474:9):                     }
                   2475:9):                 }
                   2476:9):             } else {
                   2477:9): 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2478:9): 	        $apath=&escape($apath);
                   2479:9): 	        $apath=~s/\W/\_/gs;
                   2480:9):                 &init_old_essays($symb,$apath,$adom,$aname);
                   2481:9):             }
1.41      ng       2482:         }
                   2483:     }
1.44      ng       2484: 
1.441     www      2485: # This is where output for one specific student would start
1.592     bisitz   2486:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2487:     $request->print(
                   2488:         "\n\n"
                   2489:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2490:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2491:        ."\n"
                   2492:     );
1.441     www      2493: 
1.592     bisitz   2494:     # Show additional functions if allowed
                   2495:     if ($perm{'vgr'}) {
                   2496:         $request->print(
                   2497:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2498:3):                 'View recent activity',
1.592     bisitz   2499:                 $uname,$udom,'check')
                   2500:            .' '
                   2501:         );
                   2502:     }
                   2503:     if ($perm{'opa'}) {
                   2504:         $request->print(
                   2505:             &Apache::loncommon::pprmlink(
                   2506:                 &mt('Set/Change parameters'),
                   2507:                 $uname,$udom,$symb,'check'));
                   2508:     }
                   2509: 
                   2510:     # Show Problem
1.257     albertel 2511:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2512: 	my $mode;
1.257     albertel 2513: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2514: 	    $mode='both';
1.257     albertel 2515: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2516: 	    $mode='text';
1.257     albertel 2517: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2518: 	    $mode='answer';
                   2519: 	}
1.329     albertel 2520: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2521: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2522:     }
1.144     albertel 2523: 
1.257     albertel 2524:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2525: 
1.44      ng       2526:     # Display student info
1.41      ng       2527:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2528: 
1.596.2.12.2.  0.2.4(ra 2529:ul-23):     my $boxtitle = &mt('Submissions');
                   2530:ul-23):     if ($is_tool) {
                   2531:ul-23):         $boxtitle = &mt('Transactions')
                   2532:ul-23):     }
1.590     bisitz   2533:     my $result='<div class="LC_Box">'
1.596.2.12.2.  0.2.4(ra 2534:ul-23):               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2535:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2536:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.596.2.12.2.  0.2.4(ra 2537:ul-23):     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   2538:         $result.='<p class="LC_info">'
                   2539:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2540:                 ."</p>\n";
1.469     albertel 2541:     }
                   2542: 
1.596.2.12.2.  1(raebur 2543:0):     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2544:     my $fullname;
                   2545:     my $col_fullnames = [];
1.596.2.12.2.  1(raebur 2546:0):     if ($numessay) {
1.464     albertel 2547: 	(my $sub_result,$fullname,$col_fullnames)=
                   2548: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2549: 				 $counter);
                   2550: 	$result.=$sub_result;
1.41      ng       2551:     }
1.44      ng       2552:     $request->print($result."\n");
1.588     bisitz   2553: 
1.44      ng       2554:     # print student answer/submission
1.596.2.12.2.  1(raebur 2555:0):     # Options are (1) Last submission only
                   2556:0):     #             (2) Last submission (with detailed information for that submission)
                   2557:0):     #             (3) All transactions (by date)
                   2558:0):     #             (4) The whole record (with detailed information for all transactions)
                   2559:0): 
          0.2.5(ra 2560:ep-23):     my ($lastsubonly,$partinfo) =
                   2561:ep-23):         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
                   2562:ep-23):                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
                   2563:ep-23):     $request->print($partinfo);
          1(raebur 2564:0):     $request->print($lastsubonly);
          0.2.5(ra 2565:ep-23): 
          1(raebur 2566:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2567:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2568: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2569:3):     }
                   2570:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2571:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2572: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2573: 								 $env{'request.course.id'},
1.44      ng       2574: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2575:5): 								 'Apache::grades::keywords_highlight',
                   2576:5):                                                                  $usec,$identifier));
1.41      ng       2577:     }
1.121     ng       2578:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2579: 	.$udom.'" />'."\n");
1.44      ng       2580:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2581:0):     if (!&canmodify($usec)) {
                   2582:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2583:0):         return;
1.180     albertel 2584:     } else {
1.468     albertel 2585: 	$request->print('</div>'."\n");
1.41      ng       2586:     }
1.33      ng       2587: 
1.596.2.12.2.  1(raebur 2588:0):     # grading message center
                   2589:0): 
                   2590:0):     if ($env{'form.compmsg'}) {
                   2591:0):         my $result='<div class="LC_Box">'.
                   2592:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2593:0):                    '<div class="LC_grade_message_center_body">';
                   2594:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2595:0):         my $msgfor = $givenn.' '.$lastname;
                   2596:0):         if (scalar(@$col_fullnames) > 0) {
                   2597:0):             my $lastone = pop(@$col_fullnames);
                   2598:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2599:0):         }
                   2600:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2601:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2602:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2603:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2604:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2605:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2606:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2607:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2608:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2609:0):                  '<br />&nbsp;('.
                   2610:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2611:0): 	         '</div></div>';
                   2612:0):         $request->print($result);
1.118     ng       2613:     }
1.41      ng       2614: 
                   2615:     my %seen = ();
                   2616:     my @partlist;
1.129     ng       2617:     my @gradePartRespid;
1.596.2.12.2.  0.2.4(ra 2618:ul-23):     my @part_response_id;
                   2619:ul-23):     if ($is_tool) {
                   2620:ul-23):         @part_response_id = ([0,'']);
                   2621:ul-23):     } else {
                   2622:ul-23):         @part_response_id = &flatten_responseType($responseType);
                   2623:ul-23):     }
1.585     bisitz   2624:     $request->print(
1.588     bisitz   2625:         '<div class="LC_Box">'
                   2626:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2627:     );
1.592     bisitz   2628:     $request->print(&gradeBox_start());
1.375     albertel 2629:     foreach my $part_response_id (@part_response_id) {
                   2630:     	my ($partid,$respid) = @{ $part_response_id };
                   2631: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2632: 	next if ($seen{$partid} > 0);
1.41      ng       2633: 	$seen{$partid}++;
1.524     raeburn  2634: 	push(@partlist,$partid);
                   2635: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2636: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2637:     }
1.585     bisitz   2638:     $request->print(&gradeBox_end()); # </div>
                   2639:     $request->print('</div>');
1.468     albertel 2640: 
                   2641:     $request->print('<div class="LC_grade_info_links">');
                   2642:     $request->print('</div>');
                   2643: 
1.45      ng       2644:     $result='<input type="hidden" name="partlist'.$counter.
                   2645: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2646:     $result.='<input type="hidden" name="gradePartRespid'.
                   2647: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2648:     my $ctr = 0;
                   2649:     while ($ctr < scalar(@partlist)) {
                   2650: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2651: 	    $partlist[$ctr].'" />'."\n";
                   2652: 	$ctr++;
                   2653:     }
1.468     albertel 2654:     $request->print($result.''."\n");
1.41      ng       2655: 
1.441     www      2656: # Done with printing info for one student
                   2657: 
1.468     albertel 2658:     $request->print('</div>');#LC_grade_show_user
1.441     www      2659: 
                   2660: 
1.41      ng       2661:     # print end of form
                   2662:     if ($counter == $total) {
1.592     bisitz   2663:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2664: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2665: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2666: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2667: 	my $ntstu ='<select name="NTSTU">'.
                   2668: 	    '<option>1</option><option>2</option>'.
                   2669: 	    '<option>3</option><option>5</option>'.
                   2670: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2671: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2672: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2673:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2674: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2675: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2676: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2677: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2678:         $endform.='<span class="LC_warning">'.
                   2679:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2680:                   '</span>'."\n" ;
1.349     albertel 2681:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2682:             "' name='increment' />";
1.485     albertel 2683: 	$endform.='</td></tr></table></form>';
1.41      ng       2684: 	$request->print($endform);
                   2685:     }
                   2686:     return '';
1.38      ng       2687: }
                   2688: 
1.596.2.12.2.  0.2.5(ra 2689:ep-23): sub show_last_submission {
                   2690:ep-23):     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
                   2691:ep-23):         $record,$coursedesc_by_cid) = @_;
                   2692:ep-23):     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
                   2693:ep-23):         &get_last_submission($record,$is_tool);
                   2694:ep-23): 
                   2695:ep-23):     my ($lastsubonly,$partinfo);
                   2696:ep-23):     if ($timestamp eq '') {
                   2697:ep-23):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
                   2698:ep-23):     } elsif ($is_tool) {
                   2699:ep-23):         $lastsubonly =
                   2700:ep-23):             '<div class="LC_grade_submissions_body">'
                   2701:ep-23):            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
                   2702:ep-23):     } else {
                   2703:ep-23):         my ($shownsubmdate,$showngradedate);
                   2704:ep-23):         if ($lastsubmittime && $lastgradetime) {
                   2705:ep-23):             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   2706:ep-23):             if ($lastgradetime > $lastsubmittime) {
                   2707:ep-23):                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   2708:ep-23):              }
                   2709:ep-23):         } else {
                   2710:ep-23):             $shownsubmdate = $timestamp;
                   2711:ep-23):         }
                   2712:ep-23):         $lastsubonly =
                   2713:ep-23):             '<div class="LC_grade_submissions_body">'
                   2714:ep-23):            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   2715:ep-23):         if ($showngradedate) {
                   2716:ep-23):             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   2717:ep-23):         }
                   2718:ep-23): 
                   2719:ep-23):         my %seenparts;
                   2720:ep-23):         my @part_response_id = &flatten_responseType($responseType);
                   2721:ep-23):         foreach my $part (@part_response_id) {
                   2722:ep-23):             my ($partid,$respid) = @{ $part };
                   2723:ep-23):             my $display_part=&get_display_part($partid,$symb);
                   2724:ep-23):             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2725:ep-23):                 if (exists($seenparts{$partid})) { next; }
                   2726:ep-23):                 $seenparts{$partid}=1;
                   2727:ep-23):                 $partinfo .=
                   2728:ep-23):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2729:ep-23):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2730:ep-23):                                '<a href="javascript:viewSubmitter(\''.
                   2731:ep-23):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2732:ep-23):                                '\');" target="_self">'.
                   2733:ep-23):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2734:ep-23):                     '<br />';
                   2735:ep-23):                 next;
                   2736:ep-23):             }
                   2737:ep-23):             my $responsetype = $responseType->{$partid}->{$respid};
                   2738:ep-23):             if (!exists($record->{"resource.$partid.$respid.submission"})) {
                   2739:ep-23):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2740:ep-23):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2741:ep-23):                     ' <span class="LC_internal_info">'.
                   2742:ep-23):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2743:ep-23):                     '</span>&nbsp; &nbsp;'.
                   2744:ep-23):                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2745:ep-23):                 next;
                   2746:ep-23):             }
                   2747:ep-23):             foreach my $submission (@$string) {
                   2748:ep-23):                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2749:ep-23):                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2750:ep-23):                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2751:ep-23):                 # Similarity check
                   2752:ep-23):                 my $similar='';
                   2753:ep-23):                 my ($type,$trial,$rndseed);
                   2754:ep-23):                 if ($hide eq 'rand') {
                   2755:ep-23):                     $type = 'randomizetry';
                   2756:ep-23):                     $trial = $record->{"resource.$partid.tries"};
                   2757:ep-23):                     $rndseed = $record->{"resource.$partid.rndseed"};
                   2758:ep-23):                 }
                   2759:ep-23):                 if ($env{'form.checkPlag'}) {
                   2760:ep-23):                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2761:ep-23):                     &most_similar($uname,$udom,$symb,$subval);
                   2762:ep-23):                     if ($osim) {
                   2763:ep-23):                         $osim=int($osim*100.0);
                   2764:ep-23):                         if ($hide eq 'anon') {
                   2765:ep-23):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2766:ep-23):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2767:ep-23):                         } else {
                   2768:ep-23):                             $similar='<hr />';
                   2769:ep-23):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2770:ep-23):                                 $similar .= '<h3><span class="LC_warning">'.
                   2771:ep-23):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2772:ep-23):                                                 $osim,
                   2773:ep-23):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2774:ep-23):                                             '</span></h3>';
                   2775:ep-23):                             } else {
                   2776:ep-23):                                 my %old_course_desc;
                   2777:ep-23):                                 if ($ocrsid ne '') {
                   2778:ep-23):                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
                   2779:ep-23):                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
                   2780:ep-23):                                     } else {
                   2781:ep-23):                                         my $args;
                   2782:ep-23):                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2783:ep-23):                                             $args = {'one_time' => 1};
                   2784:ep-23):                                         }
                   2785:ep-23):                                         %old_course_desc =
                   2786:ep-23):                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2787:ep-23):                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
                   2788:ep-23):                                     }
                   2789:ep-23):                                     $similar .=
                   2790:ep-23):                                         '<h3><span class="LC_warning">'.
                   2791:ep-23):                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2792:ep-23):                                             $osim,
                   2793:ep-23):                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2794:ep-23):                                             $old_course_desc{'description'},
                   2795:ep-23):                                             $old_course_desc{'num'},
                   2796:ep-23):                                             $old_course_desc{'domain'}).
                   2797:ep-23):                                         '</span></h3>';
                   2798:ep-23):                                 } else {
                   2799:ep-23):                                     $similar .=
                   2800:ep-23):                                         '<h3><span class="LC_warning">'.
                   2801:ep-23):                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2802:ep-23):                                             $osim,
                   2803:ep-23):                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2804:ep-23):                                         '</span></h3>';
                   2805:ep-23):                                 }
                   2806:ep-23):                             }
                   2807:ep-23):                             $similar .= '<blockquote><i>'.
                   2808:ep-23):                                         &keywords_highlight($oessay).
                   2809:ep-23):                                         '</i></blockquote><hr />';
                   2810:ep-23):                         }
                   2811:ep-23):                     }
                   2812:ep-23):                 }
                   2813:ep-23):                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2814:ep-23):                                      undef,$type,$trial,$rndseed);
                   2815:ep-23):                 if (($viewtype eq 'lastonly') ||
                   2816:ep-23):                     ($viewtype eq 'datesub')  ||
                   2817:ep-23):                     ($viewtype =~ /^(last|all)$/)) {
                   2818:ep-23):                     my $display_part=&get_display_part($partid,$symb);
                   2819:ep-23):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2820:ep-23):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2821:ep-23):                         ' <span class="LC_internal_info">'.
                   2822:ep-23):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2823:ep-23):                         '</span>&nbsp; &nbsp;';
                   2824:ep-23):                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2825:ep-23):                     if (@$files) {
                   2826:ep-23):                         if ($hide eq 'anon') {
                   2827:ep-23):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2828:ep-23):                         } else {
                   2829:ep-23):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2830:ep-23):                                         .'<br /><span class="LC_warning">';
                   2831:ep-23):                             if(@$files == 1) {
                   2832:ep-23):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2833:ep-23):                             } else {
                   2834:ep-23):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2835:ep-23):                             }
                   2836:ep-23):                             $lastsubonly .= '</span>';
                   2837:ep-23):                             foreach my $file (@$files) {
                   2838:ep-23):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2839:ep-23):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
                   2840:ep-23):                             }
                   2841:ep-23):                         }
                   2842:ep-23):                         $lastsubonly.='<br />';
                   2843:ep-23):                     }
                   2844:ep-23):                     if ($hide eq 'anon') {
                   2845:ep-23):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
                   2846:ep-23):                     } else {
                   2847:ep-23):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2848:ep-23):                         if ($draft) {
                   2849:ep-23):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2850:ep-23):                         }
                   2851:ep-23):                         $subval =
                   2852:ep-23):                             &cleanRecord($subval,$responsetype,$symb,$partid,
                   2853:ep-23):                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2854:ep-23):                         if ($responsetype eq 'essay') {
                   2855:ep-23):                             $subval =~ s{\n}{<br />}g;
                   2856:ep-23):                         }
                   2857:ep-23):                         $lastsubonly.=$subval."\n";
                   2858:ep-23):                     }
                   2859:ep-23):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2860:ep-23):                     $lastsubonly.='</div>';
                   2861:ep-23):                 }
                   2862:ep-23):             }
                   2863:ep-23):         }
                   2864:ep-23):         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2865:ep-23):     }
                   2866:ep-23):     return ($lastsubonly,$partinfo);
                   2867:ep-23): }
                   2868:ep-23): 
1.464     albertel 2869: sub check_collaborators {
                   2870:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2871:     my ($result,@col_fullnames);
                   2872:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2873:     foreach my $part (keys(%$handgrade)) {
                   2874: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2875: 					'.maxcollaborators',
                   2876: 					$symb,$udom,$uname);
                   2877: 	next if ($ncol <= 0);
                   2878: 	$part =~ s/\_/\./g;
                   2879: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2880: 	my (@good_collaborators, @bad_collaborators);
                   2881: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2882: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2883: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2884: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2885: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2886: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2887: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2888: 	    # Doing this grep allows 'fuzzy' specification
                   2889: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2890: 			       keys(%$classlist));
                   2891: 	    if (! scalar(@matches)) {
                   2892: 		push(@bad_collaborators, $possible_collaborator);
                   2893: 	    } else {
                   2894: 		push(@good_collaborators, @matches);
                   2895: 	    }
                   2896: 	}
                   2897: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2898: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2899: 	    foreach my $name (@good_collaborators) {
                   2900: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2901: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2902: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2903: 	    }
1.596.2.4  raeburn  2904: 	    $result.='</ol><br />'."\n";
1.466     albertel 2905: 	    my ($part)=split(/\./,$part);
1.464     albertel 2906: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2907: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2908: 		"\n";
                   2909: 	}
                   2910: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2911: 	    $result.='<div class="LC_warning">';
1.464     albertel 2912: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2913: 	    $result .= '</div>';
                   2914: 	}         
                   2915: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2916: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2917: 	    $result .= &mt('This student has submitted too many '.
                   2918: 		'collaborators.  Maximum is [_1].',$ncol);
                   2919: 	    $result .= '</div>';
                   2920: 	}
                   2921:     }
                   2922:     return ($result,$fullname,\@col_fullnames);
                   2923: }
                   2924: 
1.44      ng       2925: #--- Retrieve the last submission for all the parts
1.38      ng       2926: sub get_last_submission {
1.596.2.12.2.  0.2.4(ra 2927:ul-23):     my ($returnhash,$is_tool)=@_;
          0.2.2(ra 2928:ar-23):     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       2929:     if ($$returnhash{'version'}) {
1.46      ng       2930: 	my %lasthash=();
1.596.2.12.2.  0.2.2(ra 2931:ar-23):         my %prevsolved=();
                   2932:ar-23):         my %solved=();
                   2933:ar-23): 	my $version;
1.119     ng       2934: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.596.2.12.2.  0.2.2(ra 2935:ar-23):             my %handgraded = ();
1.397     albertel 2936: 	    foreach my $key (sort(split(/\:/,
                   2937: 					$$returnhash{$version.':keys'}))) {
                   2938: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.596.2.12.2.  0.2.2(ra 2939:ar-23):                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   2940:ar-23):                     $handgraded{$1} = 1;
                   2941:ar-23):                 } elsif ($key =~ /\.portfiles$/) {
                   2942:ar-23):                     if (($$returnhash{$version.':'.$key} ne '') &&
                   2943:ar-23):                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   2944:ar-23):                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2945:ar-23):                     }
                   2946:ar-23):                 } elsif ($key =~ /\.submission$/) {
                   2947:ar-23):                     if ($$returnhash{$version.':'.$key} ne '') {
                   2948:ar-23):                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2949:ar-23):                     }
                   2950:ar-23):                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   2951:ar-23):                     $prevsolved{$1} = $solved{$1};
                   2952:ar-23):                     $solved{$1} = $lasthash{$key};
                   2953:ar-23):                 }
          0.2.3(ra 2954:ar-23):             }
          0.2.2(ra 2955:ar-23):             foreach my $partid (keys(%handgraded)) {
                   2956:ar-23):                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   2957:ar-23):                     (($solved{$partid} eq 'incorrect_by_override') ||
                   2958:ar-23):                      ($solved{$partid} eq 'correct_by_override'))) {
                   2959:ar-23):                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   2960:ar-23):                 }
                   2961:ar-23):                 if ($solved{$partid} ne '') {
                   2962:ar-23):                     $prevsolved{$partid} = $solved{$partid};
                   2963:ar-23):                 }
                   2964:ar-23):             }
                   2965:ar-23): 	    $timestamp = 
                   2966:ar-23): 		&Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2967: 	}
1.596.2.2  raeburn  2968:         my (%typeparts,%randombytry);
1.596     raeburn  2969:         my $showsurv = 
                   2970:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2971:         foreach my $key (sort(keys(%lasthash))) {
                   2972:             if ($key =~ /\.type$/) {
                   2973:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2974:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2975:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2976:                     my ($ign,@parts) = split(/\./,$key);
                   2977:                     pop(@parts);
1.596.2.3  raeburn  2978:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2979:                     if ($lasthash{$key} eq 'randomizetry') {
                   2980:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2981:                     } else {
                   2982:                         unless ($showsurv) {
                   2983:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2984:                         }
1.596     raeburn  2985:                     }
                   2986:                     delete($lasthash{$key});
                   2987:                 }
                   2988:             }
                   2989:         }
                   2990:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2991:         my @randomize = keys(%randombytry);
1.397     albertel 2992: 	foreach my $key (keys(%lasthash)) {
                   2993: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2994:             my $hide;
                   2995:             if (@hidden) {
                   2996:                 foreach my $id (@hidden) {
                   2997:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2998:                         $hide = 'anon';
1.596     raeburn  2999:                         last;
                   3000:                     }
                   3001:                 }
                   3002:             }
1.596.2.2  raeburn  3003:             unless ($hide) {
                   3004:                 if (@randomize) {
1.596.2.12.2.  3(raebur 3005:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  3006:                         if ($key =~ /^\Q$id\E/) {
                   3007:                             $hide = 'rand';
                   3008:                             last;
                   3009:                         }
                   3010:                     }
                   3011:                 }
                   3012:             }
1.397     albertel 3013: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 3014:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 3015:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 3016:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3017:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3018: 	}
                   3019:     }
1.397     albertel 3020:     if (!@string) {
1.596.2.12.2.  0.2.4(ra 3021:ul-23):         my $msg;
                   3022:ul-23):         if ($is_tool) {
                   3023:ul-23):             $msg = &mt('No grade passed back.');
                   3024:ul-23):         } else {
                   3025:ul-23):             $msg = &mt('Nothing submitted - no attempts.');
                   3026:ul-23):         }
1.397     albertel 3027: 	$string[0] =
1.596.2.12.2.  0.2.4(ra 3028:ul-23): 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3029:     }
1.596.2.12.2.  0.2.2(ra 3030:ar-23):     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3031: }
1.35      ng       3032: 
1.44      ng       3033: #--- High light keywords, with style choosen by user.
1.38      ng       3034: sub keywords_highlight {
1.44      ng       3035:     my $string    = shift;
1.257     albertel 3036:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3037:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3038:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3039:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3040:     foreach my $keyword (@keylist) {
                   3041: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3042:     }
                   3043:     return $string;
1.38      ng       3044: }
1.36      ng       3045: 
1.596.2.12.2.  (raeburn 3046:): # For Tasks provide a mechanism to display previous version for one specific student
                   3047:): 
                   3048:): sub show_previous_task_version {
                   3049:):     my ($request,$symb) = @_;
                   3050:):     if ($symb eq '') {
          8(raebur 3051:4):         $request->print(
                   3052:4):             '<span class="LC_error">'.
                   3053:4):             &mt('Unable to handle ambiguous references.').
                   3054:4):             '</span>');
          (raeburn 3055:):         return '';
                   3056:):     }
                   3057:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3058:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3059:):     if (!&canview($usec)) {
          8(raebur 3060:4):         $request->print('<span class="LC_warning">'.
                   3061:4):                         &mt('Unable to view previous version for requested student.').
                   3062:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 3063:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 3064:4):                         '</span>');
          (raeburn 3065:):         return;
                   3066:):     }
                   3067:):     my $mode = 'both';
                   3068:):     my $isTask = ($symb =~/\.task$/);
                   3069:):     if ($isTask) {
                   3070:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3071:):             if ($env{'form.fullname'} eq '') {
                   3072:):                 $env{'form.fullname'} =
                   3073:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3074:):             }
                   3075:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3076:):             $request->print("\n\n".
                   3077:):                             '<div class="LC_grade_show_user">'.
                   3078:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3079:):                             '</h2>'."\n");
                   3080:):             &Apache::lonxml::clear_problem_counter();
                   3081:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3082:):                             {'previousversion' => $env{'form.previousversion'} }));
                   3083:):             $request->print("\n</div>");
                   3084:):         }
                   3085:):     }
                   3086:):     return;
                   3087:): }
                   3088:): 
                   3089:): sub choose_task_version_form {
                   3090:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   3091:):     my $isTask = ($symb =~/\.task$/);
                   3092:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3093:):     if ($isTask) {
                   3094:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3095:):                                               $udom,$uname);
                   3096:):         if (($record{'resource.0.version'} eq '') ||
                   3097:):             ($record{'resource.0.version'} < 2)) {
                   3098:):             return ($record{'resource.0.version'},
                   3099:):                     $record{'resource.0.version'},$result,$js);
                   3100:):         } else {
                   3101:):             $current = $record{'resource.0.version'};
                   3102:):         }
                   3103:):         if ($env{'form.previousversion'}) {
                   3104:):             $displayed = $env{'form.previousversion'};
                   3105:):             $rowtitle = &mt('Choose another version:')
                   3106:):         } else {
                   3107:):             $displayed = $current;
                   3108:):             $rowtitle = &mt('Show earlier version:');
                   3109:):         }
                   3110:):         $result = '<div class="LC_left_float">';
                   3111:):         my $list;
                   3112:):         my $numversions = 0;
                   3113:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3114:):             if ($i == $current) {
                   3115:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   3116:):                     next;
                   3117:):                 } else {
                   3118:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3119:):                     $numversions ++;
                   3120:):                 }
                   3121:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3122:):                 unless ($i == $env{'form.previousversion'}) {
                   3123:):                     $numversions ++;
                   3124:):                 }
                   3125:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3126:):             }
                   3127:):         }
                   3128:):         if ($numversions) {
                   3129:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3130:):             $result .=
                   3131:):                 '<form name="getprev" method="post" action=""'.
                   3132:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3133:):                 &Apache::loncommon::start_data_table().
                   3134:):                 &Apache::loncommon::start_data_table_row().
                   3135:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3136:):                 '<td><select name="version">'.
                   3137:):                 '<option>'.&mt('Select').'</option>'.
                   3138:):                 $list.
                   3139:):                 '</select></td>'.
                   3140:):                 &Apache::loncommon::end_data_table_row();
                   3141:):             unless ($nomenu) {
                   3142:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3143:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3144:):                 '<td><span class="LC_nobreak">'.
                   3145:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3146:):                 &mt('Yes').'</label>'.
                   3147:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3148:):                 '</span></td>'.
                   3149:):                 &Apache::loncommon::end_data_table_row();
                   3150:):             }
                   3151:):             $result .=
                   3152:):                 &Apache::loncommon::start_data_table_row().
                   3153:):                 '<th align="left">&nbsp;</th>'.
                   3154:):                 '<td>'.
                   3155:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3156:):                 '</td>'.
                   3157:):                 &Apache::loncommon::end_data_table_row().
                   3158:):                 &Apache::loncommon::end_data_table().
                   3159:):                 '</form>';
                   3160:):             $js = &previous_display_javascript($nomenu,$current);
                   3161:):         } elsif ($displayed && $nomenu) {
                   3162:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3163:):         } else {
                   3164:):             $result .= &mt('No previous versions to show for this student');
                   3165:):         }
                   3166:):         $result .= '</div>';
                   3167:):     }
                   3168:):     return ($current,$displayed,$result,$js);
                   3169:): }
                   3170:): 
                   3171:): sub previous_display_javascript {
                   3172:):     my ($nomenu,$current) = @_;
                   3173:):     my $js = <<"JSONE";
                   3174:): <script type="text/javascript">
                   3175:): // <![CDATA[
                   3176:): function previousVersion(uname,udom,symb) {
                   3177:):     var current = '$current';
                   3178:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3179:):     var prevstr = new RegExp("^\\\\d+\$");
                   3180:):     if (!prevstr.test(version)) {
                   3181:):         return false;
                   3182:):     }
                   3183:):     var url = '';
                   3184:):     if (version == current) {
                   3185:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3186:):     } else {
                   3187:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3188:):     }
                   3189:): JSONE
                   3190:):     if ($nomenu) {
                   3191:):         $js .= <<"JSTWO";
                   3192:):     document.location.href = url;
                   3193:): JSTWO
                   3194:):     } else {
                   3195:):         $js .= <<"JSTHREE";
                   3196:):     var newwin = 0;
                   3197:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3198:):         if (document.getprev.prevwin[i].checked == true) {
                   3199:):             newwin = document.getprev.prevwin[i].value;
                   3200:):         }
                   3201:):     }
                   3202:):     if (newwin == 1) {
                   3203:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3204:):         url = url+'&inhibitmenu=yes';
                   3205:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3206:):             previousWin = window.open(url,'',options,1);
                   3207:):         } else {
                   3208:):             previousWin.location.href = url;
                   3209:):         }
                   3210:):         previousWin.focus();
                   3211:):         return false;
                   3212:):     } else {
                   3213:):         document.location.href = url;
                   3214:):         return false;
                   3215:):     }
                   3216:): JSTHREE
                   3217:):     }
                   3218:):     $js .= <<"ENDJS";
                   3219:):     return false;
                   3220:): }
                   3221:): // ]]>
                   3222:): </script>
                   3223:): ENDJS
                   3224:): 
                   3225:): }
                   3226:): 
1.44      ng       3227: #--- Called from submission routine
1.38      ng       3228: sub processHandGrade {
1.596.2.12.2.  1(raebur 3229:0):     my ($request,$symb) = @_;
1.324     albertel 3230:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3231:     my $button = $env{'form.gradeOpt'};
                   3232:     my $ngrade = $env{'form.NCT'};
                   3233:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3234:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3235:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  8(raebur 3236:1):     my ($res_error,%queueable);
                   3237:1):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3238:1):     if ($res_error) {
                   3239:1):         $request->print(&navmap_errormsg());
                   3240:1):         return;
                   3241:1):     } else {
                   3242:1):         foreach my $part (@{$partlist}) {
                   3243:1):             if (ref($responseType->{$part}) eq 'HASH') {
                   3244:1):                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3245:1):                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3246:1):                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3247:1):                         $queueable{$part} = 1;
                   3248:1):                         last;
                   3249:1):                     }
                   3250:1):                 }
                   3251:1):             }
                   3252:1):         }
                   3253:1):     }
1.301     albertel 3254: 
1.44      ng       3255:     if ($button eq 'Save & Next') {
                   3256: 	my $ctr = 0;
                   3257: 	while ($ctr < $ngrade) {
1.257     albertel 3258: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3259:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
          8(raebur 3260:1):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3261: 	    if ($errorflag eq 'no_score') {
                   3262: 		$ctr++;
                   3263: 		next;
                   3264: 	    }
1.104     albertel 3265: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3266:4):                 $request->print(
                   3267:4):                     '<span class="LC_error">'
                   3268:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3269:4):                    .'</span>');
1.104     albertel 3270: 		$ctr++;
                   3271: 		next;
                   3272: 	    }
1.596.2.12.2.  1(raebur 3273:5):             if ($numhidden) {
                   3274:5):                 $request->print(
                   3275:5):                     '<span class="LC_info">'
                   3276:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3277:5):                    .'</span><br />');
                   3278:5):             }
1.257     albertel 3279: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3280: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3281: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3282:             my ($feedurl,$showsymb) =
                   3283: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3284: 	    my $messagetail;
1.62      albertel 3285: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3286: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3287: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3288: 		$subject.=' ['.$restitle.']';
1.44      ng       3289: 		my (@msgnum) = split(/,/,$includemsg);
                   3290: 		foreach (@msgnum) {
1.257     albertel 3291: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3292: 		}
1.80      ng       3293: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3294: 		if ($env{'form.withgrades'.$ctr}) {
                   3295: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3296: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3297:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3298: 		}
                   3299: 		$msgstatus = 
                   3300:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3301: 						     $message.$messagetail,
1.418     albertel 3302:                                                      undef,$feedurl,undef,
1.386     raeburn  3303:                                                      undef,undef,$showsymb,
                   3304:                                                      $restitle);
1.574     bisitz   3305: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3306: 				$msgstatus.'<br />');
1.44      ng       3307: 	    }
1.257     albertel 3308: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3309: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3310: 		foreach my $collabstr (@collabstrs) {
                   3311: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3312: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3313: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3314: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.596.2.12.2.  8(raebur 3315:1): 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3316: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3317: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3318: 			    next;
1.418     albertel 3319: 			} elsif ($message ne '') {
                   3320: 			    my ($baseurl,$showsymb) = 
                   3321: 				&get_feedurl_and_symb($symb,$collaborator,
                   3322: 						      $udom);
                   3323: 			    if ($env{'form.withgrades'.$ctr}) {
                   3324: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3325:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3326: 			    }
1.418     albertel 3327: 			    $msgstatus = 
                   3328: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3329: 			}
1.44      ng       3330: 		    }
                   3331: 		}
                   3332: 	    }
                   3333: 	    $ctr++;
                   3334: 	}
                   3335:     }
                   3336: 
1.596.2.12.2.  1(raebur 3337:0):     my %keyhash = ();
                   3338:0):     if ($numessay) {
1.119     ng       3339: 	# Keywords sorted in alphabatical order
1.257     albertel 3340: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3341: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3342:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3343: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3344: 	$env{'form.keywords'} = join(' ',@keywords);
                   3345: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3346: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3347: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3348: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3349: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3350:0):     }
1.119     ng       3351: 
1.596.2.12.2.  1(raebur 3352:0):     if ($env{'form.compmsg'}) {
1.119     ng       3353: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3354: 	# New messages are saved in env for the next student.
1.119     ng       3355: 	# All messages are saved in nohist_handgrade.db
                   3356: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3357: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3358: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3359: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3360: 		$idx++;
                   3361: 	    }
                   3362: 	    $ctr++;
1.41      ng       3363: 	}
1.119     ng       3364: 	$ctr = 0;
                   3365: 	while ($ctr < $ngrade) {
1.257     albertel 3366: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3367: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3368: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3369: 		$idx++;
                   3370: 	    }
                   3371: 	    $ctr++;
1.41      ng       3372: 	}
1.257     albertel 3373: 	$env{'form.savemsgN'} = --$idx;
                   3374: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3375:0):     }
                   3376:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3377: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3378: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3379:     }
1.596.2.12.2.  1(raebur 3380:0): 
1.44      ng       3381:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3382:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3383:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3384: 	my ($ctr,$total) = (0,0);
                   3385: 	while ($ctr < $ngrade) {
1.257     albertel 3386: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3387: 	    $ctr++;
                   3388: 	}
1.257     albertel 3389: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3390: 	$ctr = 0;
                   3391: 	while ($ctr < $total) {
1.257     albertel 3392: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3393: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3394: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3395:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3396: 	    $ctr++;
                   3397: 	}
                   3398: 	return '';
                   3399:     }
1.36      ng       3400: 
1.44      ng       3401:     # Get the next/previous one or group of students
1.257     albertel 3402:     my $firststu = $env{'form.unamedom0'};
                   3403:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3404:     my $ctr = 2;
1.41      ng       3405:     while ($laststu eq '') {
1.257     albertel 3406: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3407: 	$ctr++;
                   3408: 	$laststu = $firststu if ($ctr > $ngrade);
                   3409:     }
1.44      ng       3410: 
1.41      ng       3411:     my (@parsedlist,@nextlist);
                   3412:     my ($nextflg) = 0;
1.524     raeburn  3413:     foreach my $item (sort 
1.294     albertel 3414: 	     {
                   3415: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3416: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3417: 		 }
                   3418: 		 return $a cmp $b;
                   3419: 	     } (keys(%$fullname))) {
1.41      ng       3420: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3421: 	    push(@parsedlist,$item);
1.41      ng       3422: 	}
1.524     raeburn  3423: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3424: 	if ($button eq 'Previous') {
1.524     raeburn  3425: 	    last if ($item eq $firststu);
                   3426: 	    push(@parsedlist,$item);
1.41      ng       3427: 	}
                   3428:     }
                   3429:     $ctr = 0;
                   3430:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3431:     foreach my $student (@parsedlist) {
1.257     albertel 3432: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3433: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3434: 	
                   3435: 	if ($submitonly eq 'queued') {
                   3436: 	    my %queue_status = 
                   3437: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3438: 							$udom,$uname);
                   3439: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3440: 	}
                   3441: 
1.156     albertel 3442: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3443: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3444: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3445: 	    my $submitted = 0;
1.248     albertel 3446: 	    my $ungraded = 0;
                   3447: 	    my $incorrect = 0;
1.524     raeburn  3448: 	    foreach my $item (keys(%status)) {
                   3449: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3450: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3451: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3452: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3453: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3454: 		    $submitted = 0;
                   3455: 		}
1.41      ng       3456: 	    }
1.156     albertel 3457: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3458: 				     $submitonly eq 'incorrect' ||
                   3459: 				     $submitonly eq 'graded'));
1.248     albertel 3460: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3461: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3462: 	}
1.524     raeburn  3463: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3464: 	last if ($ctr == $ntstu);
1.41      ng       3465: 	$ctr++;
                   3466:     }
1.36      ng       3467: 
1.41      ng       3468:     $ctr = 0;
                   3469:     my $total = scalar(@nextlist)-1;
1.39      ng       3470: 
1.524     raeburn  3471:     foreach (sort(@nextlist)) {
1.41      ng       3472: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3473: 	$env{'form.student'}  = $uname;
                   3474: 	$env{'form.userdom'}  = $udom;
                   3475: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3476:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3477: 	$ctr++;
                   3478:     }
                   3479:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3480:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3481: 	$request->print($the_end);
                   3482:     }
                   3483:     return '';
1.38      ng       3484: }
1.36      ng       3485: 
1.44      ng       3486: #---- Save the score and award for each student, if changed
1.38      ng       3487: sub saveHandGrade {
1.596.2.12.2.  8(raebur 3488:1):     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3489:     my @version_parts;
1.104     albertel 3490:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3491: 					   $env{'request.course.id'});
1.104     albertel 3492:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3493:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3494:     my @parts_graded;
1.77      ng       3495:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3496:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3497:     my %aggregate = ();
                   3498:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3499:5):     if ($env{'form.HIDE'.$newflg}) {
                   3500:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3501:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3502:5):         $totchg += $numchgs;
                   3503:5):     }
1.301     albertel 3504:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3505:     foreach my $new_part (@parts) {
1.337     banghart 3506: 	#collaborator ($submi may vary for different parts
1.259     banghart 3507: 	if ($submitter && $new_part ne $part) { next; }
                   3508: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3509: 	if ($dropMenu eq 'excused') {
1.259     banghart 3510: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3511: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3512: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3513: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3514: 		}
1.364     banghart 3515: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3516: 	    }
1.125     ng       3517: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3518: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3519: 	    foreach my $key (keys(%record)) {
1.259     banghart 3520: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3521: 	    }
1.259     banghart 3522: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3523: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3524:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3525: 
                   3526:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3527: 					       [$new_part]);
                   3528:             my $aggtries =$totaltries;
1.269     raeburn  3529:             if ($last_resets{$new_part}) {
1.270     albertel 3530:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3531: 					   $new_part);
1.269     raeburn  3532:             }
1.270     albertel 3533: 
                   3534:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3535:             if ($aggtries > 0) {
1.327     albertel 3536:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3537:                 $aggregateflag = 1;
                   3538:             }
1.125     ng       3539: 	} elsif ($dropMenu eq '') {
1.259     banghart 3540: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3541: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3542: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3543: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3544: 		next;
                   3545: 	    }
1.259     banghart 3546: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3547: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3548: 	    my $partial= $pts/$wgt;
1.259     banghart 3549: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3550: 		#do not update score for part if not changed.
1.346     banghart 3551:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3552: 		next;
1.251     banghart 3553: 	    } else {
1.524     raeburn  3554: 	        push(@parts_graded,$new_part);
1.153     albertel 3555: 	    }
1.259     banghart 3556: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3557: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3558: 	    }
1.259     banghart 3559: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3560: 	    if ($partial == 0) {
1.153     albertel 3561: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3562: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3563: 		}
1.41      ng       3564: 	    } else {
1.153     albertel 3565: 		if ($record{$reckey} ne 'correct_by_override') {
                   3566: 		    $newrecord{$reckey} = 'correct_by_override';
                   3567: 		}
                   3568: 	    }	    
                   3569: 	    if ($submitter && 
1.259     banghart 3570: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3571: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3572: 	    }
1.259     banghart 3573: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3574: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3575: 	}
1.259     banghart 3576: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3577: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3578: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3579: 	        $dropMenu eq 'reset status')
                   3580: 	   {
1.524     raeburn  3581: 	    push(@version_parts,$new_part);
1.259     banghart 3582: 	}
1.41      ng       3583:     }
1.301     albertel 3584:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3585:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3586: 
1.344     albertel 3587:     if (%newrecord) {
                   3588:         if (@version_parts) {
1.364     banghart 3589:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3590:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3591: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3592: 	    foreach my $new_part (@version_parts) {
                   3593: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3594: 				$new_part,\%newrecord);
                   3595: 	    }
1.259     banghart 3596:         }
1.44      ng       3597: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3598: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3599: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.596.2.12.2.  8(raebur 3600:1): 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3601:     }
1.269     raeburn  3602:     if ($aggregateflag) {
                   3603:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3604: 			      $cdom,$cnum);
1.269     raeburn  3605:     }
1.596.2.12.2.  1(raebur 3606:5):     return ('',$pts,$wgt,$totchg);
                   3607:5): }
                   3608:5): 
                   3609:5): sub makehidden {
                   3610:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3611:5):     return unless (ref($record) eq 'HASH');
                   3612:5):     my %modified;
                   3613:5):     my $numchanged = 0;
                   3614:5):     if (exists($record->{$version.':keys'})) {
                   3615:5):         my $partsregexp = $parts;
                   3616:5):         $partsregexp =~ s/,/|/g;
                   3617:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3618:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3619:5):                  my $item = $1;
                   3620:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3621:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3622:5):                  }
                   3623:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3624:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3625:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3626:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3627:5):             }
                   3628:5):         }
                   3629:5):         if (keys(%modified)) {
                   3630:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3631:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3632:5):                 $numchanged ++;
                   3633:5):             }
                   3634:5):         }
                   3635:5):     }
                   3636:5):     return $numchanged;
1.36      ng       3637: }
1.322     albertel 3638: 
1.380     albertel 3639: sub check_and_remove_from_queue {
1.596.2.12.2.  8(raebur 3640:1):     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3641:     my @ungraded_parts;
                   3642:     foreach my $part (@{$parts}) {
                   3643: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3644: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3645: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3646: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3647: 		) {
1.596.2.12.2.  8(raebur 3648:1):             if ($queueable->{$part}) {
                   3649:1): 	        push(@ungraded_parts, $part);
                   3650:1):             }
1.380     albertel 3651: 	}
                   3652:     }
                   3653:     if ( !@ungraded_parts ) {
                   3654: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3655: 					       $cnum,$domain,$stuname);
                   3656:     }
                   3657: }
                   3658: 
1.337     banghart 3659: sub handback_files {
                   3660:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3661:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3662:     my $res_error;
                   3663:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3664:     if ($res_error) {
                   3665:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3666:         return;
                   3667:     }
1.596.2.4  raeburn  3668:     my @handedback;
                   3669:     my $file_msg;
1.375     albertel 3670:     my @part_response_id = &flatten_responseType($responseType);
                   3671:     foreach my $part_response_id (@part_response_id) {
                   3672:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3673: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3674:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3675:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3676:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3677: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3678:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3679:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3680:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3681:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3682: 		        &file_name_version_ext($answer_file);
1.355     banghart 3683: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3684:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3685:):                     my ($dir_list,$listerror) =
                   3686:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3687:):                                                  $domain,$stuname,$getpropath);
                   3688:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3689:3):                     # fix filename
1.355     banghart 3690:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3691:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3692:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3693:             	                                $save_file_name);
1.337     banghart 3694:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3695:                         $request->print('<br /><span class="LC_error">'.
                   3696:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3697:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3698:                                         '</span>');
1.356     banghart 3699:                     } else {
1.360     banghart 3700:                         # mark the file as read only
1.596.2.4  raeburn  3701:                         push(@handedback,$save_file_name);
1.367     albertel 3702: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3703: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3704: 			}
                   3705:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3706: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3707: 
1.337     banghart 3708:                     }
1.596.2.12.2.  3(raebur 3709:3):                     $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>'));
1.337     banghart 3710:                 }
                   3711:             }
                   3712:         }
1.596.2.4  raeburn  3713:     }
                   3714:     if (@handedback > 0) {
                   3715:         $request->print('<br />');
                   3716:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3717:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3718:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3719:         my ($subject,$message);
                   3720:         if (scalar(@handedback) == 1) {
                   3721:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3722:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3723:         } else {
                   3724:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3725:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3726:         }
                   3727:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3728:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3729:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3730:         my ($feedurl,$showsymb) =
                   3731:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3732:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3733:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3734:         my $msgstatus =
                   3735:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3736:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3737:                  $restitle);
                   3738:         if ($msgstatus) {
                   3739:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3740:         }
                   3741:     }
1.338     banghart 3742:     return;
1.337     banghart 3743: }
                   3744: 
1.418     albertel 3745: sub get_feedurl_and_symb {
                   3746:     my ($symb,$uname,$udom) = @_;
                   3747:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3748:     $url = &Apache::lonnet::clutter($url);
                   3749:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3750: 					$symb,$udom,$uname);
                   3751:     if ($encrypturl =~ /^yes$/i) {
                   3752: 	&Apache::lonenc::encrypted(\$url,1);
                   3753: 	&Apache::lonenc::encrypted(\$symb,1);
                   3754:     }
                   3755:     return ($url,$symb);
                   3756: }
                   3757: 
1.313     banghart 3758: sub get_submitted_files {
                   3759:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3760:     my @files;
                   3761:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3762:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3763:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3764:     	    push(@files,$file_url.$file);
                   3765:         }
                   3766:     }
                   3767:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3768:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3769:     }
                   3770:     return (\@files);
                   3771: }
1.322     albertel 3772: 
1.269     raeburn  3773: # ----------- Provides number of tries since last reset.
                   3774: sub get_num_tries {
                   3775:     my ($record,$last_reset,$part) = @_;
                   3776:     my $timestamp = '';
                   3777:     my $num_tries = 0;
                   3778:     if ($$record{'version'}) {
                   3779:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3780:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3781:                 $timestamp = $$record{$version.':timestamp'};
                   3782:                 if ($timestamp > $last_reset) {
                   3783:                     $num_tries ++;
                   3784:                 } else {
                   3785:                     last;
                   3786:                 }
                   3787:             }
                   3788:         }
                   3789:     }
                   3790:     return $num_tries;
                   3791: }
                   3792: 
                   3793: # ----------- Determine decrements required in aggregate totals 
                   3794: sub decrement_aggs {
                   3795:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3796:     my %decrement = (
                   3797:                         attempts => 0,
                   3798:                         users => 0,
                   3799:                         correct => 0
                   3800:                     );
                   3801:     $decrement{'attempts'} = $aggtries;
                   3802:     if ($solvedstatus =~ /^correct/) {
                   3803:         $decrement{'correct'} = 1;
                   3804:     }
                   3805:     if ($aggtries == $totaltries) {
                   3806:         $decrement{'users'} = 1;
                   3807:     }
1.524     raeburn  3808:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3809:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3810:     }
                   3811:     return;
                   3812: }
                   3813: 
                   3814: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3815: sub get_last_resets {
1.270     albertel 3816:     my ($symb,$courseid,$partids) =@_;
                   3817:     my %last_resets;
1.269     raeburn  3818:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3819:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3820:     my @keys;
                   3821:     foreach my $part (@{$partids}) {
                   3822: 	push(@keys,"$symb\0$part\0resettime");
                   3823:     }
                   3824:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3825: 				     $cdom,$cname);
                   3826:     foreach my $part (@{$partids}) {
                   3827: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3828:     }
1.270     albertel 3829:     return %last_resets;
1.269     raeburn  3830: }
                   3831: 
1.251     banghart 3832: # ----------- Handles creating versions for portfolio files as answers
                   3833: sub version_portfiles {
1.343     banghart 3834:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3835:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3836:     my @returned_keys;
1.255     banghart 3837:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3838:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3839:     foreach my $key (keys(%$record)) {
1.259     banghart 3840:         my $new_portfiles;
1.263     banghart 3841:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3842:             my @versioned_portfiles;
1.367     albertel 3843:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3844:             foreach my $file (@portfiles) {
1.306     banghart 3845:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3846:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3847: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3848: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3849:):                 my $getpropath = 1;
                   3850:):                 my ($dir_list,$listerror) =
                   3851:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3852:):                                              $stu_name,$getpropath);
                   3853:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3854:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3855:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3856:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3857:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3858:                         [$directory.$new_answer],
1.306     banghart 3859:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3860:                 }
1.252     banghart 3861:             }
1.343     banghart 3862:             $$record{$key} = join(',',@versioned_portfiles);
                   3863:             push(@returned_keys,$key);
1.251     banghart 3864:         }
                   3865:     } 
1.343     banghart 3866:     return (@returned_keys);   
1.305     banghart 3867: }
                   3868: 
1.307     banghart 3869: sub get_next_version {
1.341     banghart 3870:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3871:     my $version;
1.596.2.12.2.  (raeburn 3872:):     if (ref($dir_list) eq 'ARRAY') {
                   3873:):         foreach my $row (@{$dir_list}) {
                   3874:):             my ($file) = split(/\&/,$row,2);
                   3875:):             my ($file_name,$file_version,$file_ext) =
                   3876:): 	        &file_name_version_ext($file);
                   3877:):             if (($file_name eq $answer_name) && 
                   3878:): 	        ($file_ext eq $answer_ext)) {
                   3879:):                 # gets here if filename and extension match, 
                   3880:):                 # regardless of version
1.307     banghart 3881:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3882:):                     # a versioned file is found  so save it for later
                   3883:):                     if ($file_version > $version) {
                   3884:): 		        $version = $file_version;
                   3885:):                     }
1.307     banghart 3886: 	        }
                   3887:             }
                   3888:         }
1.596.2.12.2.  (raeburn 3889:):     }
1.307     banghart 3890:     $version ++;
                   3891:     return($version);
                   3892: }
                   3893: 
1.305     banghart 3894: sub version_selected_portfile {
1.306     banghart 3895:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3896:     my ($answer_name,$answer_ver,$answer_ext) =
                   3897:         &file_name_version_ext($file_name);
                   3898:     my $new_answer;
                   3899:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3900:     if($env{'form.copy'} eq '-1') {
                   3901:         $new_answer = 'problem getting file';
                   3902:     } else {
                   3903:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3904:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3905:                             $stu_name,$domain,'copy',
                   3906: 		        '/portfolio'.$directory.$new_answer);
                   3907:     }    
                   3908:     return ($new_answer);
1.251     banghart 3909: }
                   3910: 
1.304     albertel 3911: sub file_name_version_ext {
                   3912:     my ($file)=@_;
                   3913:     my @file_parts = split(/\./, $file);
                   3914:     my ($name,$version,$ext);
                   3915:     if (@file_parts > 1) {
                   3916: 	$ext=pop(@file_parts);
                   3917: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3918: 	    $version=pop(@file_parts);
                   3919: 	}
                   3920: 	$name=join('.',@file_parts);
                   3921:     } else {
                   3922: 	$name=join('.',@file_parts);
                   3923:     }
                   3924:     return($name,$version,$ext);
                   3925: }
                   3926: 
1.44      ng       3927: #--------------------------------------------------------------------------------------
                   3928: #
                   3929: #-------------------------- Next few routines handles grading by section or whole class
                   3930: #
                   3931: #--- Javascript to handle grading by section or whole class
1.42      ng       3932: sub viewgrades_js {
                   3933:     my ($request) = shift;
                   3934: 
1.539     riegler  3935:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3936:6):     &js_escape(\$alertmsg);
          1(raebur 3937:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3938:    function writePoint(partid,weight,point) {
1.125     ng       3939: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3940: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3941: 	if (point == "textval") {
1.125     ng       3942: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3943: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3944: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3945: 		var resetbox = false;
                   3946: 		for (var i=0; i<radioButton.length; i++) {
                   3947: 		    if (radioButton[i].checked) {
                   3948: 			textbox.value = i;
                   3949: 			resetbox = true;
                   3950: 		    }
                   3951: 		}
                   3952: 		if (!resetbox) {
                   3953: 		    textbox.value = "";
                   3954: 		}
                   3955: 		return;
                   3956: 	    }
1.109     matthew  3957: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3958: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3959: 				   ") greater than the weight for the part. Accept?");
                   3960: 		if (resp == false) {
                   3961: 		    textbox.value = "";
                   3962: 		    return;
                   3963: 		}
                   3964: 	    }
1.42      ng       3965: 	    for (var i=0; i<radioButton.length; i++) {
                   3966: 		radioButton[i].checked=false;
1.109     matthew  3967: 		if (parseFloat(point) == i) {
1.42      ng       3968: 		    radioButton[i].checked=true;
                   3969: 		}
                   3970: 	    }
1.41      ng       3971: 
1.42      ng       3972: 	} else {
1.125     ng       3973: 	    textbox.value = parseFloat(point);
1.42      ng       3974: 	}
1.41      ng       3975: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3976: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3977: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3978: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3979: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3980: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3981: 	    if (saveval != "correct") {
                   3982: 		scorename.value = point;
1.43      ng       3983: 		if (selname[0].selected != true) {
                   3984: 		    selname[0].selected = true;
                   3985: 		}
1.42      ng       3986: 	    }
                   3987: 	}
1.125     ng       3988: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3989:     }
                   3990: 
                   3991:     function writeRadText(partid,weight) {
1.125     ng       3992: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3993: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3994:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3995: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3996: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3997: 	    for (var i=0; i<radioButton.length; i++) {
                   3998: 		radioButton[i].checked=false;
                   3999: 
                   4000: 	    }
                   4001: 	    textbox.value = "";
                   4002: 
                   4003: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4004: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4005: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4006: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4007: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4008: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4009: 		if ((saveval != "correct") || override) {
1.42      ng       4010: 		    scorename.value = "";
1.125     ng       4011: 		    if (selval[1].selected) {
                   4012: 			selname[1].selected = true;
                   4013: 		    } else {
                   4014: 			selname[2].selected = true;
                   4015: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4016: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4017: 		    }
1.42      ng       4018: 		}
                   4019: 	    }
1.43      ng       4020: 	} else {
                   4021: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4022: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4023: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4024: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4025: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4026: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4027: 		if ((saveval != "correct") || override) {
1.125     ng       4028: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4029: 		    selname[0].selected = true;
                   4030: 		}
                   4031: 	    }
                   4032: 	}	    
1.42      ng       4033:     }
                   4034: 
                   4035:     function changeSelect(partid,user) {
1.125     ng       4036: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4037: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4038: 	var point  = textbox.value;
1.125     ng       4039: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4040: 
1.109     matthew  4041: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4042: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4043: 	    textbox.value = "";
                   4044: 	    return;
                   4045: 	}
1.109     matthew  4046: 	if (parseFloat(point) > parseFloat(weight)) {
                   4047: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4048: 			       ") greater than the weight of the part. Accept?");
                   4049: 	    if (resp == false) {
                   4050: 		textbox.value = "";
                   4051: 		return;
                   4052: 	    }
                   4053: 	}
1.42      ng       4054: 	selval[0].selected = true;
                   4055:     }
                   4056: 
                   4057:     function changeOneScore(partid,user) {
1.125     ng       4058: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4059: 	if (selval[1].selected || selval[2].selected) {
                   4060: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4061: 	    if (selval[2].selected) {
                   4062: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4063: 	    }
1.269     raeburn  4064:         }
1.42      ng       4065:     }
                   4066: 
                   4067:     function resetEntry(numpart) {
                   4068: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4069: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4070: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4071: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4072: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4073: 	    for (var i=0; i<radioButton.length; i++) {
                   4074: 		radioButton[i].checked=false;
                   4075: 
                   4076: 	    }
                   4077: 	    textbox.value = "";
                   4078: 	    selval[0].selected = true;
                   4079: 
                   4080: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4081: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4082: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4083: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4084: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4085: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4086: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4087: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4088: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4089: 		if (saveselval == "excused") {
1.43      ng       4090: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4091: 		} else {
1.43      ng       4092: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4093: 		}
                   4094: 	    }
1.41      ng       4095: 	}
1.42      ng       4096:     }
                   4097: 
1.41      ng       4098: VIEWJAVASCRIPT
1.42      ng       4099: }
                   4100: 
1.44      ng       4101: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4102: sub viewgrades {
1.596.2.12.2.  1(raebur 4103:0):     my ($request,$symb) = @_;
          0.2.4(ra 4104:ul-23):     my ($is_tool,$toolsymb);
                   4105:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4106:ul-23):         $is_tool = 1;
                   4107:ul-23):         $toolsymb = $symb;
                   4108:ul-23):     }
1.42      ng       4109:     &viewgrades_js($request);
1.41      ng       4110: 
1.168     albertel 4111:     #need to make sure we have the correct data for later EXT calls, 
                   4112:     #thus invalidate the cache
                   4113:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4114:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4115:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4116:     &Apache::lonnet::clear_EXT_cache_status();
                   4117: 
1.398     albertel 4118:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4119: 
                   4120:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4121:     $result.=&jscriptNform($symb);
1.41      ng       4122: 
1.44      ng       4123:     #beginning of class grading form
1.442     banghart 4124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4125:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4126: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4127: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4128: 	&build_section_inputs().
1.442     banghart 4129: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4130: 
1.596.2.12.2.  7(raebur 4131:6):     #retrieve selected groups
                   4132:6):     my (@groups,$group_display);
          8(raebur 4133:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 4134:6):     if (grep(/^all$/,@groups)) {
                   4135:6):         @groups = ('all');
                   4136:6):     } elsif (grep(/^none$/,@groups)) {
                   4137:6):         @groups = ('none');
                   4138:6):     } elsif (@groups > 0) {
                   4139:6):         $group_display = join(', ',@groups);
                   4140:6):     }
                   4141:6): 
                   4142:6):     my ($common_header,$specific_header,@sections,$section_display);
          6(raebur 4143:1):     if ($env{'request.course.sec'} ne '') {
                   4144:1):         @sections = ($env{'request.course.sec'});
                   4145:1):     } else {
                   4146:1):         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4147:1):     }
                   4148:1): 
                   4149:1): # Check if Save button should be usable
                   4150:1):     my $disabled = ' disabled="disabled"';
                   4151:1):     if ($perm{'mgr'}) {
                   4152:1):         if (grep(/^all$/,@sections)) {
                   4153:1):             undef($disabled);
                   4154:1):         } else {
                   4155:1):             foreach my $sec (@sections) {
                   4156:1):                 if (&canmodify($sec)) {
                   4157:1):                     undef($disabled);
                   4158:1):                     last;
                   4159:1):                 }
                   4160:1):             }
                   4161:1):         }
                   4162:1):     }
          7(raebur 4163:6):     if (grep(/^all$/,@sections)) {
                   4164:6):         @sections = ('all');
                   4165:6):         if ($group_display) {
                   4166:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4167:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4168:6):         } elsif (grep(/^none$/,@groups)) {
                   4169:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4170:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4171:6):         } else {
                   4172:6):             $common_header = &mt('Assign Common Grade to Class');
                   4173:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4174:6):         }
                   4175:6):     } elsif (grep(/^none$/,@sections)) {
                   4176:6):         @sections = ('none');
                   4177:6):         if ($group_display) {
                   4178:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4179:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4180:6):         } elsif (grep(/^none$/,@groups)) {
                   4181:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4182:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4183:6):         } else {
                   4184:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4185:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4186:6):         }
                   4187:6):     } else {
                   4188:6):         $section_display = join (", ",@sections);
                   4189:6):         if ($group_display) {
                   4190:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4191:6):                                  $section_display,$group_display);
                   4192:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4193:6):                                    $section_display,$group_display);
                   4194:6):         } elsif (grep(/^none$/,@groups)) {
                   4195:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4196:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4197:6):         } else {
                   4198:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4199:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4200:6):         }
1.52      albertel 4201:     }
1.596.2.12.2.  7(raebur 4202:6):     my %submit_types = &substatus_options();
                   4203:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4204:6): 
                   4205:6):     if ($env{'form.submitonly'} eq 'all') {
                   4206:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4207:6):     } else {
          0.2.4(ra 4208:ul-23):         my $text;
                   4209:ul-23):         if ($is_tool) {
                   4210:ul-23):             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4211:ul-23):         } else {
                   4212:ul-23):             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4213:ul-23):         }
                   4214:ul-23):         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
          7(raebur 4215:6):     }
                   4216:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4217:     #radio buttons/text box for assigning points for a section or class.
                   4218:     #handles different parts of a problem
1.582     raeburn  4219:     my $res_error;
                   4220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4221:     if ($res_error) {
                   4222:         return &navmap_errormsg();
                   4223:     }
1.42      ng       4224:     my %weight = ();
                   4225:     my $ctsparts = 0;
1.45      ng       4226:     my %seen = ();
1.596.2.12.2.  0.2.4(ra 4227:ul-23):     my @part_response_id;
                   4228:ul-23):     if ($is_tool) {
                   4229:ul-23):         @part_response_id = ([0,'']);
                   4230:ul-23):     } else {
                   4231:ul-23):         @part_response_id = &flatten_responseType($responseType);
                   4232:ul-23):     }
1.375     albertel 4233:     foreach my $part_response_id (@part_response_id) {
                   4234:     	my ($partid,$respid) = @{ $part_response_id };
                   4235: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4236: 	next if $seen{$partid};
                   4237: 	$seen{$partid}++;
1.42      ng       4238: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4239: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4240: 
1.324     albertel 4241: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4242: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4243: 	my $ctr = 0;
1.42      ng       4244: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4245: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4246: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4247: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4248: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4249: 	    $ctr++;
                   4250: 	}
1.485     albertel 4251: 	$radio.='</tr></table>';
                   4252: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4253: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4254: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4255: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4256:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4257:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4258:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4259: 		$weight{$partid}.')"> '.
1.401     albertel 4260: 	    '<option selected="selected"> </option>'.
1.485     albertel 4261: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4262: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4263: 	    '</select></td>'.
                   4264:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4265: 	$line.='<input type="hidden" name="partid_'.
                   4266: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4267: 	$line.='<input type="hidden" name="weight_'.
                   4268: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4269: 
                   4270: 	$result.=
                   4271: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4272: 	    '<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>'.
1.485     albertel 4273: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4274: 	$ctsparts++;
1.41      ng       4275:     }
1.474     albertel 4276:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4277: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4278:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4279: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4280: 
1.44      ng       4281:     #table listing all the students in a section/class
                   4282:     #header of table
1.596.2.12.2.  0.2.4(ra 4283:ul-23):     if ($env{'form.submitonly'} eq 'all') {
          7(raebur 4284:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4285:6):     } else {
          0.2.4(ra 4286:ul-23):         my $text;
                   4287:ul-23):         if ($is_tool) {
                   4288:ul-23):             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4289:ul-23):         } else {
                   4290:ul-23):             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4291:ul-23):         }
                   4292:ul-23):         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
          7(raebur 4293:6):     }
                   4294:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4295: 	      &Apache::loncommon::start_data_table_header_row().
                   4296: 	      '<th>'.&mt('No.').'</th>'.
                   4297: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4298:     my $partserror;
                   4299:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4300:     if ($partserror) {
                   4301:         return &navmap_errormsg();
                   4302:     }
1.324     albertel 4303:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4304:     my @partids = ();
1.41      ng       4305:     foreach my $part (@parts) {
1.596.2.12.2.  0.2.4(ra 4306:ul-23): 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4307:         my $narrowtext = &mt('Tries');
                   4308: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.596.2.12.2.  0.2.4(ra 4309:ul-23): 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4310: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4311:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4312:0): #
                   4313:0): # FIXME: Looks like $display looks at English text
                   4314:0): #
1.324     albertel 4315: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4316: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4317: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4318:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4319:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4320: 	    next;
1.485     albertel 4321: 	    
1.207     albertel 4322: 	} else {
1.485     albertel 4323: 	    if ($display =~ /Problem Status/) {
                   4324: 		my $grade_status_mt = &mt('Grade Status');
                   4325: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4326: 	    }
                   4327: 	    my $part_mt = &mt('Part:');
                   4328: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4329: 	}
1.485     albertel 4330: 
1.474     albertel 4331: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4332:     }
1.474     albertel 4333:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4334: 
1.270     albertel 4335:     my %last_resets = 
                   4336: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4337: 
1.41      ng       4338:     #get info for each student
1.44      ng       4339:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4340:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4341:     my $ctr = 0;
1.294     albertel 4342:     foreach (sort 
                   4343: 	     {
                   4344: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4345: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4346: 		 }
                   4347: 		 return $a cmp $b;
                   4348: 	     } (keys(%$fullname))) {
1.324     albertel 4349: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  0.2.4(ra 4350:ul-23): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4351:     }
1.474     albertel 4352:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4353:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.596.2.12.2.  6(raebur 4354:1):     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4355: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4356:6):     if ($ctr == 0) {
1.442     banghart 4357:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4358:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4359:6):                 '<span class="LC_warning">';
                   4360:6):         if ($env{'form.submitonly'} eq 'all') {
                   4361:6):             if (grep(/^all$/,@sections)) {
                   4362:6):                 if (grep(/^all$/,@groups)) {
                   4363:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4364:6):                                    $stu_status);
                   4365:6):                 } elsif (grep(/^none$/,@groups)) {
                   4366:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4367:6):                                    $stu_status);
                   4368:6):                 } else {
                   4369:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4370:6):                                    $group_display,$stu_status);
                   4371:6):                 }
                   4372:6):             } elsif (grep(/^none$/,@sections)) {
                   4373:6):                 if (grep(/^all$/,@groups)) {
                   4374:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4375:6):                                    $stu_status);
                   4376:6):                 } elsif (grep(/^none$/,@groups)) {
                   4377:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4378:6):                                    $stu_status);
                   4379:6):                 } else {
                   4380:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4381:6):                                    $group_display,$stu_status);
                   4382:6):                 }
                   4383:6):             } else {
                   4384:6):                 if (grep(/^all$/,@groups)) {
                   4385:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4386:6):                                    $section_display,$stu_status);
                   4387:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4388:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4389:6):                                    $section_display,$stu_status);
                   4390:6):                 } else {
                   4391:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4392:6):                                    $section_display,$group_display,$stu_status);
                   4393:6):                 }
                   4394:6):             }
                   4395:6):         } else {
                   4396:6):             if (grep(/^all$/,@sections)) {
                   4397:6):                 if (grep(/^all$/,@groups)) {
                   4398:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4399:6):                                    $stu_status,$submission_status);
                   4400:6):                 } elsif (grep(/^none$/,@groups)) {
                   4401:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4402:6):                                    $stu_status,$submission_status);
                   4403:6):                 } else {
                   4404:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4405:6):                                    $group_display,$stu_status,$submission_status);
                   4406:6):                 }
                   4407:6):             } elsif (grep(/^none$/,@sections)) {
                   4408:6):                 if (grep(/^all$/,@groups)) {
                   4409:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4410:6):                                    $stu_status,$submission_status);
                   4411:6):                 } elsif (grep(/^none$/,@groups)) {
                   4412:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4413:6):                                    $stu_status,$submission_status);
                   4414:6):                 } else {
                   4415:6):                     $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.',
                   4416:6):                                    $group_display,$stu_status,$submission_status);
                   4417:6):                 }
                   4418:6):             } else {
                   4419:6):                 if (grep(/^all$/,@groups)) {
                   4420:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4421:6):                                    $section_display,$stu_status,$submission_status);
                   4422:6):                 } elsif (grep(/^none$/,@groups)) {
                   4423:6):                     $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.',
                   4424:6):                                    $section_display,$stu_status,$submission_status);
                   4425:6):                 } else {
                   4426:6):                     $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.',
                   4427:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4428:6):                 }
                   4429:6):             }
                   4430:6): 	}
                   4431:6): 	$result .= '</span><br />';
1.96      albertel 4432:     }
1.41      ng       4433:     return $result;
                   4434: }
                   4435: 
1.596.2.12.2.  7(raebur 4436:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4437: sub viewstudentgrade {
1.596.2.12.2.  0.2.4(ra 4438:ul-23):     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4439:     my ($uname,$udom) = split(/:/,$student);
                   4440:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4441:6):     my $submitonly = $env{'form.submitonly'};
                   4442:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4443:6):         my %partstatus = ();
                   4444:6):         if (ref($parts) eq 'ARRAY') {
                   4445:6):             foreach my $apart (@{$parts}) {
                   4446:6):                 my ($part,$type) = &split_part_type($apart);
                   4447:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4448:6):                 $status = 'nothing' if ($status eq '');
                   4449:6):                 $partstatus{$part}      = $status;
                   4450:6):                 my $subkey = "resource.$part.submitted_by";
                   4451:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4452:6):             }
                   4453:6):             my $submitted = 0;
                   4454:6):             my $graded = 0;
                   4455:6):             my $incorrect = 0;
                   4456:6):             foreach my $key (keys(%partstatus)) {
                   4457:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4458:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4459:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4460:6): 
                   4461:6):                 my $partid = (split(/\./,$key))[1];
                   4462:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4463:6):                     $submitted = 0;
                   4464:6):                 }
                   4465:6):             }
                   4466:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4467:6):                                        $submitonly eq 'incorrect' ||
                   4468:6):                                        $submitonly eq 'graded'));
                   4469:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4470:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4471:6):         }
                   4472:6):     }
                   4473:6):     if ($submitonly eq 'queued') {
                   4474:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4475:6):         my %queue_status =
                   4476:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4477:6):                                                     $udom,$uname);
                   4478:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4479:6):     }
                   4480:6):     $$ctr++;
                   4481:6):     my %aggregates = ();
1.474     albertel 4482:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4483:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4484:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4485: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4486: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4487: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4488:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4489:     foreach my $apart (@$parts) {
                   4490: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4491: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4492:         $result.='<td align="center">';
1.269     raeburn  4493:         my ($aggtries,$totaltries);
                   4494:         unless (exists($aggregates{$part})) {
1.270     albertel 4495: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4496: 	    $aggtries = $totaltries;
1.269     raeburn  4497:             if ($$last_resets{$part}) {  
1.270     albertel 4498:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4499: 					   $part);
                   4500:             }
1.269     raeburn  4501:             $result.='<input type="hidden" name="'.
                   4502:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4503:             $result.='<input type="hidden" name="'.
                   4504:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4505:             $aggregates{$part} = 1;
                   4506:         }
1.41      ng       4507: 	if ($type eq 'awarded') {
1.320     albertel 4508: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4509: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4510: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4511: 	    $result.='<input type="text" name="'.
1.89      albertel 4512: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4513:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4514: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4515: 	} elsif ($type eq 'solved') {
                   4516: 	    my ($status,$foo)=split(/_/,$score,2);
                   4517: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4518: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4519: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4520: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4521: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4522:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4523: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4524: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4525: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4526: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4527: 	} else {
                   4528: 	    $result.='<input type="hidden" name="'.
                   4529: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4530: 		    "\n";
1.233     albertel 4531: 	    $result.='<input type="text" name="'.
1.122     ng       4532: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4533: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4534: 	}
                   4535:     }
1.474     albertel 4536:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4537:     return $result;
1.38      ng       4538: }
                   4539: 
1.44      ng       4540: #--- change scores for all the students in a section/class
                   4541: #    record does not get update if unchanged
1.38      ng       4542: sub editgrades {
1.596.2.12.2.  1(raebur 4543:0):     my ($request,$symb) = @_;
          0.2.4(ra 4544:ul-23):     my $toolsymb;
                   4545:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4546:ul-23):         $toolsymb = $symb;
                   4547:ul-23):     }
1.41      ng       4548: 
1.433     banghart 4549:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4550:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4551:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4552: 
1.477     albertel 4553:     my $result= &Apache::loncommon::start_data_table().
                   4554: 	&Apache::loncommon::start_data_table_header_row().
                   4555: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4556: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4557:     my %scoreptr = (
                   4558: 		    'correct'  =>'correct_by_override',
                   4559: 		    'incorrect'=>'incorrect_by_override',
                   4560: 		    'excused'  =>'excused',
                   4561: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4562:                     'credited' =>'credit_attempted',
1.43      ng       4563: 		    'nothing'  => '',
                   4564: 		    );
1.257     albertel 4565:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4566: 
1.44      ng       4567:     my (@partid);
                   4568:     my %weight = ();
1.54      albertel 4569:     my %columns = ();
1.44      ng       4570:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4571: 
1.582     raeburn  4572:     my $partserror;
                   4573:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4574:     if ($partserror) {
                   4575:         return &navmap_errormsg();
                   4576:     }
1.54      albertel 4577:     my $header;
1.257     albertel 4578:     while ($ctr < $env{'form.totalparts'}) {
                   4579: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4580: 	push(@partid,$partid);
1.257     albertel 4581: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4582: 	$ctr++;
1.54      albertel 4583:     }
1.324     albertel 4584:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4585:8):     my $totcolspan = 0;
1.54      albertel 4586:     foreach my $partid (@partid) {
1.478     albertel 4587: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4588: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4589: 	$columns{$partid}=2;
                   4590: 	foreach my $stores (@parts) {
                   4591: 	    my ($part,$type) = &split_part_type($stores);
                   4592: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4593: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.596.2.12.2.  0.2.4(ra 4594:ul-23): 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4595: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4596:             my $narrowtext = &mt('Tries');
                   4597: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4598: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4599: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4600: 	    $columns{$partid}+=2;
                   4601: 	}
1.596.2.12.2.  2(raebur 4602:8):         $totcolspan += $columns{$partid};
1.54      albertel 4603:     }
                   4604:     foreach my $partid (@partid) {
1.324     albertel 4605: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4606: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4607: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4608: 	    '</th>';
1.54      albertel 4609: 
1.44      ng       4610:     }
1.477     albertel 4611:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4612: 	&Apache::loncommon::start_data_table_header_row().
                   4613: 	$header.
                   4614: 	&Apache::loncommon::end_data_table_header_row();
                   4615:     my @noupdate;
1.126     ng       4616:     my ($updateCtr,$noupdateCtr) = (1,1);
1.596.2.12.2.  8(raebur 4617:1):     my ($got_types,%queueable);
1.257     albertel 4618:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4619: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4620: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4621: 	my %newrecord;
                   4622: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4623:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4624:8):         my $canmodify = &canmodify($usec);
                   4625:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4626:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4627:8):         if (!$canmodify) {
                   4628:8):             push(@noupdate,
                   4629:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4630:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4631:8):             next;
                   4632:8):         }
1.269     raeburn  4633:         my %aggregate = ();
                   4634:         my $aggregateflag = 0;
1.281     albertel 4635: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4636: 	foreach (@partid) {
1.257     albertel 4637: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4638: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4639: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4640: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4641: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4642: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4643: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4644: 	    my $score;
                   4645: 	    if ($partial eq '') {
1.257     albertel 4646: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4647: 	    } elsif ($partial > 0) {
                   4648: 		$score = 'correct_by_override';
                   4649: 	    } elsif ($partial == 0) {
                   4650: 		$score = 'incorrect_by_override';
                   4651: 	    }
1.257     albertel 4652: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4653: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4654: 
1.292     albertel 4655: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4656: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4657: 	    if ($dropMenu eq 'reset status' &&
                   4658: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4659: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4660: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4661: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4662: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4663: 		$updateflag = 1;
1.269     raeburn  4664:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4665:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4666:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4667:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4668:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4669:                     $aggregateflag = 1;
                   4670:                 }
1.139     albertel 4671: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4672: 		$updateflag = 1;
                   4673: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4674: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4675: 		$rec_update++;
1.125     ng       4676: 	    }
                   4677: 
1.93      albertel 4678: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4679: 		'<td align="center">'.$awarded.
                   4680: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4681: 
1.54      albertel 4682: 
                   4683: 	    my $partid=$_;
                   4684: 	    foreach my $stores (@parts) {
                   4685: 		my ($part,$type) = &split_part_type($stores);
                   4686: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4687: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4688: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4689: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4690: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4691: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4692: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4693: 		    $updateflag=1;
                   4694: 		}
1.93      albertel 4695: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4696: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4697: 	    }
1.44      ng       4698: 	}
1.477     albertel 4699: 	$line.="\n";
1.301     albertel 4700: 
                   4701: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4702: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4703: 
1.44      ng       4704: 	if ($updateflag) {
                   4705: 	    $count++;
1.257     albertel 4706: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4707: 				    $udom,$uname);
1.301     albertel 4708: 
                   4709: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4710: 					      $cnum,$udom,$uname)) {
                   4711: 		# need to figure out if should be in queue.
                   4712: 		my %record =  
                   4713: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4714: 					     $udom,$uname);
                   4715: 		my $all_graded = 1;
                   4716: 		my $none_graded = 1;
1.596.2.12.2.  8(raebur 4717:1):                 unless ($got_types) {
                   4718:1):                     my $error;
                   4719:1):                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4720:1):                     unless ($error) {
                   4721:1):                         foreach my $part (@parts) {
                   4722:1):                             if (ref($resptype->{$part}) eq 'HASH') {
                   4723:1):                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4724:1):                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4725:1):                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4726:1):                                         $queueable{$part} = 1;
                   4727:1):                                         last;
                   4728:1):                                     }
                   4729:1):                                 }
                   4730:1):                             }
                   4731:1):                         }
                   4732:1):                     }
                   4733:1):                     $got_types = 1;
                   4734:1):                 }
1.301     albertel 4735: 		foreach my $part (@parts) {
1.596.2.12.2.  8(raebur 4736:1):                     if ($queueable{$part}) {
                   4737:1): 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4738:1): 			    $all_graded = 0;
                   4739:1): 		        } else {
                   4740:1): 			    $none_graded = 0;
                   4741:1): 		        }
                   4742:1):                     }
1.301     albertel 4743: 		}
                   4744: 
                   4745: 		if ($all_graded || $none_graded) {
                   4746: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4747: 							   $symb,$cdom,$cnum,
                   4748: 							   $udom,$uname);
                   4749: 		}
                   4750: 	    }
                   4751: 
1.477     albertel 4752: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4753: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4754: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4755: 	    $updateCtr++;
1.93      albertel 4756: 	} else {
1.477     albertel 4757: 	    push(@noupdate,
                   4758: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4759: 	    $noupdateCtr++;
1.44      ng       4760: 	}
1.269     raeburn  4761:         if ($aggregateflag) {
                   4762:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4763: 				  $cdom,$cnum);
1.269     raeburn  4764:         }
1.93      albertel 4765:     }
1.477     albertel 4766:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4767:8):         my $numcols=$totcolspan+2;
1.477     albertel 4768: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4769: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4770: 	    &mt('No Changes Occurred For the Students Below').
                   4771: 	    '</td>'.
1.477     albertel 4772: 	    &Apache::loncommon::end_data_table_row();
                   4773: 	foreach my $line (@noupdate) {
                   4774: 	    $result.=
                   4775: 		&Apache::loncommon::start_data_table_row().
                   4776: 		$line.
                   4777: 		&Apache::loncommon::end_data_table_row();
                   4778: 	}
1.44      ng       4779:     }
1.596.2.12.2.  1(raebur 4780:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4781:     my $msg = '<p><b>'.
                   4782: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4783: 	    $rec_update,$count).'</b><br />'.
                   4784: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4785: 	'</b></p>';
1.44      ng       4786:     return $title.$msg.$result;
1.5       albertel 4787: }
1.54      albertel 4788: 
                   4789: sub split_part_type {
                   4790:     my ($partstr) = @_;
                   4791:     my ($temp,@allparts)=split(/_/,$partstr);
                   4792:     my $type=pop(@allparts);
1.439     albertel 4793:     my $part=join('_',@allparts);
1.54      albertel 4794:     return ($part,$type);
                   4795: }
                   4796: 
1.44      ng       4797: #------------- end of section for handling grading by section/class ---------
                   4798: #
                   4799: #----------------------------------------------------------------------------
                   4800: 
1.5       albertel 4801: 
1.44      ng       4802: #----------------------------------------------------------------------------
                   4803: #
                   4804: #-------------------------- Next few routines handles grading by csv upload
                   4805: #
                   4806: #--- Javascript to handle csv upload
1.27      albertel 4807: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4808:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4809:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4810:6):   &js_escape(\$error1);
                   4811:6):   &js_escape(\$error2);
1.27      albertel 4812:   return(<<ENDPICK);
                   4813:   function verify(vf) {
                   4814:     var foundsomething=0;
                   4815:     var founduname=0;
1.243     albertel 4816:     var foundID=0;
1.27      albertel 4817:     for (i=0;i<=vf.nfields.value;i++) {
                   4818:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4819:       if (i==0 && tw!=0) { foundID=1; }
                   4820:       if (i==1 && tw!=0) { founduname=1; }
                   4821:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4822:     }
1.246     albertel 4823:     if (founduname==0 && foundID==0) {
                   4824: 	alert('$error1');
                   4825: 	return;
1.27      albertel 4826:     }
                   4827:     if (foundsomething==0) {
1.246     albertel 4828: 	alert('$error2');
                   4829: 	return;
1.27      albertel 4830:     }
                   4831:     vf.submit();
                   4832:   }
                   4833:   function flip(vf,tf) {
                   4834:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4835:     var i;
                   4836:     for (i=0;i<=vf.nfields.value;i++) {
                   4837:       //can not pick the same destination field for both name and domain
                   4838:       if (((i ==0)||(i ==1)) && 
                   4839:           ((tf==0)||(tf==1)) && 
                   4840:           (i!=tf) &&
                   4841:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4842:         eval('vf.f'+i+'.selectedIndex=0;')
                   4843:       }
                   4844:     }
                   4845:   }
                   4846: ENDPICK
                   4847: }
                   4848: 
                   4849: sub csvupload_javascript_forward_associate {
1.573     bisitz   4850:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4851:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4852:6):   &js_escape(\$error1);
                   4853:6):   &js_escape(\$error2);
1.27      albertel 4854:   return(<<ENDPICK);
                   4855:   function verify(vf) {
                   4856:     var foundsomething=0;
                   4857:     var founduname=0;
1.243     albertel 4858:     var foundID=0;
1.27      albertel 4859:     for (i=0;i<=vf.nfields.value;i++) {
                   4860:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4861:       if (tw==1) { foundID=1; }
                   4862:       if (tw==2) { founduname=1; }
                   4863:       if (tw>3) { foundsomething=1; }
1.27      albertel 4864:     }
1.246     albertel 4865:     if (founduname==0 && foundID==0) {
                   4866: 	alert('$error1');
                   4867: 	return;
1.27      albertel 4868:     }
                   4869:     if (foundsomething==0) {
1.246     albertel 4870: 	alert('$error2');
                   4871: 	return;
1.27      albertel 4872:     }
                   4873:     vf.submit();
                   4874:   }
                   4875:   function flip(vf,tf) {
                   4876:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4877:     var i;
                   4878:     //can not pick the same destination field twice
                   4879:     for (i=0;i<=vf.nfields.value;i++) {
                   4880:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4881:         eval('vf.f'+i+'.selectedIndex=0;')
                   4882:       }
                   4883:     }
                   4884:   }
                   4885: ENDPICK
                   4886: }
                   4887: 
1.26      albertel 4888: sub csvuploadmap_header {
1.324     albertel 4889:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4890:     my $javascript;
1.257     albertel 4891:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4892: 	$javascript=&csvupload_javascript_reverse_associate();
                   4893:     } else {
                   4894: 	$javascript=&csvupload_javascript_forward_associate();
                   4895:     }
1.45      ng       4896: 
1.257     albertel 4897:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4898:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4899:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4900:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4901:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4902:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4903:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4904:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4905:0): <br />
                   4906:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4907: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4908: <input type="hidden" name="associate"  value="" />
                   4909: <input type="hidden" name="phase"      value="three" />
                   4910: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4911: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4912: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4913: <input type="hidden" name="upfile_associate" 
1.257     albertel 4914:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4915: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4916: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4917: <hr />
                   4918: ENDPICK
1.596.2.12.2.  1(raebur 4919:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4920:     return '';
1.26      albertel 4921: 
                   4922: }
                   4923: 
                   4924: sub csvupload_fields {
1.582     raeburn  4925:     my ($symb,$errorref) = @_;
1.596.2.12.2.  0.2.4(ra 4926:ul-23):     my $toolsymb;
                   4927:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4928:ul-23):         $toolsymb = $symb;
                   4929:ul-23):     }
1.582     raeburn  4930:     my (@parts) = &getpartlist($symb,$errorref);
                   4931:     if (ref($errorref)) {
                   4932:         if ($$errorref) {
                   4933:             return;
                   4934:         }
                   4935:     }
                   4936: 
1.556     weissno  4937:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4938: 		['username','Student Username'],
                   4939: 		['domain','Student Domain']);
1.324     albertel 4940:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4941:     foreach my $part (sort(@parts)) {
                   4942: 	my @datum;
1.596.2.12.2.  0.2.4(ra 4943:ul-23): 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4944: 	my $name=$part;
                   4945: 	if  (!$display) { $display = $name; }
                   4946: 	@datum=($name,$display);
1.244     albertel 4947: 	if ($name=~/^stores_(.*)_awarded/) {
                   4948: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4949: 	}
1.41      ng       4950: 	push(@fields,\@datum);
                   4951:     }
                   4952:     return (@fields);
1.26      albertel 4953: }
                   4954: 
                   4955: sub csvuploadmap_footer {
1.41      ng       4956:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4957:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4958:     $request->print(<<ENDPICK);
1.26      albertel 4959: </table>
                   4960: <input type="hidden" name="nfields" value="$i" />
                   4961: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4962:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4963: </form>
                   4964: ENDPICK
                   4965: }
                   4966: 
1.283     albertel 4967: sub checkforfile_js {
1.539     riegler  4968:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4969:6):     &js_escape(\$alertmsg);
          1(raebur 4970:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4971:     function checkUpload(formname) {
                   4972: 	if (formname.upfile.value == "") {
1.539     riegler  4973: 	    alert("$alertmsg");
1.86      ng       4974: 	    return false;
                   4975: 	}
                   4976: 	formname.submit();
                   4977:     }
                   4978: CSVFORMJS
1.283     albertel 4979:     return $result;
                   4980: }
                   4981: 
                   4982: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4983:0):     my ($request,$symb) = @_;
1.283     albertel 4984:     if (!$symb) {return '';}
                   4985:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4986:0):     $result.=&Apache::loncommon::start_data_table().
                   4987:0):              &Apache::loncommon::start_data_table_header_row().
                   4988:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4989:0):              &Apache::loncommon::end_data_table_header_row().
                   4990:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4991:     my $upload=&mt("Upload Scores");
1.86      ng       4992:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4993:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4994:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4995:     $result.=<<ENDUPFORM;
1.106     albertel 4996: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4997: <input type="hidden" name="symb" value="$symb" />
                   4998: <input type="hidden" name="command" value="csvuploadmap" />
                   4999: $upfile_select
1.589     bisitz   5000: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 5001: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       5002: </form>
                   5003: ENDUPFORM
1.370     www      5004:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 5005:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   5006:0):             '</td>'.
                   5007:0):             &Apache::loncommon::end_data_table_row().
                   5008:0):             &Apache::loncommon::end_data_table();
1.86      ng       5009:     return $result;
                   5010: }
                   5011: 
                   5012: 
1.26      albertel 5013: sub csvuploadmap {
1.596.2.12.2.  1(raebur 5014:0):     my ($request,$symb) = @_;
1.41      ng       5015:     if (!$symb) {return '';}
1.72      ng       5016: 
1.41      ng       5017:     my $datatoken;
1.257     albertel 5018:     if (!$env{'form.datatoken'}) {
1.41      ng       5019: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5020:     } else {
1.596.2.12.2.  3(raebur 5021:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5022:8):         if ($datatoken ne '') { 
                   5023:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5024:8):         }
1.26      albertel 5025:     }
1.41      ng       5026:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 5027:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 5028:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5029:     my ($i,$keyfields);
                   5030:     if (@records) {
1.582     raeburn  5031:         my $fieldserror;
                   5032: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5033:         if ($fieldserror) {
                   5034:             $request->print(&navmap_errormsg());
                   5035:             return;
                   5036:         }
1.257     albertel 5037: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5038: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5039: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5040: 							  \@fields);
                   5041: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5042: 	    chop($keyfields);
                   5043: 	} else {
                   5044: 	    unshift(@fields,['none','']);
                   5045: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5046: 							    \@fields);
1.311     banghart 5047:             foreach my $rec (@records) {
                   5048:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5049:                 if (%temp) {
                   5050:                     $keyfields=join(',',sort(keys(%temp)));
                   5051:                     last;
                   5052:                 }
                   5053:             }
1.41      ng       5054: 	}
                   5055:     }
                   5056:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5057: 
1.41      ng       5058:     return '';
1.27      albertel 5059: }
                   5060: 
1.246     albertel 5061: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 5062:0):     my ($request,$symb)= @_;
                   5063:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 5064:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 5065:     my $ignore=&mt('Ignore First Line');
                   5066:     $request->print(<<ENDPICK);
                   5067: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   5068: <input type="hidden" name="command"    value="csvuploadassign" />
                   5069: <p>
                   5070: <label>
                   5071:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 5072:0):    $overwrite
1.246     albertel 5073: </label>
                   5074: </p>
                   5075: ENDPICK
                   5076:     my %fields=&get_fields();
                   5077:     if (!defined($fields{'domain'})) {
1.257     albertel 5078: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 5079:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5080:     }
1.257     albertel 5081:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5082: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5083: 	my $cleankey=$1;
                   5084: 	if ($cleankey eq 'command') { next; }
                   5085: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5086: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5087:     }
                   5088:     # FIXME do a check for any duplicated user ids...
                   5089:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 5090:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5091: <hr /></form>'."\n");
1.246     albertel 5092:     return '';
                   5093: }
                   5094: 
                   5095: sub get_fields {
                   5096:     my %fields;
1.257     albertel 5097:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5098:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5099: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5100: 	    if ($env{'form.f'.$i} ne 'none') {
                   5101: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5102: 	    }
                   5103: 	} else {
1.257     albertel 5104: 	    if ($env{'form.f'.$i} ne 'none') {
                   5105: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       5106: 	    }
                   5107: 	}
1.27      albertel 5108:     }
1.246     albertel 5109:     return %fields;
                   5110: }
                   5111: 
                   5112: sub csvuploadassign {
1.596.2.12.2.  1(raebur 5113:0):     my ($request,$symb) = @_;
1.246     albertel 5114:     if (!$symb) {return '';}
1.345     bowersj2 5115:     my $error_msg = '';
1.596.2.12.2.  3(raebur 5116:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5117:8):     if ($datatoken ne '') {
                   5118:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5119:8):     }
1.246     albertel 5120:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 5121:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 5122:     my %fields=&get_fields();
1.257     albertel 5123:     my $courseid=$env{'request.course.id'};
1.97      albertel 5124:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 5125:     my @notallowed;
1.41      ng       5126:     my @skipped;
1.596.2.4  raeburn  5127:     my @warnings;
1.41      ng       5128:     my $countdone=0;
                   5129:     foreach my $grade (@gradedata) {
                   5130: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5131: 	my $domain;
                   5132: 	if ($entries{$fields{'domain'}}) {
                   5133: 	    $domain=$entries{$fields{'domain'}};
                   5134: 	} else {
1.257     albertel 5135: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5136: 	}
1.243     albertel 5137: 	$domain=~s/\s//g;
1.41      ng       5138: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5139: 	$username=~s/\s//g;
1.243     albertel 5140: 	if (!$username) {
                   5141: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5142: 	    $id=~s/\s//g;
1.243     albertel 5143: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   5144: 	    $username=$ids{$id};
                   5145: 	}
1.41      ng       5146: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5147: 	    my $id=$entries{$fields{'ID'}};
                   5148: 	    $id=~s/\s//g;
                   5149: 	    if ($id) {
                   5150: 		push(@skipped,"$id:$domain");
                   5151: 	    } else {
                   5152: 		push(@skipped,"$username:$domain");
                   5153: 	    }
1.41      ng       5154: 	    next;
                   5155: 	}
1.108     albertel 5156: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5157: 	if (!&canmodify($usec)) {
                   5158: 	    push(@notallowed,"$username:$domain");
                   5159: 	    next;
                   5160: 	}
1.244     albertel 5161: 	my %points;
1.41      ng       5162: 	my %grades;
                   5163: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5164: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5165: 		$dest eq 'domain') { next; }
                   5166: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5167: 	    if ($dest=~/stores_(.*)_points/) {
                   5168: 		my $part=$1;
                   5169: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5170: 					      $symb,$domain,$username);
1.345     bowersj2 5171:                 if ($wgt) {
                   5172:                     $entries{$fields{$dest}}=~s/\s//g;
                   5173:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5174:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5175:                                           : 'correct_by_override';
1.596.2.4  raeburn  5176:                     if ($pcr>1) {
                   5177:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   5178:                     }
1.345     bowersj2 5179:                     $grades{"resource.$part.awarded"}=$pcr;
                   5180:                     $grades{"resource.$part.solved"}=$award;
                   5181:                     $points{$part}=1;
                   5182:                 } else {
                   5183:                     $error_msg = "<br />" .
                   5184:                         &mt("Some point values were assigned"
                   5185:                             ." for problems with a weight "
                   5186:                             ."of zero. These values were "
                   5187:                             ."ignored.");
                   5188:                 }
1.244     albertel 5189: 	    } else {
                   5190: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5191: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5192: 		my $store_key=$dest;
                   5193: 		$store_key=~s/^stores/resource/;
                   5194: 		$store_key=~s/_/\./g;
                   5195: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5196: 	    }
1.41      ng       5197: 	}
1.596.2.12.2.  1(raebur 5198:0): 	if (! %grades) {
1.508     www      5199:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5200:         } else {
                   5201: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5202: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5203: 					   $env{'request.course.id'},
                   5204: 					   $domain,$username);
1.508     www      5205: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 5206:0): # Successfully stored
1.508     www      5207: 	      $request->print('.');
1.596.2.4  raeburn  5208: # Remove from grading queue
                   5209:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5210:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5211:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5212:                                              $domain,$username);
1.508     www      5213: 	   } else {
                   5214: 	      $request->print("<p><span class=\"LC_error\">".
                   5215:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5216:                                   "$username:$domain",$result)."</span></p>");
                   5217: 	   }
                   5218: 	   $request->rflush();
                   5219: 	   $countdone++;
                   5220:         }
1.41      ng       5221:     }
1.570     www      5222:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5223:     if (@warnings) {
                   5224:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5225:         $request->print(join(', ',@warnings));
                   5226:     }
1.41      ng       5227:     if (@skipped) {
1.571     www      5228: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5229:         $request->print(join(', ',@skipped));
1.106     albertel 5230:     }
                   5231:     if (@notallowed) {
1.571     www      5232: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5233: 	$request->print(join(', ',@notallowed));
1.41      ng       5234:     }
1.106     albertel 5235:     $request->print("<br />\n");
1.345     bowersj2 5236:     return $error_msg;
1.26      albertel 5237: }
1.44      ng       5238: #------------- end of section for handling csv file upload ---------
                   5239: #
                   5240: #-------------------------------------------------------------------
                   5241: #
1.122     ng       5242: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5243: #
                   5244: #--- Select a page/sequence and a student to grade
1.68      ng       5245: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5246:0):     my ($request,$symb) = @_;
1.68      ng       5247: 
1.539     riegler  5248:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5249:6):     &js_escape(\$alertmsg);
          1(raebur 5250:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5251: 
                   5252: function checkPickOne(formname) {
1.76      ng       5253:     if (radioSelection(formname.student) == null) {
1.539     riegler  5254: 	alert("$alertmsg");
1.68      ng       5255: 	return;
                   5256:     }
1.125     ng       5257:     ptr = pullDownSelection(formname.selectpage);
                   5258:     formname.page.value = formname["page"+ptr].value;
                   5259:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5260:     formname.submit();
                   5261: }
                   5262: 
                   5263: LISTJAVASCRIPT
1.118     ng       5264:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5265:0): 
1.257     albertel 5266:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5267:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5268:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5269:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5270: 
1.398     albertel 5271:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5272: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5273: 
1.80      ng       5274:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5275:     my $map_error;
                   5276:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5277:     if ($map_error) {
                   5278:         $request->print(&navmap_errormsg());
                   5279:         return; 
                   5280:     }
1.137     albertel 5281:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5282: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5283: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5284: 
1.596.2.12.2.  1(raebur 5285:0):     # Collection of hidden fields
                   5286:0):     my $ctr=0;
1.70      ng       5287:     foreach (@$titles) {
                   5288: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5289: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5290: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5291: 	$ctr++;
                   5292:     }
1.72      ng       5293:     $result.='<input type="hidden" name="page" />'."\n".
                   5294: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5295: 
1.432     banghart 5296:     $result.=&build_section_inputs();
1.442     banghart 5297:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5298:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5299:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5300:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5301:0): 
                   5302:0):     # Show grading options
                   5303:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5304:0):     my $select = '<select name="selectpage">'."\n";
                   5305:0):     $ctr=0;
                   5306:0):     foreach (@$titles) {
                   5307:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5308:0):         $select.='<option value="'.$ctr.'"'.
                   5309:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5310:0):             '>'.$showtitle.'</option>'."\n";
                   5311:0):         $ctr++;
                   5312:0):     }
                   5313:0):     $select.= '</select>';
1.72      ng       5314: 
1.596.2.12.2.  1(raebur 5315:0):     $result.=
                   5316:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5317:0):        .$select
                   5318:0):        .&Apache::lonhtmlcommon::row_closure();
                   5319:0): 
                   5320:0):     $result.=
                   5321:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5322:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5323:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5324:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5325:0):            .&mt('yes').'</label>'."\n"
                   5326:0):        .&Apache::lonhtmlcommon::row_closure();
                   5327:0): 
                   5328:0):     $result.=
                   5329:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5330:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5331:0):            .&mt('none').' </label>'."\n"
                   5332:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5333:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5334:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5335:0):            .&mt('all submissions with details').' </label>'
                   5336:0):        .&Apache::lonhtmlcommon::row_closure();
                   5337:0): 
                   5338:0):     $result.=
                   5339:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5340:0):        .'<input type="text" name="CODE" value="" />'
                   5341:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5342:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5343: 
1.596.2.12.2.  1(raebur 5344:0):     # Show list of students to select for grading
                   5345:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5346:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5347: 
1.68      ng       5348:     $request->print($result);
                   5349: 
1.485     albertel 5350:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5351: 	&Apache::loncommon::start_data_table().
                   5352: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5353: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5354: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5355: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5356: 	'<th>'.&nameUserString('header').'</th>'.
                   5357: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5358:  
1.596.2.12.2.  8(raebur 5359:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5360:     my $ptr = 1;
1.294     albertel 5361:     foreach my $student (sort 
                   5362: 			 {
                   5363: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5364: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5365: 			     }
                   5366: 			     return $a cmp $b;
                   5367: 			 } (keys(%$fullname))) {
1.68      ng       5368: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5369: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5370:                                   : '</td>');
1.126     ng       5371: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5372: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5373: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5374: 	$studentTable.=
                   5375: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5376:                          : '');
1.68      ng       5377: 	$ptr++;
                   5378:     }
1.484     albertel 5379:     if ($ptr%2 == 0) {
                   5380: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5381: 	    &Apache::loncommon::end_data_table_row();
                   5382:     }
                   5383:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5384:     $studentTable.='<input type="button" '.
1.589     bisitz   5385:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5386: 
                   5387:     $request->print($studentTable);
                   5388: 
                   5389:     return '';
                   5390: }
                   5391: 
                   5392: sub getSymbMap {
1.582     raeburn  5393:     my ($map_error) = @_;
1.132     bowersj2 5394:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5395:     unless (ref($navmap)) {
                   5396:         if (ref($map_error)) {
                   5397:             $$map_error = 'navmap';
                   5398:         }
                   5399:         return;
                   5400:     }
1.68      ng       5401:     my %symbx = ();
                   5402:     my @titles = ();
1.117     bowersj2 5403:     my $minder = 0;
                   5404: 
                   5405:     # Gather every sequence that has problems.
1.240     albertel 5406:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5407: 					       1,0,1);
1.117     bowersj2 5408:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.596.2.12.2.  0.2.4(ra 5409:ul-23): 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5410: 	    my $title = $minder.'.'.
                   5411: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5412: 	    push(@titles, $title); # minder in case two titles are identical
                   5413: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5414: 	    $minder++;
1.241     albertel 5415: 	}
1.68      ng       5416:     }
                   5417:     return \@titles,\%symbx;
                   5418: }
                   5419: 
1.72      ng       5420: #
                   5421: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5422: sub displayPage {
1.596.2.12.2.  1(raebur 5423:0):     my ($request,$symb) = @_;
1.257     albertel 5424:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5425:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5426:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5427:     my $pageTitle = $env{'form.page'};
1.103     albertel 5428:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5429:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5430:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5431: 
                   5432:     #need to make sure we have the correct data for later EXT calls, 
                   5433:     #thus invalidate the cache
                   5434:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5435:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5436:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5437:     &Apache::lonnet::clear_EXT_cache_status();
                   5438: 
1.103     albertel 5439:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5440:0): 	$request->print(
                   5441:0):             '<span class="LC_warning">'.
                   5442:0):             &mt('Unable to view requested student. ([_1])',
                   5443:0):                 $env{'form.student'}).
                   5444:0):             '</span>');
          8(raebur 5445:4):         return;
1.103     albertel 5446:     }
1.398     albertel 5447:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5448:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5449: 	'</h3>'."\n";
1.500     albertel 5450:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5451:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5452: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5453:     } else {
                   5454: 	delete($env{'form.CODE'});
                   5455:     }
1.71      ng       5456:     &sub_page_js($request);
                   5457:     $request->print($result);
                   5458: 
1.132     bowersj2 5459:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5460:     unless (ref($navmap)) {
                   5461:         $request->print(&navmap_errormsg());
                   5462:         return;
                   5463:     }
1.257     albertel 5464:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5465:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5466:     if (!$map) {
1.485     albertel 5467: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5468: 	return; 
                   5469:     }
1.68      ng       5470:     my $iterator = $navmap->getIterator($map->map_start(),
                   5471: 					$map->map_finish());
                   5472: 
1.71      ng       5473:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5474: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5475: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5476: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5477: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5478: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5479: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5480:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5481: 
1.382     albertel 5482:     if (defined($env{'form.CODE'})) {
                   5483: 	$studentTable.=
                   5484: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5485:     }
1.381     albertel 5486:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5487: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5488: 
1.594     bisitz   5489:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5490:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5491:         '</span>'."\n".
1.484     albertel 5492: 	&Apache::loncommon::start_data_table().
                   5493: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5494:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5495: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5496: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5497: 
1.329     albertel 5498:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5499:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5500:     $iterator->next(); # skip the first BEGIN_MAP
                   5501:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5502:     while ($depth > 0) {
1.68      ng       5503:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5504:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5505: 
1.596.2.12.2.  0.2.4(ra 5506:ul-23):         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5507: 	    my $parts = $curRes->parts();
1.68      ng       5508:             my $title = $curRes->compTitle();
1.71      ng       5509: 	    my $symbx = $curRes->symb();
1.596.2.12.2.  0.2.4(ra 5510:ul-23):             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5511: 	    $studentTable.=
                   5512: 		&Apache::loncommon::start_data_table_row().
                   5513: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5514: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5515:2): 		                        : '<br />('.&mt('[_1]parts',
                   5516:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5517: 		 ).
                   5518: 		 '</td>';
1.71      ng       5519: 	    $studentTable.='<td valign="top">';
1.382     albertel 5520: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.596.2.12.2.  0.2.4(ra 5521:ul-23):             if ($is_tool) {
                   5522:ul-23):                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5523:ul-23):             } else {
                   5524:ul-23): 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5525:ul-23): 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5526:ul-23): 			   		         undef,'both',\%form);
                   5527:ul-23): 	        } else {
                   5528:ul-23): 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5529:ul-23): 		    $companswer =~ s|<form(.*?)>||g;
                   5530:ul-23): 		    $companswer =~ s|</form>||g;
                   5531:ul-23): #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5532:ul-23): #		        $companswer =~ s/$1/ /ms;
                   5533:ul-23): #		        $request->print('match='.$1."<br />\n");
                   5534:ul-23): #		    }
                   5535:ul-23): #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5536:ul-23): 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5537:ul-23):                 }
1.71      ng       5538: 	    }
                   5539: 
1.257     albertel 5540: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5541: 
1.257     albertel 5542: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5543: 		if ($record{'version'} eq '') {
1.596.2.12.2.  0.2.4(ra 5544:ul-23):                     my $msg = &mt('No recorded submission for this problem.');
                   5545:ul-23):                     if ($is_tool) {
                   5546:ul-23):                         $msg = &mt('No recorded transactions for this external tool');
                   5547:ul-23):                     }
                   5548:ul-23): 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5549: 		} else {
1.116     ng       5550: 		    my %responseType = ();
                   5551: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5552: 			my @responseIds =$curRes->responseIds($partid);
                   5553: 			my @responseType =$curRes->responseType($partid);
                   5554: 			my %responseIds;
                   5555: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5556: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5557: 			}
                   5558: 			$responseType{$partid} = \%responseIds;
1.116     ng       5559: 		    }
1.148     albertel 5560: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5561: 
1.71      ng       5562: 		}
1.257     albertel 5563: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5564: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5565:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5566: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5567: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5568:5): 									'','.submission',undef,
                   5569:5):                                                                         $usec,$identifier);
1.71      ng       5570:  
                   5571: 	    }
1.103     albertel 5572: 	    if (&canmodify($usec)) {
1.585     bisitz   5573:             $studentTable.=&gradeBox_start();
1.103     albertel 5574: 		foreach my $partid (@{$parts}) {
                   5575: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5576: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5577: 		    $question++;
                   5578: 		}
1.585     bisitz   5579:             $studentTable.=&gradeBox_end();
1.196     albertel 5580: 		$prob++;
1.71      ng       5581: 	    }
                   5582: 	    $studentTable.='</td></tr>';
1.68      ng       5583: 
1.103     albertel 5584: 	}
1.68      ng       5585:         $curRes = $iterator->next();
                   5586:     }
1.596.2.12.2.  6(raebur 5587:1):     my $disabled;
                   5588:1):     unless (&canmodify($usec)) {
                   5589:1):         $disabled = ' disabled="disabled"';
                   5590:1):     }
1.68      ng       5591: 
1.589     bisitz   5592:     $studentTable.=
                   5593:         '</table>'."\n".
1.596.2.12.2.  6(raebur 5594:1):         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5595:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5596:         '</form>'."\n";
1.71      ng       5597:     $request->print($studentTable);
                   5598: 
                   5599:     return '';
1.119     ng       5600: }
                   5601: 
                   5602: sub displaySubByDates {
1.148     albertel 5603:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5604:     my $isCODE=0;
1.335     albertel 5605:     my $isTask = ($symb =~/\.task$/);
1.596.2.12.2.  0.2.4(ra 5606:ul-23):     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5607:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5608:     my $studentTable=&Apache::loncommon::start_data_table().
                   5609: 	&Apache::loncommon::start_data_table_header_row().
                   5610: 	'<th>'.&mt('Date/Time').'</th>'.
                   5611: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5612:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
          0.2.4(ra 5613:ul-23): 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5614: 	'<th>'.&mt('Status').'</th>'.
                   5615: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5616:     my ($version);
                   5617:     my %mark;
1.148     albertel 5618:     my %orders;
1.119     ng       5619:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5620:     if (!exists($$record{'1:timestamp'})) {
1.596.2.12.2.  0.2.4(ra 5621:ul-23):         if ($is_tool) {
                   5622:ul-23):             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5623:ul-23):         } else {
                   5624:ul-23): 	    return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5625:ul-23):         }
1.147     albertel 5626:     }
1.335     albertel 5627: 
                   5628:     my $interaction;
1.525     raeburn  5629:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5630:5):     my (%lastrndseed,%lasttype);
1.119     ng       5631:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5632: 	my $timestamp = 
                   5633: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5634: 	if (exists($$record{$version.':resource.0.version'})) {
                   5635: 	    $interaction = $$record{$version.':resource.0.version'};
                   5636: 	}
1.596.2.12.2.  (raeburn 5637:):         if ($isTask && $env{'form.previousversion'}) {
                   5638:):             next unless ($interaction == $env{'form.previousversion'});
                   5639:):         }
1.335     albertel 5640: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5641: 		             : "$version:resource");
1.467     albertel 5642: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5643: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5644: 	if ($isCODE) {
                   5645: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5646: 	}
1.596.2.12.2.  (raeburn 5647:):         if ($isTask) {
                   5648:):             $studentTable.='<td>'.$interaction.'</td>';
                   5649:):         }
1.119     ng       5650: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5651: 	my @displaySub = ();
                   5652: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5653:             my ($hidden,$type);
                   5654:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5655:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5656:                 $hidden = 1;
                   5657:             }
1.596.2.12.2.  1(raebur 5658:0): 	    my @matchKey;
                   5659:0):             if ($isTask) {
                   5660:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
          0.2.4(ra 5661:ul-23):             } elsif ($is_tool) {
                   5662:ul-23):                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
          1(raebur 5663:0):             } else {
                   5664:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5665:0):             }
1.122     ng       5666: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5667: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5668: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5669: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5670: 		    $$record{$version.':'.$matchKey} ne '') {
1.596.2.12.2.  0.2.4(ra 5671:ul-23):                     if ($is_tool) {
                   5672:ul-23):                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5673:                     } else {
1.596.2.12.2.  0.2.4(ra 5674:ul-23): 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5675:ul-23): 			    	                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5676:ul-23):                         $displaySub[0].='<span class="LC_nobreak">';
                   5677:ul-23):                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5678:ul-23):                                        .' <span class="LC_internal_info">'
                   5679:ul-23):                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5680:ul-23):                                        .'</span>'
                   5681:ul-23):                                        .' <b>';
                   5682:ul-23):                         if ($hidden) {
                   5683:ul-23):                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5684:ul-23):                         } else {
                   5685:ul-23):                             my ($trial,$rndseed,$newvariation);
                   5686:ul-23):                             if ($type eq 'randomizetry') {
                   5687:ul-23):                                 $trial = $$record{"$where.$partid.tries"};
                   5688:ul-23):                                 $rndseed = $$record{"$where.$partid.rndseed"};
1.596.2.2  raeburn  5689:                             }
1.596.2.12.2.  0.2.4(ra 5690:ul-23): 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5691:ul-23): 			        $displaySub[0].=&mt('Trial not counted');
                   5692:ul-23): 		            } else {
                   5693:ul-23): 			        $displaySub[0].=&mt('Trial: [_1]',
                   5694:ul-23): 				    	        $$record{"$where.$partid.tries"});
                   5695:ul-23):                                 if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
                   5696:ul-23):                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5697:ul-23):                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5698:ul-23):                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5699:ul-23):                                     }
                   5700:ul-23):                                 }
                   5701:ul-23):                                 $lastrndseed{$partid} = $rndseed;
                   5702:ul-23):                                 $lasttype{$partid} = $type;
                   5703:ul-23): 		           }
                   5704:ul-23): 		           my $responseType=($isTask ? 'Task'
                   5705:ul-23):                                                   : $responseType->{$partid}->{$responseId});
                   5706:ul-23): 		           if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5707:ul-23): 		           if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5708:ul-23): 			       $orders{$partid}->{$responseId}=
                   5709:ul-23): 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5710:ul-23):                                                $no_increment,$type,$trial,$rndseed);
                   5711:ul-23): 		            }
                   5712:ul-23): 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5713:ul-23): 		            $displaySub[0].='&nbsp; '.
                   5714:ul-23): 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5715:ul-23):                         }
1.596     raeburn  5716:                     }
1.147     albertel 5717: 		}
                   5718: 	    }
1.335     albertel 5719: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5720: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5721: 				    $$record{"$where.$partid.checkedin"},
                   5722: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5723: 					'<br />';
1.335     albertel 5724: 	    }
                   5725: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5726: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5727: 		    lc($$record{"$where.$partid.award"}).' '.
                   5728: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5729: 		    '<br />';
1.596.2.12.2.  0.2.4(ra 5730:ul-23):             } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5731:ul-23):                 if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5732:ul-23):                     $displaySub[1].=&mt('Grade passed back by external tool');
                   5733:ul-23):                 }
1.147     albertel 5734: 	    }
1.335     albertel 5735: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.596.2.12.2.  0.2.4(ra 5736:ul-23): 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5737:ul-23):                 unless ($is_tool) {
                   5738:ul-23): 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5739:ul-23):                 }
1.335     albertel 5740: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5741: 		$displaySub[2].=
1.596.2.12.2.  0.2.4(ra 5742:ul-23): 		    $$record{"$version:resource.$partid.regrader"};
                   5743:ul-23):                 unless ($is_tool) {
                   5744:ul-23): 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5745:ul-23):                 }
1.147     albertel 5746: 	    }
                   5747: 	}
                   5748: 	# needed because old essay regrader has not parts info
                   5749: 	if (exists $$record{"$version:resource.regrader"}) {
                   5750: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5751: 	}
                   5752: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5753: 	if ($displaySub[2]) {
1.467     albertel 5754: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5755: 	}
1.467     albertel 5756: 	$studentTable.='&nbsp;</td>'.
                   5757: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5758:     }
1.467     albertel 5759:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5760:     return $studentTable;
1.71      ng       5761: }
                   5762: 
                   5763: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5764:0):     my ($request,$symb) = @_;
1.71      ng       5765: 
1.257     albertel 5766:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5767:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5768:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5769:     my $pageTitle = $env{'form.page'};
1.103     albertel 5770:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5771:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5772:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5773:     if (!&canmodify($usec)) {
1.526     raeburn  5774: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5775: 	return;
                   5776:     }
1.398     albertel 5777:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5778:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5779: 	'</h3>'."\n";
1.70      ng       5780: 
1.68      ng       5781:     $request->print($result);
                   5782: 
1.582     raeburn  5783: 
1.132     bowersj2 5784:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5785:     unless (ref($navmap)) {
                   5786:         $request->print(&navmap_errormsg());
                   5787:         return;
                   5788:     }
1.257     albertel 5789:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5790:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5791:     if (!$map) {
1.527     raeburn  5792: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5793: 	return; 
                   5794:     }
1.71      ng       5795:     my $iterator = $navmap->getIterator($map->map_start(),
                   5796: 					$map->map_finish());
1.70      ng       5797: 
1.484     albertel 5798:     my $studentTable=
                   5799: 	&Apache::loncommon::start_data_table().
                   5800: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5801: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5802: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5803: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5804: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5805: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5806: 
                   5807:     $iterator->next(); # skip the first BEGIN_MAP
                   5808:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5809:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5810:     while ($depth > 0) {
1.71      ng       5811:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5812:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5813: 
1.385     albertel 5814:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5815: 	    my $parts = $curRes->parts();
1.71      ng       5816:             my $title = $curRes->compTitle();
                   5817: 	    my $symbx = $curRes->symb();
1.484     albertel 5818: 	    $studentTable.=
                   5819: 		&Apache::loncommon::start_data_table_row().
                   5820: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5821: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5822:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5823: 		.')').'</td>';
1.71      ng       5824: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5825: 
                   5826: 	    my %newrecord=();
                   5827: 	    my @displayPts=();
1.269     raeburn  5828:             my %aggregate = ();
                   5829:             my $aggregateflag = 0;
1.596.2.12.2.  9(raebur 5830:1):             my %queueable;
          1(raebur 5831:5):             if ($env{'form.HIDE'.$prob}) {
                   5832:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5833:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5834:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5835:5):                 $hideflag += $numchgs;
                   5836:5):             }
1.71      ng       5837: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5838: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5839: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.596.2.12.2.  9(raebur 5840:1):                 my @types = $curRes->responseType($partid);
          8(raebur 5841:1):                 if (grep(/^essay$/,@types)) {
                   5842:1):                     $queueable{$partid} = 1;
                   5843:1):                 } else {
          9(raebur 5844:1):                     my @ids = $curRes->responseIds($partid);
          8(raebur 5845:1):                     for (my $i=0; $i < scalar(@ids); $i++) {
          9(raebur 5846:1):                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
          8(raebur 5847:1):                                                           '.handgrade',$symb);
                   5848:1):                         if (lc($hndgrd) eq 'yes') {
                   5849:1):                             $queueable{$partid} = 1;
                   5850:1):                             last;
                   5851:1):                         }
                   5852:1):                     }
                   5853:1):                 }
1.257     albertel 5854: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5855: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5856: 		my $partial = $newpts/$wgt;
                   5857: 		my $score;
                   5858: 		if ($partial > 0) {
                   5859: 		    $score = 'correct_by_override';
1.125     ng       5860: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5861: 		    $score = 'incorrect_by_override';
                   5862: 		}
1.257     albertel 5863: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5864: 		if ($dropMenu eq 'excused') {
1.71      ng       5865: 		    $partial = '';
                   5866: 		    $score = 'excused';
1.125     ng       5867: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5868: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5869: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5870: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5871: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5872: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5873: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5874: 		    $changeflag++;
                   5875: 		    $newpts = '';
1.269     raeburn  5876:                     
                   5877:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5878:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5879:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5880:                     if ($aggtries > 0) {
                   5881:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5882:                         $aggregateflag = 1;
                   5883:                     }
1.71      ng       5884: 		}
1.324     albertel 5885: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5886: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5887: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5888: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5889: 		    '&nbsp;<br />';
1.526     raeburn  5890: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5891: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5892: 		    '&nbsp;<br />';
1.71      ng       5893: 		$question++;
1.380     albertel 5894: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5895: 
1.71      ng       5896: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5897: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5898: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5899: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5900: 
                   5901: 		$changeflag++;
                   5902: 	    }
                   5903: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5904: 		my %record = 
                   5905: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5906: 					     $udom,$uname);
                   5907: 
                   5908: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5909: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5910: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5911: 		    $newrecord{'resource.CODE'} = '';
                   5912: 		}
1.257     albertel 5913: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5914: 					$udom,$uname);
1.382     albertel 5915: 		%record = &Apache::lonnet::restore($symbx,
                   5916: 						   $env{'request.course.id'},
                   5917: 						   $udom,$uname);
1.380     albertel 5918: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.596.2.12.2.  8(raebur 5919:1): 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5920: 	    }
1.380     albertel 5921: 	    
1.269     raeburn  5922:             if ($aggregateflag) {
                   5923:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5924:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5925:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5926:             }
1.125     ng       5927: 
1.71      ng       5928: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5929: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5930: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5931: 
1.196     albertel 5932: 	    $prob++;
1.68      ng       5933: 	}
1.71      ng       5934:         $curRes = $iterator->next();
1.68      ng       5935:     }
1.98      albertel 5936: 
1.484     albertel 5937:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5938:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5939: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5940:5): 		  $changeflag).'<br />');
                   5941:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5942:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5943:5):                      $hideflag).'<br />');
                   5944:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5945: 
1.70      ng       5946:     return '';
                   5947: }
                   5948: 
1.72      ng       5949: #-------- end of section for handling grading by page/sequence ---------
                   5950: #
                   5951: #-------------------------------------------------------------------
                   5952: 
1.581     www      5953: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5954: #
                   5955: #------ start of section for handling grading by page/sequence ---------
                   5956: 
1.423     albertel 5957: =pod
                   5958: 
                   5959: =head1 Bubble sheet grading routines
                   5960: 
1.424     albertel 5961:   For this documentation:
                   5962: 
                   5963:    'scanline' refers to the full line of characters
                   5964:    from the file that we are parsing that represents one entire sheet
                   5965: 
                   5966:    'bubble line' refers to the data
1.596.2.6  raeburn  5967:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5968: 
                   5969: 
1.596.2.6  raeburn  5970: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5971: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5972: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5973: one of the predefined configurations for what each scanline looks
                   5974: like.
                   5975: 
                   5976: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5977: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5978: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5979:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5980: invalid student/employee ID
1.424     albertel 5981: 
                   5982: If the CODE option is used that determines the randomization of the
1.556     weissno  5983: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5984: username:domain.
                   5985: 
                   5986: During the validation phase the instructor can choose to skip scanlines. 
                   5987: 
1.596.2.6  raeburn  5988: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5989: 
                   5990:   scantron_original_filename (unmodified original file)
                   5991:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5992:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5993: 
                   5994: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5995: correction information that isn't representable in the bubblesheet
1.424     albertel 5996: file (see &scantron_getfile() for more information)
                   5997: 
                   5998: After all scanlines are either valid, marked as valid or skipped, then
                   5999: foreach line foreach problem in the picked sequence, an ssi request is
                   6000: made that simulates a user submitting their selected letter(s) against
                   6001: the homework problem.
1.423     albertel 6002: 
                   6003: =over 4
                   6004: 
                   6005: 
                   6006: 
                   6007: =item defaultFormData
                   6008: 
                   6009:   Returns html hidden inputs used to hold context/default values.
                   6010: 
                   6011:  Arguments:
                   6012:   $symb - $symb of the current resource 
                   6013: 
                   6014: =cut
1.422     foxr     6015: 
1.81      albertel 6016: sub defaultFormData {
1.324     albertel 6017:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 6018:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 6019: }
                   6020: 
1.447     foxr     6021: 
1.423     albertel 6022: =pod 
                   6023: 
                   6024: =item getSequenceDropDown
                   6025: 
                   6026:    Return html dropdown of possible sequences to grade
                   6027:  
                   6028:  Arguments:
1.582     raeburn  6029:    $symb - $symb of the current resource
                   6030:    $map_error - ref to scalar which will container error if
                   6031:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 6032: 
                   6033: =cut
1.422     foxr     6034: 
1.75      albertel 6035: sub getSequenceDropDown {
1.582     raeburn  6036:     my ($symb,$map_error)=@_;
1.75      albertel 6037:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  6038:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6039:     if (ref($map_error)) {
                   6040:         return if ($$map_error);
                   6041:     }
1.137     albertel 6042:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 6043:     my $ctr=0;
                   6044:     foreach (@$titles) {
                   6045: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6046: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 6047: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 6048: 	    '>'.$showtitle.'</option>'."\n";
                   6049: 	$ctr++;
                   6050:     }
                   6051:     $result.= '</select>';
                   6052:     return $result;
                   6053: }
                   6054: 
1.495     albertel 6055: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  6056:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 6057: 
                   6058: my %first_bubble_line;             # First bubble line no. for each bubble.
                   6059: 
1.509     raeburn  6060: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   6061:                                    # matchresponse or rankresponse, where 
                   6062:                                    # an individual response can have multiple 
                   6063:                                    # lines
1.503     raeburn  6064: 
                   6065: my %responsetype_per_response;     # responsetype for each response
                   6066: 
1.596.2.12.2.  6(raebur 6067:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   6068:3):                                    # numbered response. Needed when randomorder
                   6069:3):                                    # or randompick are in use. Key is ID, value 
                   6070:3):                                    # is response number.
                   6071:3): 
1.495     albertel 6072: # Save and restore the bubble lines array to the form env.
                   6073: 
                   6074: 
                   6075: sub save_bubble_lines {
                   6076:     foreach my $line (keys(%bubble_lines_per_response)) {
                   6077: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   6078: 	$env{"form.scantron.first_bubble_line.$line"} =
                   6079: 	    $first_bubble_line{$line};
1.503     raeburn  6080:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   6081:             $subdivided_bubble_lines{$line};
                   6082:         $env{"form.scantron.responsetype.$line"} =
                   6083:             $responsetype_per_response{$line};
1.495     albertel 6084:     }
1.596.2.12.2.  6(raebur 6085:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   6086:3):         my $line = $masterseq_id_responsenum{$resid};
                   6087:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   6088:3):     }
1.495     albertel 6089: }
                   6090: 
                   6091: 
                   6092: sub restore_bubble_lines {
                   6093:     my $line = 0;
                   6094:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 6095:3):     %masterseq_id_responsenum = ();
1.495     albertel 6096:     while ($env{"form.scantron.bubblelines.$line"}) {
                   6097: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   6098: 	$bubble_lines_per_response{$line} = $value;
                   6099: 	$first_bubble_line{$line}  =
                   6100: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  6101:         $subdivided_bubble_lines{$line} =
                   6102:             $env{"form.scantron.sub_bubblelines.$line"};
                   6103:         $responsetype_per_response{$line} =
                   6104:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 6105:3):         my $id = $env{"form.scantron.residpart.$line"};
                   6106:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 6107: 	$line++;
                   6108:     }
                   6109: }
                   6110: 
1.423     albertel 6111: =pod 
                   6112: 
                   6113: =item scantron_filenames
                   6114: 
                   6115:    Returns a list of the scantron files in the current course 
                   6116: 
                   6117: =cut
1.422     foxr     6118: 
1.202     albertel 6119: sub scantron_filenames {
1.257     albertel 6120:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6121:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6122:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 6123:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6124:):                                                         $cname,$getpropath);
1.202     albertel 6125:     my @possiblenames;
1.596.2.12.2.  (raeburn 6126:):     if (ref($dirlist) eq 'ARRAY') {
                   6127:):         foreach my $filename (sort(@{$dirlist})) {
                   6128:): 	    ($filename)=split(/&/,$filename);
                   6129:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6130:): 	    $filename=~s/^scantron_orig_//;
                   6131:): 	    push(@possiblenames,$filename);
                   6132:):         }
1.202     albertel 6133:     }
                   6134:     return @possiblenames;
                   6135: }
                   6136: 
1.423     albertel 6137: =pod 
                   6138: 
                   6139: =item scantron_uploads
                   6140: 
                   6141:    Returns  html drop-down list of scantron files in current course.
                   6142: 
                   6143:  Arguments:
                   6144:    $file2grade - filename to set as selected in the dropdown
                   6145: 
                   6146: =cut
1.422     foxr     6147: 
1.202     albertel 6148: sub scantron_uploads {
1.209     ng       6149:     my ($file2grade) = @_;
1.202     albertel 6150:     my $result=	'<select name="scantron_selectfile">';
                   6151:     $result.="<option></option>";
                   6152:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6153: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6154:     }
                   6155:     $result.="</select>";
                   6156:     return $result;
                   6157: }
                   6158: 
1.423     albertel 6159: =pod 
                   6160: 
                   6161: =item scantron_scantab
                   6162: 
                   6163:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6164:   file.
                   6165: 
                   6166: =cut
1.422     foxr     6167: 
1.82      albertel 6168: sub scantron_scantab {
                   6169:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6170:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 6171:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6172:     if (@lines > 0) {
                   6173:         foreach my $line (@lines) {
                   6174:             next if (($line =~ /^\#/) || ($line eq ''));
                   6175: 	    my ($name,$descrip)=split(/:/,$line);
                   6176: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6177:         }
1.82      albertel 6178:     }
                   6179:     $result.='</select>'."\n";
1.518     raeburn  6180:     return $result;
                   6181: }
                   6182: 
1.423     albertel 6183: =pod 
                   6184: 
                   6185: =item scantron_CODElist
                   6186: 
                   6187:   Returns html drop down of the saved CODE lists from current course,
                   6188:   generated from earlier printings.
                   6189: 
                   6190: =cut
1.422     foxr     6191: 
1.186     albertel 6192: sub scantron_CODElist {
1.257     albertel 6193:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6194:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6195:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6196:     my $namechoice='<option></option>';
1.225     albertel 6197:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6198: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6199: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6200: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6201:     }
                   6202:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6203:     return $namechoice;
                   6204: }
                   6205: 
1.423     albertel 6206: =pod 
                   6207: 
                   6208: =item scantron_CODEunique
                   6209: 
                   6210:   Returns the html for "Each CODE to be used once" radio.
                   6211: 
                   6212: =cut
1.422     foxr     6213: 
1.186     albertel 6214: sub scantron_CODEunique {
1.532     bisitz   6215:     my $result='<span class="LC_nobreak">
1.272     albertel 6216:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6217:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6218:                 </span>
1.532     bisitz   6219:                 <span class="LC_nobreak">
1.272     albertel 6220:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6221:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6222:                 </span>';
1.186     albertel 6223:     return $result;
                   6224: }
1.423     albertel 6225: 
                   6226: =pod 
                   6227: 
                   6228: =item scantron_selectphase
                   6229: 
1.596.2.6  raeburn  6230:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6231:   Allows for - starting a grading run.
1.424     albertel 6232:              - downloading existing scan data (original, corrected
1.423     albertel 6233:                                                 or skipped info)
                   6234: 
                   6235:              - uploading new scan data
                   6236: 
                   6237:  Arguments:
                   6238:   $r          - The Apache request object
                   6239:   $file2grade - name of the file that contain the scanned data to score
                   6240: 
                   6241: =cut
1.186     albertel 6242: 
1.75      albertel 6243: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 6244:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6245:     if (!$symb) {return '';}
1.582     raeburn  6246:     my $map_error;
                   6247:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6248:     if ($map_error) {
                   6249:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6250:         return;
                   6251:     }
1.324     albertel 6252:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6253:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6254:     my $format_selector=&scantron_scantab();
1.186     albertel 6255:     my $CODE_selector=&scantron_CODElist();
                   6256:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6257:     my $result;
1.422     foxr     6258: 
1.513     foxr     6259:     $ssi_error = 0;
                   6260: 
1.596.2.4  raeburn  6261:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6262:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6263: 
                   6264:         # Chunk of form to prompt for a scantron file upload.
                   6265: 
                   6266:         $r->print('
1.596.2.12.2.  9(raebur 6267:9):     <br />');
                   6268:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6269:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6270:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6271:9):         &js_escape(\$alertmsg);
                   6272:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6273:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6274:     function checkUpload(formname) {
                   6275:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6276:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6277:             return false;
                   6278:         }
                   6279:         formname.submit();
1.596.2.12.2.  9(raebur 6280:9):     }'."\n".$formatjs));
                   6281:9):         $r->print('
1.596.2.4  raeburn  6282:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6283:                 '.$default_form_data.'
                   6284:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6285:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6286:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6287:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6288:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6289:9):                 <th>
                   6290:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6291:9):                 </th>
                   6292:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6293:9):               '.&Apache::loncommon::start_data_table_row().'
                   6294:9):             <td>
                   6295:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6296:9):         if ($formatoptions) {
                   6297:9):             $r->print('</td>
                   6298:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6299:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6300:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6301:9):                  </td>
                   6302:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6303:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6304:9):                  <td>'
                   6305:9):             );
                   6306:9):         } else {
                   6307:9):             $r->print(' <br />');
                   6308:9):         }
                   6309:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6310:9):               </td>
                   6311:9):              '.&Apache::loncommon::end_data_table_row().'
                   6312:9):              '.&Apache::loncommon::end_data_table().'
                   6313:9):              </form>'
                   6314:9):         );
1.596.2.4  raeburn  6315: 
                   6316:     }
                   6317: 
1.422     foxr     6318:     # Chunk of form to prompt for a file to grade and how:
                   6319: 
1.489     albertel 6320:     $result.= '
                   6321:     <br />
                   6322:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6323:     <input type="hidden" name="command" value="scantron_warning" />
                   6324:     '.$default_form_data.'
                   6325:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6326:        '.&Apache::loncommon::start_data_table_header_row().'
                   6327:             <th colspan="2">
1.492     albertel 6328:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6329:             </th>
                   6330:        '.&Apache::loncommon::end_data_table_header_row().'
                   6331:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6332:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6333:        '.&Apache::loncommon::end_data_table_row().'
                   6334:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6335:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6336:        '.&Apache::loncommon::end_data_table_row().'
                   6337:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6338:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6339:        '.&Apache::loncommon::end_data_table_row().'
                   6340:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6341:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6342:        '.&Apache::loncommon::end_data_table_row().'
                   6343:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6344:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6345:        '.&Apache::loncommon::end_data_table_row().'
                   6346:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6347: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6348:             <td>
1.492     albertel 6349: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6350:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6351:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6352: 	    </td>
1.489     albertel 6353:        '.&Apache::loncommon::end_data_table_row().'
                   6354:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6355:             <td colspan="2">
1.572     www      6356:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6357:             </td>
1.489     albertel 6358:        '.&Apache::loncommon::end_data_table_row().'
                   6359:     '.&Apache::loncommon::end_data_table().'
                   6360:     </form>
                   6361: ';
1.162     albertel 6362:    
                   6363:     $r->print($result);
                   6364: 
1.422     foxr     6365:     # Chunk of the form that prompts to view a scoring office file,
                   6366:     # corrected file, skipped records in a file.
                   6367: 
1.489     albertel 6368:     $r->print('
                   6369:    <br />
                   6370:    <form action="/adm/grades" name="scantron_download">
                   6371:      '.$default_form_data.'
                   6372:      <input type="hidden" name="command" value="scantron_download" />
                   6373:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6374:        '.&Apache::loncommon::start_data_table_header_row().'
                   6375:               <th>
1.492     albertel 6376:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6377:               </th>
                   6378:        '.&Apache::loncommon::end_data_table_header_row().'
                   6379:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6380:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6381:                 <br />
1.492     albertel 6382:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6383:        '.&Apache::loncommon::end_data_table_row().'
                   6384:      '.&Apache::loncommon::end_data_table().'
                   6385:    </form>
                   6386:    <br />
                   6387: ');
1.162     albertel 6388: 
1.457     banghart 6389:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6390: 
1.596.2.12.2.  8(raebur 6391:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6392:              $default_form_data."\n".
                   6393:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6394:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6395:              '<th colspan="2">
1.572     www      6396:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6397:              '</th>'."\n".
                   6398:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6399:               &Apache::loncommon::start_data_table_row()."\n".
                   6400:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6401:               '<td> '.$sequence_selector.' </td>'.
                   6402:               &Apache::loncommon::end_data_table_row()."\n".
                   6403:               &Apache::loncommon::start_data_table_row()."\n".
                   6404:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6405:               '<td> '.$file_selector.' </td>'."\n".
                   6406:               &Apache::loncommon::end_data_table_row()."\n".
                   6407:               &Apache::loncommon::start_data_table_row()."\n".
                   6408:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6409:               '<td> '.$format_selector.' </td>'."\n".
                   6410:               &Apache::loncommon::end_data_table_row()."\n".
                   6411:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6412:               '<td> '.&mt('Options').' </td>'."\n".
                   6413:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6414:               &Apache::loncommon::end_data_table_row()."\n".
                   6415:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6416:               '<td colspan="2">'."\n".
                   6417:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6418:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6419:               '</td>'."\n".
                   6420:               &Apache::loncommon::end_data_table_row()."\n".
                   6421:               &Apache::loncommon::end_data_table()."\n".
                   6422:               '</form><br />');
                   6423:     return;
1.75      albertel 6424: }
                   6425: 
1.423     albertel 6426: =pod 
                   6427: 
                   6428: =item username_to_idmap
                   6429: 
1.556     weissno  6430:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6431:     student username:domain.
                   6432: 
                   6433:   Arguments:
                   6434: 
                   6435:     $classlist - reference to the class list hash. This is a hash
                   6436:                  keyed by student name:domain  whose elements are references
1.424     albertel 6437:                  to arrays containing various chunks of information
1.423     albertel 6438:                  about the student. (See loncoursedata for more info).
                   6439: 
                   6440:   Returns
                   6441:     %idmap - the constructed hash
                   6442: 
                   6443: =cut
                   6444: 
1.82      albertel 6445: sub username_to_idmap {
                   6446:     my ($classlist)= @_;
                   6447:     my %idmap;
                   6448:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6449:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6450:5):         unless ($id eq '') {
                   6451:5):             if (!exists($idmap{$id})) {
                   6452:5):                 $idmap{$id} = $student;
                   6453:5):             } else {
                   6454:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6455:5):                 if ($status eq 'Active') {
                   6456:5):                     $idmap{$id} = $student;
                   6457:5):                 }
                   6458:5):             }
                   6459:5):         }
1.82      albertel 6460:     }
                   6461:     return %idmap;
                   6462: }
1.423     albertel 6463: 
                   6464: =pod
                   6465: 
1.424     albertel 6466: =item scantron_fixup_scanline
1.423     albertel 6467: 
                   6468:    Process a requested correction to a scanline.
                   6469: 
                   6470:   Arguments:
1.596.2.12.2.  9(raebur 6471:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6472:     $scan_data         - hash of correction information 
                   6473:                           (see &scantron_getfile())
                   6474:     $line              - existing scanline
                   6475:     $whichline         - line number of the passed in scanline
                   6476:     $field             - type of change to process 
                   6477:                          (either 
1.573     bisitz   6478:                           'ID'     -> correct the student/employee ID
1.423     albertel 6479:                           'CODE'   -> correct the CODE
                   6480:                           'answer' -> fixup the submitted answers)
                   6481:     
                   6482:    $args               - hash of additional info,
                   6483:                           - 'ID' 
                   6484:                                'newid' -> studentID to use in replacement
1.424     albertel 6485:                                           of existing one
1.423     albertel 6486:                           - 'CODE' 
                   6487:                                'CODE_ignore_dup' - set to true if duplicates
                   6488:                                                    should be ignored.
                   6489: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6490:                                         if the existing unfound code should
1.423     albertel 6491:                                         be used as is
                   6492:                           - 'answer'
                   6493:                                'response' - new answer or 'none' if blank
                   6494:                                'question' - the bubble line to change
1.503     raeburn  6495:                                'questionnum' - the question identifier,
                   6496:                                                may include subquestion. 
1.423     albertel 6497: 
                   6498:   Returns:
                   6499:     $line - the modified scanline
                   6500: 
                   6501:   Side effects: 
                   6502:     $scan_data - may be updated
                   6503: 
                   6504: =cut
                   6505: 
1.82      albertel 6506: 
1.157     albertel 6507: sub scantron_fixup_scanline {
                   6508:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6509:     if ($field eq 'ID') {
                   6510: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6511: 	    return ($line,1,'New value too large');
1.157     albertel 6512: 	}
                   6513: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6514: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6515: 				     $args->{'newid'});
                   6516: 	}
                   6517: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6518: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6519: 	if ($args->{'newid'}=~/^\s*$/) {
                   6520: 	    &scan_data($scan_data,"$whichline.user",
                   6521: 		       $args->{'username'}.':'.$args->{'domain'});
                   6522: 	}
1.186     albertel 6523:     } elsif ($field eq 'CODE') {
1.192     albertel 6524: 	if ($args->{'CODE_ignore_dup'}) {
                   6525: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6526: 	}
                   6527: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6528: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6529: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6530: 		return ($line,1,'New CODE value too large');
                   6531: 	    }
                   6532: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6533: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6534: 	    }
                   6535: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6536: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6537: 	}
1.157     albertel 6538:     } elsif ($field eq 'answer') {
1.497     foxr     6539: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6540: 	my $off=$scantron_config->{'Qoff'};
                   6541: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6542: 	my $answer=${off}x$length;
                   6543: 	if ($args->{'response'} eq 'none') {
                   6544: 	    &scan_data($scan_data,
1.503     raeburn  6545: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6546: 	} else {
                   6547: 	    if ($on eq 'letter') {
                   6548: 		my @alphabet=('A'..'Z');
                   6549: 		$answer=$alphabet[$args->{'response'}];
                   6550: 	    } elsif ($on eq 'number') {
                   6551: 		$answer=$args->{'response'}+1;
                   6552: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6553: 	    } else {
1.497     foxr     6554: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6555: 	    }
1.497     foxr     6556: 	    &scan_data($scan_data,
1.503     raeburn  6557: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6558: 	}
1.497     foxr     6559: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6560: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6561:     }
                   6562:     return $line;
                   6563: }
1.423     albertel 6564: 
                   6565: =pod
                   6566: 
                   6567: =item scan_data
                   6568: 
                   6569:     Edit or look up  an item in the scan_data hash.
                   6570: 
                   6571:   Arguments:
                   6572:     $scan_data  - The hash (see scantron_getfile)
                   6573:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6574:                   scantronfilename_key).
1.423     albertel 6575:     $data        - New value of the hash entry.
                   6576:     $delete      - If true, the entry is removed from the hash.
                   6577: 
                   6578:   Returns:
                   6579:     The new value of the hash table field (undefined if deleted).
                   6580: 
                   6581: =cut
                   6582: 
                   6583: 
1.157     albertel 6584: sub scan_data {
                   6585:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6586:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6587:     if (defined($value)) {
                   6588: 	$scan_data->{$filename.'_'.$key} = $value;
                   6589:     }
                   6590:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6591:     return $scan_data->{$filename.'_'.$key};
                   6592: }
1.423     albertel 6593: 
1.495     albertel 6594: # ----- These first few routines are general use routines.----
                   6595: 
                   6596: # Return the number of occurences of a pattern in a string.
                   6597: 
                   6598: sub occurence_count {
                   6599:     my ($string, $pattern) = @_;
                   6600: 
                   6601:     my @matches = ($string =~ /$pattern/g);
                   6602: 
                   6603:     return scalar(@matches);
                   6604: }
                   6605: 
                   6606: 
                   6607: # Take a string known to have digits and convert all the
                   6608: # digits into letters in the range J,A..I.
                   6609: 
                   6610: sub digits_to_letters {
                   6611:     my ($input) = @_;
                   6612: 
                   6613:     my @alphabet = ('J', 'A'..'I');
                   6614: 
                   6615:     my @input    = split(//, $input);
                   6616:     my $output ='';
                   6617:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6618: 	if ($input[$i] =~ /\d/) {
                   6619: 	    $output .= $alphabet[$input[$i]];
                   6620: 	} else {
                   6621: 	    $output .= $input[$i];
                   6622: 	}
                   6623:     }
                   6624:     return $output;
                   6625: }
                   6626: 
1.423     albertel 6627: =pod 
                   6628: 
                   6629: =item scantron_parse_scanline
                   6630: 
                   6631:   Decodes a scanline from the selected scantron file
                   6632: 
                   6633:  Arguments:
                   6634:     line             - The text of the scantron file line to process
                   6635:     whichline        - Line number
                   6636:     scantron_config  - Hash describing the format of the scantron lines.
                   6637:     scan_data        - Hash of extra information about the scanline
                   6638:                        (see scantron_getfile for more information)
                   6639:     just_header      - True if should not process question answers but only
                   6640:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6641:3):     randomorder      - True if randomorder in use
                   6642:3):     randompick       - True if randompick in use
                   6643:3):     sequence         - Exam folder URL
                   6644:3):     master_seq       - Ref to array containing symbs in exam folder
                   6645:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6646:3):                        (corresponding values are resource objects)
                   6647:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6648:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6649:3):                        are refs to an array of resource objects, ordered
                   6650:3):                        according to order used for CODE, when randomorder
                   6651:3):                        and or randompick are in use.
                   6652:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6653:3):                        for current line to question number used for same question
                   6654:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6655:3):     startline        - Ref to hash where key is question number (0 is first)
                   6656:3):                        and value is number of first bubble line for current 
                   6657:3):                        student or code-based randompick and/or randomorder.
                   6658:3):     totalref         - Ref of scalar used to score total number of bubble
                   6659:3):                        lines needed for responses in a scan line (used when
                   6660:3):                        randompick in use. 
                   6661:3): 
1.423     albertel 6662:  Returns:
                   6663:    Hash containing the result of parsing the scanline
                   6664: 
                   6665:    Keys are all proceeded by the string 'scantron.'
                   6666: 
                   6667:        CODE    - the CODE in use for this scanline
                   6668:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6669:                  by the operator
                   6670:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6671:                             CODEs were selected, but the usage has been
                   6672:                             forced by the operator
1.556     weissno  6673:        ID  - student/employee ID
1.423     albertel 6674:        PaperID - if used, the ID number printed on the sheet when the 
                   6675:                  paper was scanned
                   6676:        FirstName - first name from the sheet
                   6677:        LastName  - last name from the sheet
                   6678: 
                   6679:      if just_header was not true these key may also exist
                   6680: 
1.447     foxr     6681:        missingerror - a list of bubble ranges that are considered to be answers
                   6682:                       to a single question that don't have any bubbles filled in.
                   6683:                       Of the form questionnumber:firstbubblenumber:count.
                   6684:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6685:                       to a single question that have more than one bubble filled in.
                   6686:                       Of the form questionnumber::firstbubblenumber:count
                   6687:    
                   6688:                 In the above, count is the number of bubble responses in the
                   6689:                 input line needed to represent the possible answers to the question.
                   6690:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6691:                 per line would have count = 2.
                   6692: 
1.423     albertel 6693:        maxquest     - the number of the last bubble line that was parsed
                   6694: 
                   6695:        (<number> starts at 1)
                   6696:        <number>.answer - zero or more letters representing the selected
                   6697:                          letters from the scanline for the bubble line 
                   6698:                          <number>.
                   6699:                          if blank there was either no bubble or there where
                   6700:                          multiple bubbles, (consult the keys missingerror and
                   6701:                          doubleerror if this is an error condition)
                   6702: 
                   6703: =cut
                   6704: 
1.82      albertel 6705: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6706:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6707:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6708:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6709: 
1.82      albertel 6710:     my %record;
1.596.2.12.2.  6(raebur 6711:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6712:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6713: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6714: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6715: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6716: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6717: 	    $record{'scantron.CODE'}=substr($data,
                   6718: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6719: 					    $$scantron_config{'CODElength'});
1.191     albertel 6720: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6721: 		$record{'scantron.useCODE'}=1;
                   6722: 	    }
1.192     albertel 6723: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6724: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6725: 	    }
1.82      albertel 6726: 	} else {
                   6727: 	    #FIXME interpret first N questions
                   6728: 	}
                   6729:     }
1.83      albertel 6730:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6731: 				  $$scantron_config{'IDlength'});
1.157     albertel 6732:     $record{'scantron.PaperID'}=
                   6733: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6734: 	       $$scantron_config{'PaperIDlength'});
                   6735:     $record{'scantron.FirstName'}=
                   6736: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6737: 	       $$scantron_config{'FirstNamelength'});
                   6738:     $record{'scantron.LastName'}=
                   6739: 	substr($data,$$scantron_config{'LastName'}-1,
                   6740: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6741:     if ($just_header) { return \%record; }
1.194     albertel 6742: 
1.82      albertel 6743:     my @alphabet=('A'..'Z');
                   6744:     my $questnum=0;
1.447     foxr     6745:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6746: 
1.596.2.12.2.  6(raebur 6747:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6748:3):     if ($randompick || $randomorder) {
                   6749:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6750:3):                                          $master_seq,$symb_to_resource,
                   6751:3):                                          $partids_by_symb,$orderedforcode,
                   6752:3):                                          $respnumlookup,$startline);
                   6753:3):         if ($total) {
                   6754:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6755:3):         }
                   6756:3):         if (ref($totalref)) {
                   6757:3):             $$totalref = $total;
                   6758:3):         }
                   6759:3):     }
                   6760:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6761:     chomp($questions);		# Get rid of any trailing \n.
                   6762:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6763:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6764:3):         my $answers_needed;
                   6765:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6766:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6767:3):         } else {
                   6768:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6769:3):         }
1.503     raeburn  6770:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6771:                              || 1;
                   6772:         $questnum++;
                   6773:         my $quest_id = $questnum;
                   6774:         my $currentquest = substr($questions,0,$answer_length);
                   6775:         $questions       = substr($questions,$answer_length);
                   6776:         if (length($currentquest) < $answer_length) { next; }
                   6777: 
1.596.2.12.2.  6(raebur 6778:3):         my $subdivided;
                   6779:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6780:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6781:3):         } else {
                   6782:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6783:3):         }
                   6784:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6785:             my $subquestnum = 1;
                   6786:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6787:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6788:             foreach my $subans (@subanswers_needed) {
                   6789:                 my $subans_length =
                   6790:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6791:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6792:                 $subquestions   = substr($subquestions,$subans_length);
                   6793:                 $quest_id = "$questnum.$subquestnum";
                   6794:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6795:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6796:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6797:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6798:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6799:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6800:                 } else {
                   6801:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6802:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6803:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6804:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6805:                 }
                   6806:                 $subquestnum ++;
                   6807:             }
                   6808:         } else {
                   6809:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6810:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6811:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6812:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6813:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6814:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6815:             } else {
                   6816:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6817:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6818:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6819:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6820:             }
                   6821:         }
                   6822:     }
                   6823:     $record{'scantron.maxquest'}=$questnum;
                   6824:     return \%record;
                   6825: }
1.447     foxr     6826: 
1.596.2.12.2.  6(raebur 6827:3): sub get_master_seq {
          0(raebur 6828:2):     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
          6(raebur 6829:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6830:3):                    (ref($symb_to_resource) eq 'HASH'));
          0(raebur 6831:2):     if ($need_symb_in_map) {
                   6832:2):         return unless (ref($symb_for_examcode) eq 'HASH');
                   6833:2):     }
          6(raebur 6834:3):     my $resource_error;
                   6835:3):     foreach my $resource (@{$resources}) {
                   6836:3):         my $ressymb;
                   6837:3):         if (ref($resource)) {
                   6838:3):             $ressymb = $resource->symb();
                   6839:3):             push(@{$master_seq},$ressymb);
                   6840:3):             $symb_to_resource->{$ressymb} = $resource;
          0(raebur 6841:2):             if ($need_symb_in_map) {
                   6842:2):                 unless ($resource->is_map()) {
                   6843:2):                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6844:2):                     unless (exists($symb_for_examcode->{$map})) {
                   6845:2):                         $symb_for_examcode->{$map} = $ressymb;
                   6846:2):                     }
                   6847:2):                 }
                   6848:2):             }
          6(raebur 6849:3):         } else {
                   6850:3):             $resource_error = 1;
                   6851:3):             last;
                   6852:3):         }
                   6853:3):     }
                   6854:3):     return $resource_error;
                   6855:3): }
                   6856:3): 
                   6857:3): sub get_respnum_lookups {
                   6858:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6859:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6860:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6861:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6862:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6863:3):                    (ref($startline) eq 'HASH'));
                   6864:3):     my ($user,$scancode);
                   6865:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6866:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6867:3):         $scancode = $record->{'scantron.CODE'};
                   6868:3):     } else {
                   6869:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6870:3):     }
                   6871:3):     my @mapresources =
                   6872:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6873:3):                      $orderedforcode);
                   6874:3):     my $total = 0;
                   6875:3):     my $count = 0;
                   6876:3):     foreach my $resource (@mapresources) {
                   6877:3):         my $id = $resource->id();
                   6878:3):         my $symb = $resource->symb();
                   6879:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6880:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6881:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6882:3):                 if ($respnum ne '') {
                   6883:3):                     $respnumlookup->{$count} = $respnum;
                   6884:3):                     $startline->{$count} = $total;
                   6885:3):                     $total += $bubble_lines_per_response{$respnum};
                   6886:3):                     $count ++;
                   6887:3):                 }
                   6888:3):             }
                   6889:3):         }
                   6890:3):     }
                   6891:3):     return $total;
                   6892:3): }
                   6893:3): 
1.503     raeburn  6894: sub scantron_validator_lettnum {
                   6895:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6896:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6897:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6898: 
                   6899:     # Qon 'letter' implies for each slot in currquest we have:
                   6900:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6901:     #    about anything else (esp. a value of Qoff) for missing
                   6902:     #    bubbles.
                   6903:     #
                   6904:     # Qon 'number' implies each slot gives a digit that indexes the
                   6905:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6906:     #    and * or ? for double bubbles on a single line.
                   6907:     #
1.447     foxr     6908: 
1.503     raeburn  6909:     my $matchon;
                   6910:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6911:         $matchon = '[A-Z]';
                   6912:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6913:         $matchon = '\d';
                   6914:     }
                   6915:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6916:3):     my $responsenum = $questnum-1;
                   6917:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6918:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6919:3):     }
                   6920:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6921:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6922:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6923:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6924:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6925:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6926:         my @singlelines = split('',$currquest);
                   6927:         foreach my $entry (@singlelines) {
                   6928:             $occurrences = &occurence_count($entry,$matchon);
                   6929:             if ($occurrences > 1) {
                   6930:                 last;
                   6931:             }
1.596.2.12.2.  6(raebur 6932:3):         }
1.503     raeburn  6933:     } else {
                   6934:         $occurrences = &occurence_count($currquest,$matchon); 
                   6935:     }
                   6936:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6937:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6938:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6939:             my $bubble = substr($currquest,$ans,1);
                   6940:             if ($bubble =~ /$matchon/ ) {
                   6941:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6942:                     if ($bubble == 0) {
                   6943:                         $bubble = 10; 
                   6944:                     }
                   6945:                     $record->{"scantron.$ansnum.answer"} = 
                   6946:                         $alphabet->[$bubble-1];
                   6947:                 } else {
                   6948:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6949:                 }
                   6950:             } else {
                   6951:                 $record->{"scantron.$ansnum.answer"}='';
                   6952:             }
                   6953:             $ansnum++;
                   6954:         }
                   6955:     } elsif (!defined($currquest)
                   6956:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6957:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6958:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6959:             $record->{"scantron.$ansnum.answer"}='';
                   6960:             $ansnum++;
                   6961:         }
                   6962:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6963:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6964:         }
                   6965:     } else {
                   6966:         if ($$scantron_config{'Qon'} eq 'number') {
                   6967:             $currquest = &digits_to_letters($currquest);            
                   6968:         }
                   6969:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6970:             my $bubble = substr($currquest,$ans,1);
                   6971:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6972:             $ansnum++;
                   6973:         }
                   6974:     }
                   6975:     return $ansnum;
                   6976: }
1.447     foxr     6977: 
1.503     raeburn  6978: sub scantron_validator_positional {
                   6979:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6980:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6981:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6982: 
1.503     raeburn  6983:     # Otherwise there's a positional notation;
                   6984:     # each bubble line requires Qlength items, and there are filled in
                   6985:     # bubbles for each case where there 'Qon' characters.
                   6986:     #
1.447     foxr     6987: 
1.503     raeburn  6988:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6989: 
1.503     raeburn  6990:     # If the split only gives us one element.. the full length of the
                   6991:     # answer string, no bubbles are filled in:
1.447     foxr     6992: 
1.507     raeburn  6993:     if ($answers_needed eq '') {
                   6994:         return;
                   6995:     }
                   6996: 
1.503     raeburn  6997:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6998:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6999:             $record->{"scantron.$ansnum.answer"}='';
                   7000:             $ansnum++;
                   7001:         }
                   7002:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   7003:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   7004:         }
                   7005:     } elsif (scalar(@array) == 2) {
                   7006:         my $location = length($array[0]);
                   7007:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   7008:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   7009:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7010:             if ($ans eq $line_num) {
                   7011:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   7012:             } else {
                   7013:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   7014:             }
                   7015:             $ansnum++;
                   7016:          }
                   7017:     } else {
                   7018:         #  If there's more than one instance of a bubble character
                   7019:         #  That's a double bubble; with positional notation we can
                   7020:         #  record all the bubbles filled in as well as the
                   7021:         #  fact this response consists of multiple bubbles.
                   7022:         #
1.596.2.12.2.  6(raebur 7023:3):         my $responsenum = $questnum-1;
                   7024:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7025:3):             $responsenum = $respnumlookup->{$questnum-1}
                   7026:3):         }
                   7027:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7028:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7029:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7030:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7031:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7032:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  7033:             my $doubleerror = 0;
                   7034:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   7035:                    (!$doubleerror)) {
                   7036:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   7037:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   7038:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   7039:                if (length(@currarray) > 2) {
                   7040:                    $doubleerror = 1;
                   7041:                } 
                   7042:             }
                   7043:             if ($doubleerror) {
                   7044:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7045:             }
                   7046:         } else {
                   7047:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7048:         }
                   7049:         my $item = $ansnum;
                   7050:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7051:             $record->{"scantron.$item.answer"} = '';
                   7052:             $item ++;
                   7053:         }
1.447     foxr     7054: 
1.503     raeburn  7055:         my @ans=@array;
                   7056:         my $i=0;
                   7057:         my $increment = 0;
                   7058:         while ($#ans) {
                   7059:             $i+=length($ans[0]) + $increment;
                   7060:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   7061:             my $bubble = $i%$$scantron_config{'Qlength'};
                   7062:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   7063:             shift(@ans);
                   7064:             $increment = 1;
                   7065:         }
                   7066:         $ansnum += $answers_needed;
1.82      albertel 7067:     }
1.503     raeburn  7068:     return $ansnum;
1.82      albertel 7069: }
                   7070: 
1.423     albertel 7071: =pod
                   7072: 
                   7073: =item scantron_add_delay
                   7074: 
                   7075:    Adds an error message that occurred during the grading phase to a
                   7076:    queue of messages to be shown after grading pass is complete
                   7077: 
                   7078:  Arguments:
1.424     albertel 7079:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 7080:    $scanline    - the scanline that caused the error
                   7081:    $errormesage - the error message
                   7082:    $errorcode   - a numeric code for the error
                   7083: 
                   7084:  Side Effects:
1.424     albertel 7085:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 7086: 
                   7087: =cut
                   7088: 
1.82      albertel 7089: sub scantron_add_delay {
1.140     albertel 7090:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   7091:     push(@$delayqueue,
                   7092: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   7093: 	  'ecode' => $errorcode }
                   7094: 	 );
1.82      albertel 7095: }
                   7096: 
1.423     albertel 7097: =pod
                   7098: 
                   7099: =item scantron_find_student
                   7100: 
1.424     albertel 7101:    Finds the username for the current scanline
                   7102: 
                   7103:   Arguments:
                   7104:    $scantron_record - hash result from scantron_parse_scanline
                   7105:    $scan_data       - hash of correction information 
                   7106:                       (see &scantron_getfile() form more information)
                   7107:    $idmap           - hash from &username_to_idmap()
                   7108:    $line            - number of current scanline
                   7109:  
                   7110:   Returns:
                   7111:    Either 'username:domain' or undef if unknown
                   7112: 
1.423     albertel 7113: =cut
                   7114: 
1.82      albertel 7115: sub scantron_find_student {
1.157     albertel 7116:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7117:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7118:     if ($scanID =~ /^\s*$/) {
                   7119:  	return &scan_data($scan_data,"$line.user");
                   7120:     }
1.83      albertel 7121:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7122:  	if (lc($id) eq lc($scanID)) {
                   7123:  	    return $$idmap{$id};
                   7124:  	}
1.83      albertel 7125:     }
                   7126:     return undef;
                   7127: }
                   7128: 
1.423     albertel 7129: =pod
                   7130: 
                   7131: =item scantron_filter
                   7132: 
1.424     albertel 7133:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7134:    hidden resources was selected
                   7135: 
1.423     albertel 7136: =cut
                   7137: 
1.83      albertel 7138: sub scantron_filter {
                   7139:     my ($curres)=@_;
1.331     albertel 7140: 
                   7141:     if (ref($curres) && $curres->is_problem()) {
                   7142: 	# if the user has asked to not have either hidden
                   7143: 	# or 'randomout' controlled resources to be graded
                   7144: 	# don't include them
                   7145: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7146: 	    && $curres->randomout) {
                   7147: 	    return 0;
                   7148: 	}
1.83      albertel 7149: 	return 1;
                   7150:     }
                   7151:     return 0;
1.82      albertel 7152: }
                   7153: 
1.423     albertel 7154: =pod
                   7155: 
                   7156: =item scantron_process_corrections
                   7157: 
1.424     albertel 7158:    Gets correction information out of submitted form data and corrects
                   7159:    the scanline
                   7160: 
1.423     albertel 7161: =cut
                   7162: 
1.157     albertel 7163: sub scantron_process_corrections {
                   7164:     my ($r) = @_;
1.596.2.12.2.  9(raebur 7165:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7166:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7167:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7168:     my $which=$env{'form.scantron_line'};
1.200     albertel 7169:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7170:     my ($skip,$err,$errmsg);
1.257     albertel 7171:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7172: 	$skip=1;
1.257     albertel 7173:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7174: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7175: 	    $env{'form.scantron_domain'};
1.157     albertel 7176: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7177: 	($line,$err,$errmsg)=
                   7178: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7179: 				     'ID',{'newid'=>$newid,
1.257     albertel 7180: 				    'username'=>$env{'form.scantron_username'},
                   7181: 				    'domain'=>$env{'form.scantron_domain'}});
                   7182:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7183: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7184: 	my $newCODE;
1.192     albertel 7185: 	my %args;
1.190     albertel 7186: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7187: 	    $newCODE='use_unfound';
1.190     albertel 7188: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7189: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7190: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7191: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7192: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7193: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7194: 	}
1.257     albertel 7195: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7196: 	    $args{'CODE_ignore_dup'}=1;
                   7197: 	}
                   7198: 	$args{'CODE'}=$newCODE;
1.186     albertel 7199: 	($line,$err,$errmsg)=
                   7200: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7201: 				     'CODE',\%args);
1.257     albertel 7202:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7203: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7204: 	    ($line,$err,$errmsg)=
                   7205: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7206: 					 $which,'answer',
                   7207: 					 { 'question'=>$question,
1.503     raeburn  7208: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7209:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7210: 	    if ($err) { last; }
                   7211: 	}
                   7212:     }
                   7213:     if ($err) {
1.596.2.12.2.  0(raebur 7214:3): 	$r->print(
                   7215:3):             '<p class="LC_error">'
                   7216:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7217:3):                 $errmsg)
          1(raebur 7218:3):            .'</p>');
1.157     albertel 7219:     } else {
1.200     albertel 7220: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7221: 	&scantron_putfile($scanlines,$scan_data);
                   7222:     }
                   7223: }
                   7224: 
1.423     albertel 7225: =pod
                   7226: 
                   7227: =item reset_skipping_status
                   7228: 
1.424     albertel 7229:    Forgets the current set of remember skipped scanlines (and thus
                   7230:    reverts back to considering all lines in the
                   7231:    scantron_skipped_<filename> file)
                   7232: 
1.423     albertel 7233: =cut
                   7234: 
1.200     albertel 7235: sub reset_skipping_status {
                   7236:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7237:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7238:     &scantron_putfile(undef,$scan_data);
                   7239: }
                   7240: 
1.423     albertel 7241: =pod
                   7242: 
                   7243: =item start_skipping
                   7244: 
1.424     albertel 7245:    Marks a scanline to be skipped. 
                   7246: 
1.423     albertel 7247: =cut
                   7248: 
1.376     albertel 7249: sub start_skipping {
1.200     albertel 7250:     my ($scan_data,$i)=@_;
                   7251:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7252:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7253: 	$remembered{$i}=2;
                   7254:     } else {
                   7255: 	$remembered{$i}=1;
                   7256:     }
1.200     albertel 7257:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7258: }
                   7259: 
1.423     albertel 7260: =pod
                   7261: 
                   7262: =item should_be_skipped
                   7263: 
1.424     albertel 7264:    Checks whether a scanline should be skipped.
                   7265: 
1.423     albertel 7266: =cut
                   7267: 
1.200     albertel 7268: sub should_be_skipped {
1.376     albertel 7269:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7270:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7271: 	# not redoing old skips
1.376     albertel 7272: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7273: 	return 0;
                   7274:     }
                   7275:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7276: 
                   7277:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7278: 	return 0;
                   7279:     }
1.200     albertel 7280:     return 1;
                   7281: }
                   7282: 
1.423     albertel 7283: =pod
                   7284: 
                   7285: =item remember_current_skipped
                   7286: 
1.424     albertel 7287:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7288:    file and remembers them into scan_data for later use.
                   7289: 
1.423     albertel 7290: =cut
                   7291: 
1.200     albertel 7292: sub remember_current_skipped {
                   7293:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7294:     my %to_remember;
                   7295:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7296: 	if ($scanlines->{'skipped'}[$i]) {
                   7297: 	    $to_remember{$i}=1;
                   7298: 	}
                   7299:     }
1.376     albertel 7300: 
1.200     albertel 7301:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7302:     &scantron_putfile(undef,$scan_data);
                   7303: }
                   7304: 
1.423     albertel 7305: =pod
                   7306: 
                   7307: =item check_for_error
                   7308: 
1.424     albertel 7309:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7310:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7311:     something went wrong.
                   7312: 
1.423     albertel 7313: =cut
                   7314: 
1.200     albertel 7315: sub check_for_error {
                   7316:     my ($r,$result)=@_;
                   7317:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7318: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7319:     }
                   7320: }
1.157     albertel 7321: 
1.423     albertel 7322: =pod
                   7323: 
                   7324: =item scantron_warning_screen
                   7325: 
1.424     albertel 7326:    Interstitial screen to make sure the operator has selected the
                   7327:    correct options before we start the validation phase.
                   7328: 
1.423     albertel 7329: =cut
                   7330: 
1.203     albertel 7331: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7332:0):     my ($button_text,$symb)=@_;
1.257     albertel 7333:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7334:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7335:     my $CODElist;
1.284     albertel 7336:     if ($scantron_config{'CODElocation'} &&
                   7337: 	$scantron_config{'CODEstart'} &&
                   7338: 	$scantron_config{'CODElength'}) {
                   7339: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7340:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7341: 	$CODElist=
1.492     albertel 7342: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7343: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7344:     }
1.596.2.12.2.  (raeburn 7345:):     my $lastbubblepoints;
                   7346:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7347:):         $lastbubblepoints =
                   7348:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7349:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7350:):     }
1.492     albertel 7351:     return ('
1.203     albertel 7352: <p>
1.492     albertel 7353: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7354:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7355: </p>
                   7356: <table>
1.492     albertel 7357: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7358: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.596.2.12.2.  (raeburn 7359:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7360: </table>
1.596.2.12.2.  1(raebur 7361:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7362:0): '.&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>
1.203     albertel 7363: 
                   7364: <br />
1.492     albertel 7365: ');
1.203     albertel 7366: }
                   7367: 
1.423     albertel 7368: =pod
                   7369: 
                   7370: =item scantron_do_warning
                   7371: 
1.424     albertel 7372:    Check if the operator has picked something for all required
                   7373:    fields. Error out if something is missing.
                   7374: 
1.423     albertel 7375: =cut
                   7376: 
1.203     albertel 7377: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7378:0):     my ($r,$symb)=@_;
1.203     albertel 7379:     if (!$symb) {return '';}
1.324     albertel 7380:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7381:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7382:     if ( $env{'form.selectpage'} eq '' ||
                   7383: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7384: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7385: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7386: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7387: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7388: 	} 
1.257     albertel 7389: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7390: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.237     albertel 7391: 	} 
1.257     albertel 7392: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7393: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 7394: 	} 
                   7395:     } else {
1.596.2.12.2.  1(raebur 7396:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7397:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7398: 	$r->print('
1.596.2.12.2.  (raeburn 7399:): '.$warning.$bubbledbyhand.'
1.492     albertel 7400: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7401: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7402: ');
1.237     albertel 7403:     }
1.596.2.12.2.  1(raebur 7404:0):     $r->print("</form><br />");
1.203     albertel 7405:     return '';
                   7406: }
                   7407: 
1.423     albertel 7408: =pod
                   7409: 
                   7410: =item scantron_form_start
                   7411: 
1.424     albertel 7412:     html hidden input for remembering all selected grading options
                   7413: 
1.423     albertel 7414: =cut
                   7415: 
1.203     albertel 7416: sub scantron_form_start {
                   7417:     my ($max_bubble)=@_;
                   7418:     my $result= <<SCANTRONFORM;
                   7419: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7420:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7421:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7422:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7423:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7424:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7425:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7426:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7427:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7428:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7429: SCANTRONFORM
1.447     foxr     7430: 
                   7431:   my $line = 0;
                   7432:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7433:        my $chunk =
                   7434: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7435:        $chunk .=
                   7436: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7437:        $chunk .= 
                   7438:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7439:        $chunk .=
                   7440:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7441:3):        $chunk .=
                   7442:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7443:        $result .= $chunk;
                   7444:        $line++;
1.596.2.12.2.  6(raebur 7445:3):     }
1.203     albertel 7446:     return $result;
                   7447: }
                   7448: 
1.423     albertel 7449: =pod
                   7450: 
                   7451: =item scantron_validate_file
                   7452: 
1.596.2.6  raeburn  7453:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7454: 
                   7455:     Also processes any necessary information resets that need to
                   7456:     occur before validation begins (ignore previous corrections,
                   7457:     restarting the skipped records processing)
                   7458: 
1.423     albertel 7459: =cut
                   7460: 
1.157     albertel 7461: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7462:0):     my ($r,$symb) = @_;
1.157     albertel 7463:     if (!$symb) {return '';}
1.324     albertel 7464:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7465:     
1.596.2.12.2.  0(raebur 7466:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7467:     # them when doing the corrections reset
1.257     albertel 7468:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7469: 	&reset_skipping_status();
                   7470:     }
1.257     albertel 7471:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7472: 	&remember_current_skipped();
1.257     albertel 7473: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7474:     }
                   7475: 
1.257     albertel 7476:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7477: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7478: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7479: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7480: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7481:     }
1.200     albertel 7482: 
1.257     albertel 7483:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7484: 	&scantron_process_corrections($r);
                   7485:     }
1.503     raeburn  7486:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7487:     #get the student pick code ready
                   7488:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7489:     my $nav_error;
1.596.2.12.2.  9(raebur 7490:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7491:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7492:     if ($nav_error) {
                   7493:         $r->print(&navmap_errormsg());
                   7494:         return '';
                   7495:     }
1.203     albertel 7496:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7497:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7498:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7499:):     }
1.157     albertel 7500:     $r->print($result);
                   7501:     
1.334     albertel 7502:     my @validate_phases=( 'sequence',
                   7503: 			  'ID',
1.157     albertel 7504: 			  'CODE',
                   7505: 			  'doublebubble',
                   7506: 			  'missingbubbles');
1.257     albertel 7507:     if (!$env{'form.validatepass'}) {
                   7508: 	$env{'form.validatepass'} = 0;
1.157     albertel 7509:     }
1.257     albertel 7510:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7511: 
1.448     foxr     7512: 
1.157     albertel 7513:     my $stop=0;
                   7514:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7515: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7516: 	$r->rflush();
1.596.2.12.2.  6(raebur 7517:3): 
1.157     albertel 7518: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7519: 	{
                   7520: 	    no strict 'refs';
                   7521: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7522: 	}
                   7523:     }
                   7524:     if (!$stop) {
1.596.2.12.2.  1(raebur 7525:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7526: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7527:                   $warning.
                   7528:                   &mt('Perform verification for each student after storage of submissions?').
                   7529:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7530:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7531:                   ('&nbsp;'x3).'<label>'.
                   7532:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7533:                   '</label></span><br />'.
                   7534:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7535:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7536:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7537:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7538:     } else {
                   7539: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7540: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7541:     }
                   7542:     if ($stop) {
1.334     albertel 7543: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7544: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7545: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7546: 
1.596.2.12.2.  1(raebur 7547:0):             $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>');
1.334     albertel 7548: 	} else {
1.503     raeburn  7549:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7550: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7551:             } else {
1.539     riegler  7552:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7553:             }
1.492     albertel 7554: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7555: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7556: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7557: 	}
1.157     albertel 7558:     }
1.596.2.12.2.  1(raebur 7559:0):     $r->print(" </form><br />");
1.157     albertel 7560:     return '';
                   7561: }
                   7562: 
1.423     albertel 7563: 
                   7564: =pod
                   7565: 
                   7566: =item scantron_remove_file
                   7567: 
1.596.2.6  raeburn  7568:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7569:    scantron_original_<filename> is never removed
                   7570: 
                   7571: 
1.423     albertel 7572: =cut
                   7573: 
1.200     albertel 7574: sub scantron_remove_file {
1.192     albertel 7575:     my ($which)=@_;
1.257     albertel 7576:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7577:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7578:     my $file='scantron_';
1.200     albertel 7579:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7580: 	$file.=$which.'_';
1.192     albertel 7581:     } else {
                   7582: 	return 'refused';
                   7583:     }
1.257     albertel 7584:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7585:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7586: }
                   7587: 
1.423     albertel 7588: 
                   7589: =pod
                   7590: 
                   7591: =item scantron_remove_scan_data
                   7592: 
1.596.2.6  raeburn  7593:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7594:    data file.  (In the case that both the are doing skipped records we need
                   7595:    to remember the old skipped lines for the time being so that element
                   7596:    persists for a while.)
                   7597: 
1.423     albertel 7598: =cut
                   7599: 
1.200     albertel 7600: sub scantron_remove_scan_data {
1.257     albertel 7601:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7602:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7603:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7604:     my @todelete;
1.257     albertel 7605:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7606:     foreach my $key (@keys) {
                   7607: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7608: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7609: 		$key=~/remember_skipping/) {
                   7610: 		next;
                   7611: 	    }
1.192     albertel 7612: 	    push(@todelete,$key);
                   7613: 	}
                   7614:     }
1.200     albertel 7615:     my $result;
1.192     albertel 7616:     if (@todelete) {
1.491     albertel 7617: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7618: 				       \@todelete,$cdom,$cname);
                   7619:     } else {
                   7620: 	$result = 'ok';
1.192     albertel 7621:     }
                   7622:     return $result;
                   7623: }
                   7624: 
1.423     albertel 7625: 
                   7626: =pod
                   7627: 
                   7628: =item scantron_getfile
                   7629: 
1.596.2.6  raeburn  7630:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7631:     the scan_data hash
                   7632:   
                   7633:   Arguments:
                   7634:     None
                   7635: 
                   7636:   Returns:
                   7637:     2 hash references
                   7638: 
                   7639:      - first one has 
                   7640:          orig      -
                   7641:          corrected -
                   7642:          skipped   -  each of which points to an array ref of the specified
                   7643:                       file broken up into individual lines
                   7644:          count     - number of scanlines
                   7645:  
                   7646:      - second is the scan_data hash possible keys are
1.425     albertel 7647:        ($number refers to scanline numbered $number and thus the key affects
                   7648:         only that scanline
                   7649:         $bubline refers to the specific bubble line element and the aspects
                   7650:         refers to that specific bubble line element)
                   7651: 
                   7652:        $number.user - username:domain to use
                   7653:        $number.CODE_ignore_dup 
                   7654:                     - ignore the duplicate CODE error 
                   7655:        $number.useCODE
                   7656:                     - use the CODE in the scanline as is
                   7657:        $number.no_bubble.$bubline
                   7658:                     - it is valid that there is no bubbled in bubble
                   7659:                       at $number $bubline
                   7660:        remember_skipping
                   7661:                     - a frozen hash containing keys of $number and values
                   7662:                       of either 
                   7663:                         1 - we are on a 'do skipped records pass' and plan
                   7664:                             on processing this line
                   7665:                         2 - we are on a 'do skipped records pass' and this
                   7666:                             scanline has been marked to skip yet again
1.424     albertel 7667: 
1.423     albertel 7668: =cut
                   7669: 
1.157     albertel 7670: sub scantron_getfile {
1.200     albertel 7671:     #FIXME really would prefer a scantron directory
1.257     albertel 7672:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7673:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7674:     my $lines;
                   7675:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7676: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7677:     my %scanlines;
                   7678:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7679:     my $temp=$scanlines{'orig'};
                   7680:     $scanlines{'count'}=$#$temp;
                   7681: 
                   7682:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7683: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7684:     if ($lines eq '-1') {
                   7685: 	$scanlines{'corrected'}=[];
                   7686:     } else {
                   7687: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7688:     }
                   7689:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7690: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7691:     if ($lines eq '-1') {
                   7692: 	$scanlines{'skipped'}=[];
                   7693:     } else {
                   7694: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7695:     }
1.175     albertel 7696:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7697:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7698:     my %scan_data = @tmp;
                   7699:     return (\%scanlines,\%scan_data);
                   7700: }
                   7701: 
1.423     albertel 7702: =pod
                   7703: 
                   7704: =item lonnet_putfile
                   7705: 
1.424     albertel 7706:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7707: 
                   7708:  Arguments:
                   7709:    $contents - data to store
                   7710:    $filename - filename to store $contents into
                   7711: 
                   7712:  Returns:
                   7713:    result value from &Apache::lonnet::finishuserfileupload
                   7714: 
1.423     albertel 7715: =cut
                   7716: 
1.157     albertel 7717: sub lonnet_putfile {
                   7718:     my ($contents,$filename)=@_;
1.257     albertel 7719:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7720:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7721:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7722:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7723: 
                   7724: }
                   7725: 
1.423     albertel 7726: =pod
                   7727: 
                   7728: =item scantron_putfile
                   7729: 
1.596.2.6  raeburn  7730:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7731:     scan_data hash. (Does not modify the original version only the
                   7732:     corrected and skipped versions.
                   7733: 
                   7734:  Arguments:
                   7735:     $scanlines - hash ref that looks like the first return value from
                   7736:                  &scantron_getfile()
                   7737:     $scan_data - hash ref that looks like the second return value from
                   7738:                  &scantron_getfile()
                   7739: 
1.423     albertel 7740: =cut
                   7741: 
1.157     albertel 7742: sub scantron_putfile {
                   7743:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7744:     #FIXME really would prefer a scantron directory
1.257     albertel 7745:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7746:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7747:     if ($scanlines) {
                   7748: 	my $prefix='scantron_';
1.157     albertel 7749: # no need to update orig, shouldn't change
                   7750: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7751: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7752: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7753: 			$prefix.'corrected_'.
1.257     albertel 7754: 			$env{'form.scantron_selectfile'});
1.200     albertel 7755: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7756: 			$prefix.'skipped_'.
1.257     albertel 7757: 			$env{'form.scantron_selectfile'});
1.200     albertel 7758:     }
1.175     albertel 7759:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7760: }
                   7761: 
1.423     albertel 7762: =pod
                   7763: 
                   7764: =item scantron_get_line
                   7765: 
1.424     albertel 7766:    Returns the correct version of the scanline
                   7767: 
                   7768:  Arguments:
                   7769:     $scanlines - hash ref that looks like the first return value from
                   7770:                  &scantron_getfile()
                   7771:     $scan_data - hash ref that looks like the second return value from
                   7772:                  &scantron_getfile()
                   7773:     $i         - number of the requested line (starts at 0)
                   7774: 
                   7775:  Returns:
                   7776:    A scanline, (either the original or the corrected one if it
                   7777:    exists), or undef if the requested scanline should be
                   7778:    skipped. (Either because it's an skipped scanline, or it's an
                   7779:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7780:    pass.
                   7781: 
1.423     albertel 7782: =cut
                   7783: 
1.157     albertel 7784: sub scantron_get_line {
1.200     albertel 7785:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7786:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7787:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7788:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7789:     return $scanlines->{'orig'}[$i]; 
                   7790: }
                   7791: 
1.423     albertel 7792: =pod
                   7793: 
                   7794: =item scantron_todo_count
                   7795: 
1.424     albertel 7796:     Counts the number of scanlines that need processing.
                   7797: 
                   7798:  Arguments:
                   7799:     $scanlines - hash ref that looks like the first return value from
                   7800:                  &scantron_getfile()
                   7801:     $scan_data - hash ref that looks like the second return value from
                   7802:                  &scantron_getfile()
                   7803: 
                   7804:  Returns:
                   7805:     $count - number of scanlines to process
                   7806: 
1.423     albertel 7807: =cut
                   7808: 
1.200     albertel 7809: sub get_todo_count {
                   7810:     my ($scanlines,$scan_data)=@_;
                   7811:     my $count=0;
                   7812:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7813: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7814: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7815: 	$count++;
                   7816:     }
                   7817:     return $count;
                   7818: }
                   7819: 
1.423     albertel 7820: =pod
                   7821: 
                   7822: =item scantron_put_line
                   7823: 
1.596.2.6  raeburn  7824:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7825:     data file.
                   7826: 
                   7827:  Arguments:
                   7828:     $scanlines - hash ref that looks like the first return value from
                   7829:                  &scantron_getfile()
                   7830:     $scan_data - hash ref that looks like the second return value from
                   7831:                  &scantron_getfile()
                   7832:     $i         - line number to update
                   7833:     $newline   - contents of the updated scanline
                   7834:     $skip      - if true make the line for skipping and update the
                   7835:                  'skipped' file
                   7836: 
1.423     albertel 7837: =cut
                   7838: 
1.157     albertel 7839: sub scantron_put_line {
1.200     albertel 7840:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7841:     if ($skip) {
                   7842: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7843: 	&start_skipping($scan_data,$i);
1.157     albertel 7844: 	return;
                   7845:     }
                   7846:     $scanlines->{'corrected'}[$i]=$newline;
                   7847: }
                   7848: 
1.423     albertel 7849: =pod
                   7850: 
                   7851: =item scantron_clear_skip
                   7852: 
1.424     albertel 7853:    Remove a line from the 'skipped' file
                   7854: 
                   7855:  Arguments:
                   7856:     $scanlines - hash ref that looks like the first return value from
                   7857:                  &scantron_getfile()
                   7858:     $scan_data - hash ref that looks like the second return value from
                   7859:                  &scantron_getfile()
                   7860:     $i         - line number to update
                   7861: 
1.423     albertel 7862: =cut
                   7863: 
1.376     albertel 7864: sub scantron_clear_skip {
                   7865:     my ($scanlines,$scan_data,$i)=@_;
                   7866:     if (exists($scanlines->{'skipped'}[$i])) {
                   7867: 	undef($scanlines->{'skipped'}[$i]);
                   7868: 	return 1;
                   7869:     }
                   7870:     return 0;
                   7871: }
                   7872: 
1.423     albertel 7873: =pod
                   7874: 
                   7875: =item scantron_filter_not_exam
                   7876: 
1.424     albertel 7877:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7878:    filter out resources that are not marked as 'exam' mode
                   7879: 
1.423     albertel 7880: =cut
                   7881: 
1.334     albertel 7882: sub scantron_filter_not_exam {
                   7883:     my ($curres)=@_;
                   7884:     
                   7885:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7886: 	# if the user has asked to not have either hidden
                   7887: 	# or 'randomout' controlled resources to be graded
                   7888: 	# don't include them
                   7889: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7890: 	    && $curres->randomout) {
                   7891: 	    return 0;
                   7892: 	}
                   7893: 	return 1;
                   7894:     }
                   7895:     return 0;
                   7896: }
                   7897: 
1.423     albertel 7898: =pod
                   7899: 
                   7900: =item scantron_validate_sequence
                   7901: 
1.424     albertel 7902:     Validates the selected sequence, checking for resource that are
                   7903:     not set to exam mode.
                   7904: 
1.423     albertel 7905: =cut
                   7906: 
1.334     albertel 7907: sub scantron_validate_sequence {
                   7908:     my ($r,$currentphase) = @_;
                   7909: 
                   7910:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7911:     unless (ref($navmap)) {
                   7912:         $r->print(&navmap_errormsg());
                   7913:         return (1,$currentphase);
                   7914:     }
1.334     albertel 7915:     my (undef,undef,$sequence)=
                   7916: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7917: 
                   7918:     my $map=$navmap->getResourceByUrl($sequence);
                   7919: 
                   7920:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7921:                                     value="ignore" />');
                   7922:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7923: 	my @resources=
                   7924: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7925: 	if (@resources) {
1.596.2.12.2.  0(raebur 7926:2): 	    $r->print('<p class="LC_warning">'
                   7927:2):                .&mt('Some resources in the sequence currently are not set to'
                   7928:2):                    .' exam mode. Grading these resources currently may not'
                   7929:2):                    .' work correctly.')
                   7930:2):                .'</p>'
                   7931:2):             );
1.334     albertel 7932: 	    return (1,$currentphase);
                   7933: 	}
                   7934:     }
                   7935: 
                   7936:     return (0,$currentphase+1);
                   7937: }
                   7938: 
1.423     albertel 7939: 
                   7940: 
1.157     albertel 7941: sub scantron_validate_ID {
                   7942:     my ($r,$currentphase) = @_;
                   7943:     
                   7944:     #get student info
                   7945:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7946:     my %idmap=&username_to_idmap($classlist);
                   7947: 
                   7948:     #get scantron line setup
1.596.2.12.2.  9(raebur 7949:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7950:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7951: 
                   7952:     my $nav_error;
1.596.2.12.2.  (raeburn 7953:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7954:     if ($nav_error) {
                   7955:         $r->print(&navmap_errormsg());
                   7956:         return(1,$currentphase);
                   7957:     }
1.157     albertel 7958: 
                   7959:     my %found=('ids'=>{},'usernames'=>{});
                   7960:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7961: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7962: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7963: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7964: 						 $scan_data);
                   7965: 	my $id=$$scan_record{'scantron.ID'};
                   7966: 	my $found;
                   7967: 	foreach my $checkid (keys(%idmap)) {
                   7968: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7969: 	}
                   7970: 	if ($found) {
                   7971: 	    my $username=$idmap{$found};
                   7972: 	    if ($found{'ids'}{$found}) {
                   7973: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7974: 					 $line,'duplicateID',$found);
1.194     albertel 7975: 		return(1,$currentphase);
1.157     albertel 7976: 	    } elsif ($found{'usernames'}{$username}) {
                   7977: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7978: 					 $line,'duplicateID',$username);
1.194     albertel 7979: 		return(1,$currentphase);
1.157     albertel 7980: 	    }
1.186     albertel 7981: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7982: 	    $found{'ids'}{$found}++;
                   7983: 	    $found{'usernames'}{$username}++;
                   7984: 	} else {
                   7985: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7986: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7987: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7988: 		    &scantron_get_correction($r,$i,$scan_record,
                   7989: 					     \%scantron_config,
                   7990: 					     $line,'duplicateID',$username);
1.194     albertel 7991: 		    return(1,$currentphase);
1.157     albertel 7992: 		} elsif (!defined($username)) {
                   7993: 		    &scantron_get_correction($r,$i,$scan_record,
                   7994: 					     \%scantron_config,
                   7995: 					     $line,'incorrectID');
1.194     albertel 7996: 		    return(1,$currentphase);
1.157     albertel 7997: 		}
                   7998: 		$found{'usernames'}{$username}++;
                   7999: 	    } else {
                   8000: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8001: 					 $line,'incorrectID');
1.194     albertel 8002: 		return(1,$currentphase);
1.157     albertel 8003: 	    }
                   8004: 	}
                   8005:     }
                   8006: 
                   8007:     return (0,$currentphase+1);
                   8008: }
                   8009: 
1.423     albertel 8010: 
1.157     albertel 8011: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 8012:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8013:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8014: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8015: #to show both the current line and the previous one and allow skipping
                   8016: #the previous one or the current one
                   8017: 
1.333     albertel 8018:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  8019:         $r->print(
                   8020:             '<p class="LC_warning">'
                   8021:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8022:                 "<b>$error</b>",
                   8023:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8024:            ."</p> \n");
1.157     albertel 8025:     } else {
1.596.2.6  raeburn  8026:         $r->print(
                   8027:             '<p class="LC_warning">'
                   8028:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8029:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8030:            ."</p> \n");
                   8031:     }
                   8032:     my $message =
                   8033:         '<p>'
                   8034:        .&mt('The ID on the form is [_1]',
                   8035:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8036:        .'<br />'
1.596.2.12  raeburn  8037:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  8038:             $$scan_record{'scantron.LastName'},
                   8039:             $$scan_record{'scantron.FirstName'})
                   8040:        .'</p>';
1.242     albertel 8041: 
1.157     albertel 8042:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8043:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8044:                            # Array populated for doublebubble or
                   8045:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8046:                            # to validate radio button checking   
                   8047: 
1.157     albertel 8048:     if ($error =~ /ID$/) {
1.186     albertel 8049: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  8050: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8051: 		      "</p>\n");
1.157     albertel 8052: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  8053: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 8054: 	}
1.242     albertel 8055: 	$r->print($message);
1.492     albertel 8056: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8057: 	$r->print("\n<ul><li> ");
                   8058: 	#FIXME it would be nice if this sent back the user ID and
                   8059: 	#could do partial userID matches
                   8060: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8061: 				       'scantron_username','scantron_domain'));
                   8062: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 8063:3): 	$r->print("\n:\n".
1.257     albertel 8064: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8065: 
                   8066: 	$r->print('</li>');
1.186     albertel 8067:     } elsif ($error =~ /CODE$/) {
                   8068: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  8069: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8070: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  8071: 	    $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");
1.186     albertel 8072: 	}
1.596.2.6  raeburn  8073:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   8074:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8075:                  ."</p>\n");
1.242     albertel 8076: 	$r->print($message);
1.596.2.6  raeburn  8077: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8078: 	$r->print("\n<br /> ");
1.194     albertel 8079: 	my $i=0;
1.273     albertel 8080: 	if ($error eq 'incorrectCODE' 
                   8081: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8082: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8083: 	    if ($closest > 0) {
                   8084: 		foreach my $testcode (@{$closest}) {
                   8085: 		    my $checked='';
1.569     bisitz   8086: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8087: 		    $r->print("
                   8088:    <label>
1.569     bisitz   8089:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8090:        ".&mt("Use the similar CODE [_1] instead.",
                   8091: 	    "<b><tt>".$testcode."</tt></b>")."
                   8092:     </label>
                   8093:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8094: 		    $r->print("\n<br />");
                   8095: 		    $i++;
                   8096: 		}
1.194     albertel 8097: 	    }
                   8098: 	}
1.273     albertel 8099: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8100: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8101: 	    $r->print("
                   8102:     <label>
1.569     bisitz   8103:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  8104:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8105: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8106:     </label>");
1.273     albertel 8107: 	    $r->print("\n<br />");
                   8108: 	}
1.194     albertel 8109: 
1.596.2.12.2.  1(raebur 8110:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8111: function change_radio(field) {
1.190     albertel 8112:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8113:     var i;
                   8114:     for (i=0;i<slct.length;i++) {
                   8115:         if (slct[i].value==field) { slct[i].checked=true; }
                   8116:     }
                   8117: }
                   8118: ENDSCRIPT
1.187     albertel 8119: 	my $href="/adm/pickcode?".
1.359     www      8120: 	   "form=".&escape("scantronupload").
                   8121: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8122: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8123: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8124: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8125: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8126: 	    $r->print("
                   8127:     <label>
                   8128:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8129:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8130: 	     "<a target='_blank' href='$href'>","</a>")."
                   8131:     </label> 
1.558     bisitz   8132:     ".&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\')" />'));
1.332     albertel 8133: 	    $r->print("\n<br />");
                   8134: 	}
1.492     albertel 8135: 	$r->print("
                   8136:     <label>
                   8137:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8138:        ".&mt("Use [_1] as the CODE.",
                   8139: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
1.187     albertel 8140: 	$r->print("\n<br /><br />");
1.157     albertel 8141:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  8142: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8143: 
                   8144: 	# The form field scantron_questions is acutally a list of line numbers.
                   8145: 	# represented by this form so:
                   8146: 
1.596.2.12.2.  6(raebur 8147:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8148:3):                                                 $respnumlookup,$startline);
1.497     foxr     8149: 
1.157     albertel 8150: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8151: 		  $line_list.'" />');
1.242     albertel 8152: 	$r->print($message);
1.492     albertel 8153: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8154: 	foreach my $question (@{$arg}) {
1.503     raeburn  8155: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8156:3):                                                    $scan_record, $error,
                   8157:3):                                                    $randomorder,$randompick,
                   8158:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8159:             push(@lines_to_correct,@linenums);
1.157     albertel 8160: 	}
1.503     raeburn  8161:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8162:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  8163: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
1.242     albertel 8164: 	$r->print($message);
1.492     albertel 8165: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8166: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8167: 
1.503     raeburn  8168: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8169: 	# a list of question numbers. Therefore:
                   8170: 	#
                   8171: 	
1.596.2.12.2.  6(raebur 8172:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8173:3):                                                 $respnumlookup,$startline);
1.497     foxr     8174: 
1.157     albertel 8175: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8176: 		  $line_list.'" />');
1.157     albertel 8177: 	foreach my $question (@{$arg}) {
1.503     raeburn  8178: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8179:3):                                                    $scan_record, $error,
                   8180:3):                                                    $randomorder,$randompick,
                   8181:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8182:             push(@lines_to_correct,@linenums);
1.157     albertel 8183: 	}
1.503     raeburn  8184:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8185:     } else {
                   8186: 	$r->print("\n<ul>");
                   8187:     }
                   8188:     $r->print("\n</li></ul>");
1.497     foxr     8189: }
                   8190: 
1.503     raeburn  8191: sub verify_bubbles_checked {
                   8192:     my (@ansnums) = @_;
                   8193:     my $ansnumstr = join('","',@ansnums);
                   8194:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.596.2.12.2.  6(raebur 8195:6):     &js_escape(\$warning);
          1(raebur 8196:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8197: function verify_bubble_radio(form) {
                   8198:     var ansnumArray = new Array ("$ansnumstr");
                   8199:     var need_bubble_count = 0;
                   8200:     for (var i=0; i<ansnumArray.length; i++) {
                   8201:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8202:             var bubble_picked = 0; 
                   8203:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8204:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8205:                     bubble_picked = 1;
                   8206:                 }
                   8207:             }
                   8208:             if (bubble_picked == 0) {
                   8209:                 need_bubble_count ++;
                   8210:             }
                   8211:         }
                   8212:     }
                   8213:     if (need_bubble_count) {
                   8214:         alert("$warning");
                   8215:         return;
                   8216:     }
                   8217:     form.submit(); 
                   8218: }
                   8219: ENDSCRIPT
                   8220:     return $output;
                   8221: }
                   8222: 
1.497     foxr     8223: =pod
                   8224: 
                   8225: =item  questions_to_line_list
1.157     albertel 8226: 
1.497     foxr     8227: Converts a list of questions into a string of comma separated
                   8228: line numbers in the answer sheet used by the questions.  This is
                   8229: used to fill in the scantron_questions form field.
                   8230: 
                   8231:   Arguments:
                   8232:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 8233:3):      randomorder  - True if randomorder in use.
                   8234:3):      randompick   - True if randompick in use.
                   8235:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8236:3):                      for current line to question number used for same question
                   8237:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   8238:3):      startline    - Reference to hash where key is question number (0 is first)
                   8239:3):                     and key is number of first bubble line for current student
                   8240:3):                     or code-based randompick and/or randomorder.
1.497     foxr     8241: 
                   8242: =cut
                   8243: 
                   8244: 
                   8245: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 8246:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8247:     my @lines;
                   8248: 
1.503     raeburn  8249:     foreach my $item (@{$questions}) {
                   8250:         my $question = $item;
                   8251:         my ($first,$count,$last);
                   8252:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8253:             $question = $1;
                   8254:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 8255:3):             my $responsenum = $question-1;
                   8256:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8257:3):                 $responsenum = $respnumlookup->{$question-1};
                   8258:3):                 if (ref($startline) eq 'HASH') {
                   8259:3):                     $first = $startline->{$question-1} + 1;
                   8260:3):                 }
                   8261:3):             } else {
                   8262:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8263:3):             }
          7(raebur 8264:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8265:             my $subcount = 1;
                   8266:             while ($subcount<$subquestion) {
                   8267:                 $first += $subans[$subcount-1];
                   8268:                 $subcount ++;
                   8269:             }
                   8270:             $count = $subans[$subquestion-1];
                   8271:         } else {
1.596.2.12.2.  7(raebur 8272:3):             my $responsenum = $question-1;
                   8273:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8274:3):                 $responsenum = $respnumlookup->{$question-1};
                   8275:3):                 if (ref($startline) eq 'HASH') {
                   8276:3):                     $first = $startline->{$question-1} + 1;
                   8277:3):                 }
                   8278:3):             } else {
                   8279:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8280:3):             }
                   8281:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8282:         }
1.506     raeburn  8283:         $last = $first+$count-1;
1.503     raeburn  8284:         push(@lines, ($first..$last));
1.497     foxr     8285:     }
                   8286:     return join(',', @lines);
                   8287: }
                   8288: 
                   8289: =pod 
                   8290: 
                   8291: =item prompt_for_corrections
                   8292: 
                   8293: Prompts for a potentially multiline correction to the
                   8294: user's bubbling (factors out common code from scantron_get_correction
                   8295: for multi and missing bubble cases).
                   8296: 
                   8297:  Arguments:
                   8298:    $r           - Apache request object.
                   8299:    $question    - The question number to prompt for.
                   8300:    $scan_config - The scantron file configuration hash.
                   8301:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8302:    $error       - Type of error
1.596.2.12.2.  7(raebur 8303:3):    $randomorder - True if randomorder in use.
                   8304:3):    $randompick  - True if randompick in use.
                   8305:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8306:3):                     for current line to question number used for same question
                   8307:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8308:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8309:3):                   and value is number of first bubble line for current student
                   8310:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8311: 
                   8312:  Implicit inputs:
                   8313:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8314:                                   Numbered from 0 (but question numbers are from
                   8315:                                   1.
                   8316:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8317:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8318:                                   type problems render as separate sub-questions, 
1.503     raeburn  8319:                                   in exam mode. This hash contains a 
                   8320:                                   comma-separated list of the lines per 
                   8321:                                   sub-question.
1.510     raeburn  8322:    %responsetype_per_response   - essayresponse, formularesponse,
                   8323:                                   stringresponse, imageresponse, reactionresponse,
                   8324:                                   and organicresponse type problem parts can have
1.503     raeburn  8325:                                   multiple lines per response if the weight
                   8326:                                   assigned exceeds 10.  In this case, only
                   8327:                                   one bubble per line is permitted, but more 
                   8328:                                   than one line might contain bubbles, e.g.
                   8329:                                   bubbling of: line 1 - J, line 2 - J, 
                   8330:                                   line 3 - B would assign 22 points.  
1.497     foxr     8331: 
                   8332: =cut
                   8333: 
                   8334: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8335:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8336:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8337:     my ($current_line,$lines);
                   8338:     my @linenums;
                   8339:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8340:3):     my ($first,$responsenum);
1.503     raeburn  8341:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8342:         $question = $1;
                   8343:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8344:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8345:3):             $responsenum = $respnumlookup->{$question-1};
                   8346:3):             if (ref($startline) eq 'HASH') {
                   8347:3):                 $first = $startline->{$question-1};
                   8348:3):             }
                   8349:3):         } else {
                   8350:3):             $responsenum = $question-1;
          7(raebur 8351:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8352:3):         }
                   8353:3):         $current_line = $first + 1 ;
                   8354:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8355:         my $subcount = 1;
                   8356:         while ($subcount<$subquestion) {
                   8357:             $current_line += $subans[$subcount-1];
                   8358:             $subcount ++;
                   8359:         }
                   8360:         $lines = $subans[$subquestion-1];
                   8361:     } else {
1.596.2.12.2.  6(raebur 8362:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8363:3):             $responsenum = $respnumlookup->{$question-1};
                   8364:3):             if (ref($startline) eq 'HASH') {
                   8365:3):                 $first = $startline->{$question-1};
                   8366:3):             }
                   8367:3):         } else {
                   8368:3):             $responsenum = $question-1;
                   8369:3):             $first = $first_bubble_line{$responsenum};
                   8370:3):         }
                   8371:3):         $current_line = $first + 1;
                   8372:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8373:     }
1.497     foxr     8374:     if ($lines > 1) {
1.503     raeburn  8375:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8376:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8377:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8378:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8379:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8380:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8381:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8382:3):             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  8383:         } else {
                   8384:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8385:         }
1.497     foxr     8386:     }
                   8387:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8388:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8389:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8390: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8391:         push(@linenums,$current_line);
1.497     foxr     8392: 	$current_line++;
                   8393:     }
                   8394:     if ($lines > 1) {
                   8395: 	$r->print("<hr /><br />");
                   8396:     }
1.503     raeburn  8397:     return @linenums;
1.157     albertel 8398: }
1.423     albertel 8399: 
                   8400: =pod
                   8401: 
                   8402: =item scantron_bubble_selector
                   8403:   
                   8404:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8405:    possibly showing the existing the selected bubbles if known
1.423     albertel 8406: 
                   8407:  Arguments:
                   8408:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8409:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8410:     $line        - Number of the line being displayed.
1.503     raeburn  8411:     $questionnum - Question number (may include subquestion)
                   8412:     $error       - Type of error.
1.497     foxr     8413:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8414: 
                   8415: =cut
                   8416: 
1.157     albertel 8417: sub scantron_bubble_selector {
1.503     raeburn  8418:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8419:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8420: 
                   8421:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8422:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8423:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8424:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8425:):             $max=$$scan_config{'BubblesPerRow'};
                   8426:):             if (($scmode eq 'number') && ($max > 10)) {
                   8427:):                 $max = 10;
                   8428:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8429:):                 $max = 26;
                   8430:):             }
                   8431:):         } else {
                   8432:):             $max = 10;
                   8433:):         }
                   8434:):     }
1.274     albertel 8435: 
1.157     albertel 8436:     my @alphabet=('A'..'Z');
1.503     raeburn  8437:     $r->print(&Apache::loncommon::start_data_table().
                   8438:               &Apache::loncommon::start_data_table_row());
                   8439:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8440:     for (my $i=0;$i<$max+1;$i++) {
                   8441: 	$r->print("\n".'<td align="center">');
                   8442: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8443: 	else { $r->print('&nbsp;'); }
                   8444: 	$r->print('</td>');
                   8445:     }
1.503     raeburn  8446:     $r->print(&Apache::loncommon::end_data_table_row().
                   8447:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8448:     for (my $i=0;$i<$max;$i++) {
                   8449: 	$r->print("\n".
                   8450: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8451: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8452:     }
1.503     raeburn  8453:     my $nobub_checked = ' ';
                   8454:     if ($error eq 'missingbubble') {
                   8455:         $nobub_checked = ' checked = "checked" ';
                   8456:     }
                   8457:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8458: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8459:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8460:               $line.'" value="'.$questionnum.'" /></td>');
                   8461:     $r->print(&Apache::loncommon::end_data_table_row().
                   8462:               &Apache::loncommon::end_data_table());
1.157     albertel 8463: }
                   8464: 
1.423     albertel 8465: =pod
                   8466: 
                   8467: =item num_matches
                   8468: 
1.424     albertel 8469:    Counts the number of characters that are the same between the two arguments.
                   8470: 
                   8471:  Arguments:
                   8472:    $orig - CODE from the scanline
                   8473:    $code - CODE to match against
                   8474: 
                   8475:  Returns:
                   8476:    $count - integer count of the number of same characters between the
                   8477:             two arguments
                   8478: 
1.423     albertel 8479: =cut
                   8480: 
1.194     albertel 8481: sub num_matches {
                   8482:     my ($orig,$code) = @_;
                   8483:     my @code=split(//,$code);
                   8484:     my @orig=split(//,$orig);
                   8485:     my $same=0;
                   8486:     for (my $i=0;$i<scalar(@code);$i++) {
                   8487: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8488:     }
                   8489:     return $same;
                   8490: }
                   8491: 
1.423     albertel 8492: =pod
                   8493: 
                   8494: =item scantron_get_closely_matching_CODEs
                   8495: 
1.424     albertel 8496:    Cycles through all CODEs and finds the set that has the greatest
                   8497:    number of same characters as the provided CODE
                   8498: 
                   8499:  Arguments:
                   8500:    $allcodes - hash ref returned by &get_codes()
                   8501:    $CODE     - CODE from the current scanline
                   8502: 
                   8503:  Returns:
                   8504:    2 element list
                   8505:     - first elements is number of how closely matching the best fit is 
                   8506:       (5 means best set has 5 matching characters)
                   8507:     - second element is an arrary ref containing the set of valid CODEs
                   8508:       that best fit the passed in CODE
                   8509: 
1.423     albertel 8510: =cut
                   8511: 
1.194     albertel 8512: sub scantron_get_closely_matching_CODEs {
                   8513:     my ($allcodes,$CODE)=@_;
                   8514:     my @CODEs;
                   8515:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8516: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8517:     }
                   8518: 
                   8519:     return ($#CODEs,$CODEs[-1]);
                   8520: }
                   8521: 
1.423     albertel 8522: =pod
                   8523: 
                   8524: =item get_codes
                   8525: 
1.424     albertel 8526:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8527:    set of remembered CODEs.
                   8528: 
                   8529:  Arguments:
                   8530:   $old_name - name of the set of remembered CODEs
                   8531:   $cdom     - domain of the course
                   8532:   $cnum     - internal course name
                   8533: 
                   8534:  Returns:
                   8535:   %allcodes - keys are the valid CODEs, values are all 1
                   8536: 
1.423     albertel 8537: =cut
                   8538: 
1.194     albertel 8539: sub get_codes {
1.280     foxr     8540:     my ($old_name, $cdom, $cnum) = @_;
                   8541:     if (!$old_name) {
                   8542: 	$old_name=$env{'form.scantron_CODElist'};
                   8543:     }
                   8544:     if (!$cdom) {
                   8545: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8546:     }
                   8547:     if (!$cnum) {
                   8548: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8549:     }
1.278     albertel 8550:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8551: 				    $cdom,$cnum);
                   8552:     my %allcodes;
                   8553:     if ($result{"type\0$old_name"} eq 'number') {
                   8554: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8555:     } else {
                   8556: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8557:     }
1.194     albertel 8558:     return %allcodes;
                   8559: }
                   8560: 
1.423     albertel 8561: =pod
                   8562: 
                   8563: =item scantron_validate_CODE
                   8564: 
1.424     albertel 8565:    Validates all scanlines in the selected file to not have any
                   8566:    invalid or underspecified CODEs and that none of the codes are
                   8567:    duplicated if this was requested.
                   8568: 
1.423     albertel 8569: =cut
                   8570: 
1.157     albertel 8571: sub scantron_validate_CODE {
                   8572:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8573:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8574:     if ($scantron_config{'CODElocation'} &&
                   8575: 	$scantron_config{'CODEstart'} &&
                   8576: 	$scantron_config{'CODElength'}) {
1.257     albertel 8577: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8578: 	    &FIXME_blow_up()
                   8579: 	}
                   8580:     } else {
                   8581: 	return (0,$currentphase+1);
                   8582:     }
                   8583:     
                   8584:     my %usedCODEs;
                   8585: 
1.194     albertel 8586:     my %allcodes=&get_codes();
1.186     albertel 8587: 
1.582     raeburn  8588:     my $nav_error;
1.596.2.12.2.  (raeburn 8589:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8590:     if ($nav_error) {
                   8591:         $r->print(&navmap_errormsg());
                   8592:         return(1,$currentphase);
                   8593:     }
1.447     foxr     8594: 
1.186     albertel 8595:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8596:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8597: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8598: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8599: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8600: 						 $scan_data);
                   8601: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8602: 	my $error=0;
1.224     albertel 8603: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8604: 	    &scantron_get_correction($r,$i,$scan_record,
                   8605: 				     \%scantron_config,
                   8606: 				     $line,'incorrectCODE',\%allcodes);
                   8607: 	    return(1,$currentphase);
                   8608: 	}
1.221     albertel 8609: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8610: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8611: 	    &scantron_get_correction($r,$i,$scan_record,
                   8612: 				     \%scantron_config,
1.194     albertel 8613: 				     $line,'incorrectCODE',\%allcodes);
                   8614: 	    return(1,$currentphase);
1.186     albertel 8615: 	}
1.214     albertel 8616: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8617: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8618: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8619: 	    &scantron_get_correction($r,$i,$scan_record,
                   8620: 				     \%scantron_config,
1.194     albertel 8621: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8622: 	    return(1,$currentphase);
1.186     albertel 8623: 	}
1.524     raeburn  8624: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8625:     }
1.157     albertel 8626:     return (0,$currentphase+1);
                   8627: }
                   8628: 
1.423     albertel 8629: =pod
                   8630: 
                   8631: =item scantron_validate_doublebubble
                   8632: 
1.424     albertel 8633:    Validates all scanlines in the selected file to not have any
                   8634:    bubble lines with multiple bubbles marked.
                   8635: 
1.423     albertel 8636: =cut
                   8637: 
1.157     albertel 8638: sub scantron_validate_doublebubble {
                   8639:     my ($r,$currentphase) = @_;
                   8640:     #get student info
                   8641:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8642:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8643:3):     my (undef,undef,$sequence)=
                   8644:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8645: 
                   8646:     #get scantron line setup
1.596.2.12.2.  9(raebur 8647:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8648:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8649:3): 
                   8650:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8651:3):     unless (ref($navmap)) {
                   8652:3):         $r->print(&navmap_errormsg());
                   8653:3):         return(1,$currentphase);
                   8654:3):     }
                   8655:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8656:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8657:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8658:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8659:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8660:3): 
1.583     raeburn  8661:     my $nav_error;
1.596.2.12.2.  6(raebur 8662:3):     if (ref($map)) {
                   8663:3):         $randomorder = $map->randomorder();
                   8664:3):         $randompick = $map->randompick();
          0(raebur 8665:2):         unless ($randomorder || $randompick) {
                   8666:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8667:2):                 if ($res->randomorder()) {
                   8668:2):                     $randomorder = 1;
                   8669:2):                 }
                   8670:2):                 if ($res->randompick()) {
                   8671:2):                     $randompick = 1;
                   8672:2):                 }
                   8673:2):                 last if ($randomorder || $randompick);
                   8674:2):             }
                   8675:2):         }
          6(raebur 8676:3):         if ($randomorder || $randompick) {
                   8677:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8678:3):             if ($nav_error) {
                   8679:3):                 $r->print(&navmap_errormsg());
                   8680:3):                 return(1,$currentphase);
                   8681:3):             }
                   8682:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8683:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8684:3):         }
                   8685:3):     } else {
                   8686:3):         $r->print(&navmap_errormsg());
                   8687:3):         return(1,$currentphase);
                   8688:3):     }
                   8689:3): 
          (raeburn 8690:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8691:     if ($nav_error) {
                   8692:         $r->print(&navmap_errormsg());
                   8693:         return(1,$currentphase);
                   8694:     }
1.447     foxr     8695: 
1.157     albertel 8696:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8697: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8698: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8699: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8700:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8701:3):                                                  $randompick,$sequence,\@master_seq,
                   8702:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8703:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8704: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8705: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8706: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8707:3): 				 $$scan_record{'scantron.doubleerror'},
                   8708:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8709:     	return (1,$currentphase);
                   8710:     }
                   8711:     return (0,$currentphase+1);
                   8712: }
                   8713: 
1.423     albertel 8714: 
1.503     raeburn  8715: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8716:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8717:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8718: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8719: 	&restore_bubble_lines();
1.257     albertel 8720: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8721:     }
1.330     albertel 8722: 
1.447     foxr     8723:     my (undef, undef, $sequence) =
1.257     albertel 8724: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8725: 
1.447     foxr     8726:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8727:     unless (ref($navmap)) {
                   8728:         if (ref($nav_error)) {
                   8729:             $$nav_error = 1;
                   8730:         }
1.591     raeburn  8731:         return;
1.582     raeburn  8732:     }
1.191     albertel 8733:     my $map=$navmap->getResourceByUrl($sequence);
                   8734:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8735:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8736: 
                   8737:     &Apache::lonxml::clear_problem_counter();
                   8738: 
1.557     raeburn  8739:     my $uname       = $env{'user.name'};
                   8740:     my $udom        = $env{'user.domain'};
1.435     foxr     8741:     my $cid         = $env{'request.course.id'};
                   8742:     my $total_lines = 0;
                   8743:     %bubble_lines_per_response = ();
1.447     foxr     8744:     %first_bubble_line         = ();
1.503     raeburn  8745:     %subdivided_bubble_lines   = ();
                   8746:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8747:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8748: 
1.447     foxr     8749:     my $response_number = 0;
                   8750:     my $bubble_line     = 0;
1.191     albertel 8751:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8752:3):         my $resid = $resource->id();
          (raeburn 8753:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8754:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8755:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8756: 	    foreach my $part_id (@{$parts}) {
                   8757:                 my $lines;
                   8758: 
                   8759: 	        # TODO - make this a persistent hash not an array.
                   8760: 
                   8761:                 # optionresponse, matchresponse and rankresponse type items 
                   8762:                 # render as separate sub-questions in exam mode.
                   8763:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8764:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8765:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8766:                     my ($numbub,$numshown);
                   8767:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8768:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8769:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8770:                         }
                   8771:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8772:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8773:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8774:                         }
                   8775:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8776:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8777:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8778:                         }
                   8779:                     }
                   8780:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8781:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8782:                     }
1.596.2.12.2.  (raeburn 8783:):                     my $bubbles_per_row =
                   8784:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8785:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8786:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8787:                         $inner_bubble_lines++;
                   8788:                     }
                   8789:                     for (my $i=0; $i<$numshown; $i++) {
                   8790:                         $subdivided_bubble_lines{$response_number} .= 
                   8791:                             $inner_bubble_lines.',';
                   8792:                     }
                   8793:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8794:                     $lines = $numshown * $inner_bubble_lines;
                   8795:                 } else {
                   8796:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8797:):                 }
1.542     raeburn  8798: 
                   8799:                 $first_bubble_line{$response_number} = $bubble_line;
                   8800: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8801:                 $responsetype_per_response{$response_number} = 
                   8802:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8803:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8804: 	        $response_number++;
                   8805: 
                   8806: 	        $bubble_line +=  $lines;
                   8807: 	        $total_lines +=  $lines;
                   8808: 	    }
                   8809:         }
                   8810:     }
1.552     raeburn  8811:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8812: 
                   8813:     &save_bubble_lines();
                   8814:     $env{'form.scantron_maxbubble'} =
                   8815: 	$total_lines;
                   8816:     return $env{'form.scantron_maxbubble'};
                   8817: }
1.523     raeburn  8818: 
1.596.2.12.2.  (raeburn 8819:): sub bubblesheet_bubbles_per_row {
                   8820:):     my ($scantron_config) = @_;
                   8821:):     my $bubbles_per_row;
                   8822:):     if (ref($scantron_config) eq 'HASH') {
                   8823:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8824:):     }
                   8825:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8826:):         $bubbles_per_row = 10;
                   8827:):     }
                   8828:):     return $bubbles_per_row;
                   8829:): }
                   8830:): 
1.157     albertel 8831: sub scantron_validate_missingbubbles {
                   8832:     my ($r,$currentphase) = @_;
                   8833:     #get student info
                   8834:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8835:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8836:3):     my (undef,undef,$sequence)=
                   8837:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8838: 
                   8839:     #get scantron line setup
1.596.2.12.2.  9(raebur 8840:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8841:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8842:3): 
                   8843:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8844:3):     unless (ref($navmap)) {
                   8845:3):         $r->print(&navmap_errormsg());
                   8846:3):         return(1,$currentphase);
                   8847:3):     }
                   8848:3): 
                   8849:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8850:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8851:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8852:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8853:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8854:3): 
1.582     raeburn  8855:     my $nav_error;
1.596.2.12.2.  6(raebur 8856:3):     if (ref($map)) {
                   8857:3):         $randomorder = $map->randomorder();
                   8858:3):         $randompick = $map->randompick();
          0(raebur 8859:2):         unless ($randomorder || $randompick) {
                   8860:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8861:2):                 if ($res->randomorder()) {
                   8862:2):                     $randomorder = 1;
                   8863:2):                 }
                   8864:2):                 if ($res->randompick()) {
                   8865:2):                     $randompick = 1;
                   8866:2):                 }
                   8867:2):                 last if ($randomorder || $randompick);
                   8868:2):             }
                   8869:2):         }
          7(raebur 8870:3):         if ($randomorder || $randompick) {
                   8871:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8872:3):             if ($nav_error) {
                   8873:3):                 $r->print(&navmap_errormsg());
                   8874:3):                 return(1,$currentphase);
                   8875:3):             }
                   8876:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8877:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8878:3):         }
          6(raebur 8879:3):     } else {
                   8880:3):         $r->print(&navmap_errormsg());
          7(raebur 8881:3):         return(1,$currentphase);
          6(raebur 8882:3):     }
                   8883:3): 
                   8884:3): 
          (raeburn 8885:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8886:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8887:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8888:         return(1,$currentphase);
                   8889:     }
1.596.2.12.2.  6(raebur 8890:3): 
1.157     albertel 8891:     if (!$max_bubble) { $max_bubble=2**31; }
                   8892:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8893: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8894: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8895:3):         my $scan_record =
                   8896:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8897:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8898:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8899:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8900: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8901: 	my @to_correct;
1.470     foxr     8902: 	
                   8903: 	# Probably here's where the error is...
                   8904: 
1.157     albertel 8905: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8906:             my $lastbubble;
                   8907:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8908:3):                 my $question = $1;
                   8909:3):                 my $subquestion = $2;
                   8910:3):                 my ($first,$responsenum);
                   8911:3):                 if ($randomorder || $randompick) {
                   8912:3):                     $responsenum = $respnumlookup{$question-1};
                   8913:3):                     $first = $startline{$question-1};
                   8914:3):                 } else {
                   8915:3):                     $responsenum = $question-1;
                   8916:3):                     $first = $first_bubble_line{$responsenum};
                   8917:3):                 }
                   8918:3):                 if (!defined($first)) { next; }
          7(raebur 8919:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8920:3):                 my $subcount = 1;
                   8921:3):                 while ($subcount<$subquestion) {
                   8922:3):                     $first += $subans[$subcount-1];
                   8923:3):                     $subcount ++;
                   8924:3):                 }
                   8925:3):                 my $count = $subans[$subquestion-1];
                   8926:3):                 $lastbubble = $first + $count;
1.505     raeburn  8927:             } else {
1.596.2.12.2.  6(raebur 8928:3):                 my ($first,$responsenum);
                   8929:3):                 if ($randomorder || $randompick) {
                   8930:3):                     $responsenum = $respnumlookup{$missing-1};
                   8931:3):                     $first = $startline{$missing-1};
                   8932:3):                 } else {
                   8933:3):                     $responsenum = $missing-1;
                   8934:3):                     $first = $first_bubble_line{$responsenum};
                   8935:3):                 }
                   8936:3):                 if (!defined($first)) { next; }
                   8937:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8938:             }
                   8939:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8940: 	    push(@to_correct,$missing);
                   8941: 	}
                   8942: 	if (@to_correct) {
                   8943: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8944:3): 				     $line,'missingbubble',\@to_correct,
                   8945:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8946:3):                                      \%startline);
1.157     albertel 8947: 	    return (1,$currentphase);
                   8948: 	}
                   8949: 
                   8950:     }
                   8951:     return (0,$currentphase+1);
                   8952: }
                   8953: 
1.596.2.12.2.  (raeburn 8954:): sub hand_bubble_option {
                   8955:):     my (undef, undef, $sequence) =
                   8956:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8957:):     return if ($sequence eq '');
                   8958:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8959:):     unless (ref($navmap)) {
                   8960:):         return;
                   8961:):     }
                   8962:):     my $needs_hand_bubbles;
                   8963:):     my $map=$navmap->getResourceByUrl($sequence);
                   8964:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8965:):     foreach my $res (@resources) {
                   8966:):         if (ref($res)) {
                   8967:):             if ($res->is_problem()) {
                   8968:):                 my $partlist = $res->parts();
                   8969:):                 foreach my $part (@{ $partlist }) {
                   8970:):                     my @types = $res->responseType($part);
                   8971:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8972:):                         $needs_hand_bubbles = 1;
                   8973:):                         last;
                   8974:):                     }
                   8975:):                 }
                   8976:):             }
                   8977:):         }
                   8978:):     }
                   8979:):     if ($needs_hand_bubbles) {
          9(raebur 8980:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8981:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8982:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8983:):                &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 />').
                   8984:):                '<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;'.
          8(raebur 8985:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8986:):     }
                   8987:):     return;
                   8988:): }
1.423     albertel 8989: 
1.82      albertel 8990: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8991:0):     my ($r,$symb) = @_;
1.513     foxr     8992: 
1.257     albertel 8993:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8994:     if (!$symb) {
                   8995: 	return '';
                   8996:     }
1.324     albertel 8997:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8998: 
1.596.2.12.2.  9(raebur 8999:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 9000:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 9001:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9002:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9003:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9004:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9005:     unless (ref($navmap)) {
                   9006:         $r->print(&navmap_errormsg());
                   9007:         return '';
1.596.2.12.2.  6(raebur 9008:3):     }
1.83      albertel 9009:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9010:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
          0(raebur 9011:2):         %grader_randomlists_by_symb,%symb_for_examcode);
          1(raebur 9012:2):     if (ref($map)) {
                   9013:2):         $randomorder = $map->randomorder();
          6(raebur 9014:3):         $randompick = $map->randompick();
          0(raebur 9015:2):         unless ($randomorder || $randompick) {
                   9016:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9017:2):                 if ($res->randomorder()) {
                   9018:2):                     $randomorder = 1;
                   9019:2):                 }
                   9020:2):                 if ($res->randompick()) {
                   9021:2):                     $randompick = 1;
                   9022:2):                 }
                   9023:2):                 last if ($randomorder || $randompick);
                   9024:2):             }
                   9025:2):         }
          6(raebur 9026:3):     } else {
                   9027:3):         $r->print(&navmap_errormsg());
                   9028:3):         return '';
          1(raebur 9029:2):     }
          6(raebur 9030:3):     my $nav_error;
1.83      albertel 9031:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9032:3):     if ($randomorder || $randompick) {
          0(raebur 9033:2):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
          6(raebur 9034:3):         if ($nav_error) {
                   9035:3):             $r->print(&navmap_errormsg());
                   9036:3):             return '';
1.586     raeburn  9037:         }
                   9038:     }
1.596.2.12.2.  6(raebur 9039:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9040:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9041: 
1.554     raeburn  9042:     my ($uname,$udom);
1.82      albertel 9043:     my $result= <<SCANTRONFORM;
1.81      albertel 9044: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9045:   <input type="hidden" name="command" value="scantron_configphase" />
                   9046:   $default_form_data
                   9047: SCANTRONFORM
1.82      albertel 9048:     $r->print($result);
                   9049: 
                   9050:     my @delayqueue;
1.542     raeburn  9051:     my (%completedstudents,%scandata);
1.140     albertel 9052:     
1.520     www      9053:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9054:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 9055:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 9056:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9057:     $r->print('<br />');
1.140     albertel 9058:     my $start=&Time::HiRes::time();
1.158     albertel 9059:     my $i=-1;
1.542     raeburn  9060:     my $started;
1.447     foxr     9061: 
1.596.2.12.2.  (raeburn 9062:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9063:     if ($nav_error) {
                   9064:         $r->print(&navmap_errormsg());
                   9065:         return '';
                   9066:     }
                   9067: 
1.513     foxr     9068:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9069:     # the user and return.
                   9070: 
                   9071:     if ($ssi_error) {
                   9072: 	$r->print("</form>");
                   9073: 	&ssi_print_error($r);
1.520     www      9074:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9075: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9076:     }
1.447     foxr     9077: 
1.596.2.12.2.  9(raebur 9078:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9079:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 9080:3):     my %orderedforcode;
1.542     raeburn  9081: 
1.157     albertel 9082:     while ($i<$scanlines->{'count'}) {
                   9083:  	($uname,$udom)=('','');
                   9084:  	$i++;
1.200     albertel 9085:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9086:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9087: 	if ($started) {
1.596.2.12.2.  1(raebur 9088:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9089: 	}
                   9090: 	$started=1;
1.596.2.12.2.  6(raebur 9091:3):         my %respnumlookup = ();
                   9092:3):         my %startline = ();
                   9093:3):         my $total;
1.157     albertel 9094:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 9095:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   9096:3):                                                  $randompick,$sequence,\@master_seq,
                   9097:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9098:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9099:3):                                                  \$total);
1.157     albertel 9100:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9101:  					      \%idmap,$i)) {
                   9102:   	    &scantron_add_delay(\@delayqueue,$line,
                   9103:  				'Unable to find a student that matches',1);
                   9104:  	    next;
                   9105:   	}
                   9106:  	if (exists $completedstudents{$uname}) {
                   9107:  	    &scantron_add_delay(\@delayqueue,$line,
                   9108:  				'Student '.$uname.' has multiple sheets',2);
                   9109:  	    next;
                   9110:  	}
1.596.2.12.2.  1(raebur 9111:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9112:2):         my $user = $uname.':'.$usec;
1.157     albertel 9113:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9114: 
1.596.2.12.2.  1(raebur 9115:2):         my $scancode;
                   9116:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9117:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9118:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9119:2):         } else {
                   9120:2):             $scancode = '';
                   9121:2):         }
                   9122:2): 
                   9123:2):         my @mapresources = @resources;
          6(raebur 9124:3):         if ($randomorder || $randompick) {
          1(raebur 9125:2):             @mapresources =
          6(raebur 9126:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9127:3):                              \%orderedforcode);
          1(raebur 9128:2):         }
1.586     raeburn  9129:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 9130:2):         foreach my $resource (@mapresources) {
1.586     raeburn  9131:             my $ressymb;
                   9132:             if (ref($resource)) {
                   9133:                 $ressymb = $resource->symb();
                   9134:             } else {
                   9135:                 $res_error = 1;
                   9136:                 last;
                   9137:             }
1.557     raeburn  9138:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9139:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9140:7):                 my $currcode;
                   9141:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9142:7):                     $currcode = $scancode;
                   9143:7):                 }
1.557     raeburn  9144:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 9145:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 9146:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   9147:7):                                               $currcode);
1.557     raeburn  9148:                 $partids_by_symb{$ressymb} = $parts;
                   9149:             } else {
                   9150:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9151:             }
1.554     raeburn  9152:         }
                   9153: 
1.586     raeburn  9154:         if ($res_error) {
                   9155:             &scantron_add_delay(\@delayqueue,$line,
                   9156:                                 'An error occurred while grading student '.$uname,2);
                   9157:             next;
                   9158:         }
                   9159: 
1.330     albertel 9160: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9161:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9162: 
                   9163: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9164: 	    &scantron_putfile($scanlines,$scan_data);
                   9165: 	}
1.161     albertel 9166: 	
1.542     raeburn  9167:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9168:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 9169:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   9170:3):                                    \%respnumlookup,\%startline) 
                   9171:3):             eq 'ssi_error') {
1.542     raeburn  9172:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9173:             $r->print("</form>");
                   9174:             &ssi_print_error($r);
                   9175:             &Apache::lonnet::remove_lock($lock);
                   9176:             return '';      # Why return ''?  Beats me.
                   9177:         }
1.513     foxr     9178: 
1.596.2.12.2.  6(raebur 9179:3):         if (($scancode) && ($randomorder || $randompick)) {
          0(raebur 9180:2):             foreach my $key (keys(%symb_for_examcode)) {
                   9181:2):                 my $symb_in_map = $symb_for_examcode{$key};
                   9182:2):                 if ($symb_in_map ne '') {
                   9183:2):                     my $parmresult =
                   9184:2):                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9185:2):                                                                '0_examcode',2,$scancode,
                   9186:2):                                                                'string_examcode',$uname,
                   9187:2):                                                                $udom);
                   9188:2):                 }
                   9189:2):             }
          6(raebur 9190:3):         }
1.140     albertel 9191: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9192:         if ($env{'form.verifyrecord'}) {
                   9193:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 9194:3):             if ($randompick) {
                   9195:3):                 if ($total) {
                   9196:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   9197:3):                 }
                   9198:3):             }
                   9199:3): 
1.542     raeburn  9200:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9201:             chomp($studentdata);
                   9202:             $studentdata =~ s/\r$//;
                   9203:             my $studentrecord = '';
                   9204:             my $counter = -1;
1.596.2.12.2.  1(raebur 9205:2):             foreach my $resource (@mapresources) {
1.554     raeburn  9206:                 my $ressymb = $resource->symb();
1.542     raeburn  9207:                 ($counter,my $recording) =
                   9208:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9209:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9210:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9211:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9212:                 $studentrecord .= $recording;
                   9213:             }
                   9214:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9215:                 &Apache::lonxml::clear_problem_counter();
                   9216:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9217:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 9218:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   9219:3):                                            \%respnumlookup,\%startline)
                   9220:3):                     eq 'ssi_error') {
1.554     raeburn  9221:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9222:                     $r->print("</form>");
                   9223:                     &ssi_print_error($r);
                   9224:                     &Apache::lonnet::remove_lock($lock);
                   9225:                     delete($completedstudents{$uname});
                   9226:                     return '';
                   9227:                 }
1.542     raeburn  9228:                 $counter = -1;
                   9229:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 9230:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  9231:                     my $ressymb = $resource->symb();
1.542     raeburn  9232:                     ($counter,my $recording) =
                   9233:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9234:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9235:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   9236:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   9237:3):                                                  \%startline);
1.542     raeburn  9238:                     $studentrecord .= $recording;
                   9239:                 }
                   9240:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  9241:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9242:                     if ($scancode eq '') {
1.596.2.6  raeburn  9243:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9244:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9245:                     } else {
1.596.2.6  raeburn  9246:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9247:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9248:                     }
                   9249:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9250:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9251:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9252:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9253:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9254:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 9255:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9256:                               &Apache::loncommon::end_data_table_row().
                   9257:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9258:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 9259:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9260:                               &Apache::loncommon::end_data_table_row().
                   9261:                               &Apache::loncommon::end_data_table().'</p>');
                   9262:                 } else {
                   9263:                     $r->print('<br /><span class="LC_warning">'.
                   9264:                              &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 />'.
                   9265:                              &mt("As a consequence, this user's submission history records two tries.").
                   9266:                                  '</span><br />');
                   9267:                 }
                   9268:             }
                   9269:         }
1.543     raeburn  9270:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9271:     } continue {
1.330     albertel 9272: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9273: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9274:     }
1.140     albertel 9275:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9276:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9277: #    my $lasttime = &Time::HiRes::time()-$start;
                   9278: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9279: 
1.200     albertel 9280:     $r->print("</form>");
1.157     albertel 9281:     return '';
1.75      albertel 9282: }
1.157     albertel 9283: 
1.557     raeburn  9284: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 9285:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9286:):         $bubbles_per_row) = @_;
1.557     raeburn  9287:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9288:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9289:         foreach my $resource (@{$resources}) {
                   9290:             my $ressymb = $resource->symb();
                   9291:             my ($analysis,$parts) =
                   9292:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 9293:):                                           $env{'user.name'},$env{'user.domain'},
                   9294:):                                           1,$bubbles_per_row);
1.557     raeburn  9295:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9296:             if (ref($analysis) eq 'HASH') {
                   9297:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9298:                     $grader_randomlists_by_symb->{$ressymb} =
                   9299:                         $analysis->{'parts_withrandomlist'};
                   9300:                 }
                   9301:             }
                   9302:         }
                   9303:     }
                   9304:     return;
                   9305: }
                   9306: 
1.596.2.12.2.  1(raebur 9307:2): =pod
                   9308:2): 
                   9309:2): =item users_order
                   9310:2): 
                   9311:2):   Returns array of resources in current map, ordered based on either CODE,
                   9312:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9313:2):   "NAMEd" exam.
                   9314:2): 
          6(raebur 9315:3):   Should be used when randomorder and/or randompick applied when the 
                   9316:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9317:3):   for the version of the exam the student received.
          1(raebur 9318:2): 
                   9319:2): =cut
                   9320:2): 
                   9321:2): sub users_order  {
          6(raebur 9322:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9323:2):     my @mapresources;
          6(raebur 9324:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9325:2):         return @mapresources;
                   9326:2):     }
          6(raebur 9327:3):     if ($scancode) {
                   9328:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9329:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9330:3):         } else {
                   9331:3):             $env{'form.CODE'} = $scancode;
                   9332:3):             my $actual_seq =
                   9333:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9334:3):                                                                $master_seq,
                   9335:3):                                                                $user,$scancode,1);
                   9336:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9337:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9338:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9339:3):                     if (@mapresources > 0) {
                   9340:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9341:3):                     }
                   9342:3):                 }
                   9343:3):             }
                   9344:3):             delete($env{'form.CODE'});
          1(raebur 9345:2):         }
                   9346:2):     } else {
                   9347:2):         my $actual_seq =
                   9348:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9349:2):                                                            $master_seq,
          5(raebur 9350:3):                                                            $user,undef,1);
          1(raebur 9351:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9352:2):             @mapresources =
                   9353:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9354:2):         }
          6(raebur 9355:3):     }
                   9356:3):     return @mapresources;
          1(raebur 9357:2): }
                   9358:2): 
1.542     raeburn  9359: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9360:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9361:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9362:3):     my $uselookup = 0;
                   9363:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9364:3):         (ref($startline) eq 'HASH')) {
                   9365:3):         $uselookup = 1;
                   9366:3):     }
                   9367:3): 
1.554     raeburn  9368:     if (ref($resources) eq 'ARRAY') {
                   9369:         my $count = 0;
                   9370:         foreach my $resource (@{$resources}) {
                   9371:             my $ressymb = $resource->symb();
                   9372:             my %form = ('submitted'      => 'scantron',
                   9373:                         'grade_target'   => 'grade',
                   9374:                         'grade_username' => $uname,
                   9375:                         'grade_domain'   => $udom,
                   9376:                         'grade_courseid' => $env{'request.course.id'},
                   9377:                         'grade_symb'     => $ressymb,
                   9378:                         'CODE'           => $scancode
                   9379:                        );
1.596.2.12.2.  (raeburn 9380:):             if ($bubbles_per_row ne '') {
                   9381:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9382:):             }
                   9383:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9384:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9385:):             }
1.554     raeburn  9386:             if (ref($parts) eq 'HASH') {
                   9387:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9388:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9389:3):                         if ($uselookup) {
                   9390:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9391:3):                         } else {
                   9392:3):                             $form{'scantron_questnum_start.'.$part} =
                   9393:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9394:3):                         }
1.554     raeburn  9395:                         $count++;
                   9396:                     }
                   9397:                 }
                   9398:             }
                   9399:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9400:             return 'ssi_error' if ($ssi_error);
                   9401:             last if (&Apache::loncommon::connection_aborted($r));
                   9402:         }
1.542     raeburn  9403:     }
                   9404:     return;
                   9405: }
                   9406: 
1.157     albertel 9407: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9408:0):     my ($r,$symb) = @_;
1.565     raeburn  9409:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9410:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9411:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9412:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9413:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9414: 							  'domainid',
1.565     raeburn  9415: 							  'coursename',$dom);
                   9416:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9417:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9418:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9419:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9420:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9421:     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.");
1.596.2.12.2.  6(raebur 9422:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9423:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9424:     function checkUpload(formname) {
                   9425: 	if (formname.upfile.value == "") {
1.579     raeburn  9426: 	    alert("'.$nofile_alert.'");
1.157     albertel 9427: 	    return false;
                   9428: 	}
1.565     raeburn  9429:         if (formname.courseid.value == "") {
1.579     raeburn  9430:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9431:             return false;
                   9432:         }
1.157     albertel 9433: 	formname.submit();
                   9434:     }
1.565     raeburn  9435: 
                   9436:     function ToSyllabus() {
                   9437:         var cdom = '."'$dom'".';
                   9438:         var cnum = document.rules.courseid.value;
                   9439:         if (cdom == "" || cdom == null) {
                   9440:             return;
                   9441:         }
                   9442:         if (cnum == "" || cnum == null) {
                   9443:            return;
                   9444:         }
                   9445:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9446:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9447:         return;
                   9448:     }
                   9449: 
1.596.2.12.2.  9(raebur 9450:9):     '.$formatjs.'
                   9451:9): '));
                   9452:9):     $r->print('
1.596.2.4  raeburn  9453: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9454: 
1.492     albertel 9455: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9456: '.$default_form_data.
                   9457:   &Apache::lonhtmlcommon::start_pick_box().
                   9458:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9459:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9460:   &Apache::lonhtmlcommon::row_closure().
                   9461:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9462:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9463:   &Apache::lonhtmlcommon::row_closure().
                   9464:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9465:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9466:9):   &Apache::lonhtmlcommon::row_closure());
                   9467:9):     if ($formatoptions) {
                   9468:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9469:9):                   &Apache::lonhtmlcommon::row_closure());
                   9470:9):     }
                   9471:9):     $r->print(
1.565     raeburn  9472:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9473:   '<input type="file" name="upfile" size="50" />'.
                   9474:   &Apache::lonhtmlcommon::row_closure(1).
                   9475:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9476: 
1.492     albertel 9477: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9478: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9479: </form>
1.492     albertel 9480: ');
1.157     albertel 9481:     return '';
                   9482: }
                   9483: 
1.596.2.12.2.  9(raebur 9484:9): sub scantron_upload_dataformat {
                   9485:9):     my ($dom) = @_;
                   9486:9):     my ($formatoptions,$formattitle,$formatjs);
                   9487:9):     $formatjs = <<'END';
                   9488:9): function toggleScantab(form) {
                   9489:9):    return;
                   9490:9): }
                   9491:9): END
                   9492:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9493:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9494:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9495:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9496:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9497:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9498:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9499:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9500:9):                             my ($onclick,$formatextra,$singleline);
                   9501:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9502:9):                             my $count = 0;
                   9503:9):                             foreach my $line (@lines) {
          0.2.1(ra 9504:an-23):                                 next if (($line =~ /^\#/) || ($line eq ''));
          9(raebur 9505:9):                                 $singleline = $line;
                   9506:9):                                 $count ++;
                   9507:9):                             }
                   9508:9):                             if ($count > 1) {
                   9509:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9510:9):                                                '<span class="LC_nobreak">'.
          4(raebur 9511:0):                                                &mt('Bubblesheet type').':&nbsp;'.
          9(raebur 9512:9):                                                &scantron_scantab().'</span></div>';
                   9513:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9514:9):                                 $formatjs = <<"END";
                   9515:9): function toggleScantab(form) {
                   9516:9):     var divid = 'bubbletype';
                   9517:9):     if (document.getElementById(divid)) {
                   9518:9):         var radioname = 'fileformat';
                   9519:9):         var num = form.elements[radioname].length;
                   9520:9):         if (num) {
                   9521:9):             for (var i=0; i<num; i++) {
                   9522:9):                 if (form.elements[radioname][i].checked) {
                   9523:9):                     var chosen = form.elements[radioname][i].value;
                   9524:9):                     if (chosen == 'dat') {
                   9525:9):                         document.getElementById(divid).style.display = 'none';
                   9526:9):                     } else if (chosen == 'csv') {
                   9527:9):                         document.getElementById(divid).style.display = 'block';
                   9528:9):                     }
                   9529:9):                 }
                   9530:9):             }
                   9531:9):         }
                   9532:9):     }
                   9533:9):     return;
                   9534:9): }
                   9535:9): 
                   9536:9): END
                   9537:9):                             } elsif ($count == 1) {
                   9538:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9539:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9540:9):                             }
                   9541:9):                             $formattitle = &mt('File format');
                   9542:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9543:9):                                              &mt('Plain Text (no delimiters)').
                   9544:9):                                              '</label>'.('&nbsp;'x2).
                   9545:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9546:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9547:9):                         }
                   9548:9):                     }
                   9549:9):                 }
                   9550:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9551:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9552:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9553:9):                         $formattitle = &mt('Bubblesheet type');
                   9554:9):                         $formatoptions = &scantron_scantab();
                   9555:9):                     }
                   9556:9):                 }
                   9557:9):             }
                   9558:9):         }
                   9559:9):     }
                   9560:9):     return ($formatoptions,$formattitle,$formatjs);
                   9561:9): }
1.423     albertel 9562: 
1.157     albertel 9563: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9564:0):     my ($r,$symb) = @_;
1.182     albertel 9565:     my $doanotherupload=
                   9566: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9567: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9568: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9569: 	'</form>'."\n";
1.257     albertel 9570:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9571: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9572: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9573: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9574:0):         unless ($symb) {
1.182     albertel 9575: 	    $r->print($doanotherupload);
                   9576: 	}
1.162     albertel 9577: 	return '';
                   9578:     }
1.257     albertel 9579:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9580:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9581:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9582:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9583:3):         $r->print(
                   9584:3):             &Apache::lonhtmlcommon::confirm_success(
                   9585:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9586:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9587:     } else {
1.596.2.12.2.  9(raebur 9588:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9589:9):         my $parser;
                   9590:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9591:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9592:9):                 my $is_csv;
                   9593:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9594:9):                 if (@possibles > 1) {
                   9595:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9596:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9597:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9598:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9599:9):                                     $is_csv = 1;
                   9600:9):                                 }
                   9601:9):                             }
                   9602:9):                         }
                   9603:9):                     }
                   9604:9):                 } elsif (@possibles == 1) {
                   9605:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9606:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9607:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9608:9):                                 $is_csv = 1;
                   9609:9):                             }
                   9610:9):                         }
                   9611:9):                     }
                   9612:9):                 }
                   9613:9):                 if ($is_csv) {
                   9614:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9615:9):                 }
                   9616:9):             }
                   9617:9):         }
                   9618:9):         my $result =
                   9619:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9620:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9621: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9622:3):             $r->print(
                   9623:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9624:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9625:3):                         (length($env{'form.upfile'})-1),
                   9626:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9627:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9628:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9629:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9630: 	} else {
1.596.2.12.2.  5(raebur 9631:3):             $r->print(
                   9632:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9633:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9634:3):                           $result,
1.568     raeburn  9635: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9636: 	}
                   9637:     }
1.174     albertel 9638:     if ($symb) {
1.596.2.12.2.  1(raebur 9639:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9640:     } else {
1.182     albertel 9641: 	$r->print($doanotherupload);
1.174     albertel 9642:     }
1.157     albertel 9643:     return '';
                   9644: }
                   9645: 
1.567     raeburn  9646: sub validate_uploaded_scantron_file {
                   9647:     my ($cdom,$cname,$fname) = @_;
                   9648:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9649:     my @lines;
                   9650:     if ($scanlines ne '-1') {
                   9651:         @lines=split("\n",$scanlines,-1);
                   9652:     }
                   9653:     my $output;
                   9654:     if (@lines) {
                   9655:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9656:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9657:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9658:         my %idmap = &username_to_idmap($classlist);
                   9659:         foreach my $key (keys(%idmap)) {
                   9660:             my $lckey = lc($key);
                   9661:             $idmap{$lckey} = $idmap{$key};
                   9662:         }
                   9663:         my %unique_formats;
1.596.2.12.2.  9(raebur 9664:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9665:         foreach my $line (@formatlines) {
1.596.2.12.2.  0.2.1(ra 9666:an-23):             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  9667:             my @config = split(/:/,$line);
                   9668:             my $idstart = $config[5];
                   9669:             my $idlength = $config[6];
                   9670:             if (($idstart ne '') && ($idlength > 0)) {
                   9671:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9672:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9673:                 } else {
                   9674:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9675:                 }
                   9676:             }
                   9677:         }
                   9678:         foreach my $key (keys(%unique_formats)) {
                   9679:             my ($idstart,$idlength) = split(':',$key);
                   9680:             %{$counts{$key}} = (
                   9681:                                'found'   => 0,
                   9682:                                'total'   => 0,
                   9683:                               );
                   9684:             foreach my $line (@lines) {
                   9685:                 next if ($line =~ /^#/);
                   9686:                 next if ($line =~ /^[\s\cz]*$/);
                   9687:                 my $id = substr($line,$idstart-1,$idlength);
                   9688:                 $id = lc($id);
                   9689:                 if (exists($idmap{$id})) {
                   9690:                     $counts{$key}{'found'} ++;
                   9691:                 }
                   9692:                 $counts{$key}{'total'} ++;
                   9693:             }
                   9694:             if ($counts{$key}{'total'}) {
                   9695:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9696:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9697:                     $max_match_pct = $percent_match;
                   9698:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9699:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9700:                     $max_match_count = $counts{$key}{'total'};
                   9701:                 }
                   9702:             }
                   9703:         }
                   9704:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9705:             my $format_descs;
                   9706:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9707:             for (my $i=0; $i<$numwithformat; $i++) {
                   9708:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9709:                 if ($i<$numwithformat-2) {
                   9710:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9711:                 } elsif ($i==$numwithformat-2) {
                   9712:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9713:                 } elsif ($i==$numwithformat-1) {
                   9714:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9715:                 }
                   9716:             }
                   9717:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9718:3):             $output .= '<br />';
                   9719:3):             if ($found_match_count == $max_match_count) {
                   9720:3):                 # 100% matching entries
                   9721:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9722:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9723:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9724:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9725:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9726:3):                     ' in the file (for the format defined for [_3]).',
                   9727:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9728:3):             } else {
                   9729:3):                 # Not all entries matching? -> Show warning and additional info
                   9730:3):                 $output .=
                   9731:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9732:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9733:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9734:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9735:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9736:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9737:3):                         ' in the file (for the format defined for [_3]).',
                   9738:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9739:3):                     '<p class="LC_info">'.
                   9740:3):                     &mt('A low percentage of matches results from one of the following:').
                   9741:3):                     '</p><ul>'.
                   9742:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9743:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9744:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9745:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9746:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9747:3):                     '</ul>';
                   9748:3):             }
1.567     raeburn  9749:         }
                   9750:     } else {
1.596.2.12.2.  5(raebur 9751:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9752:     }
                   9753:     return $output;
                   9754: }
                   9755: 
1.202     albertel 9756: sub valid_file {
                   9757:     my ($requested_file)=@_;
                   9758:     foreach my $filename (sort(&scantron_filenames())) {
                   9759: 	if ($requested_file eq $filename) { return 1; }
                   9760:     }
                   9761:     return 0;
                   9762: }
                   9763: 
                   9764: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9765:0):     my ($r,$symb) = @_;
          (raeburn 9766:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9767:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9768:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9769:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9770:     if (! &valid_file($file)) {
1.492     albertel 9771: 	$r->print('
1.202     albertel 9772: 	<p>
1.596.2.12.2.  3(raebur 9773:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9774:         </p>
1.492     albertel 9775: ');
1.202     albertel 9776: 	return;
                   9777:     }
                   9778:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9779:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9780:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9781:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9782:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9783:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9784:     $r->print('
1.202     albertel 9785:     <p>
1.596.2.12.2.  1(raebur 9786:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9787: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9788:     </p>
                   9789:     <p>
1.492     albertel 9790: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9791: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9792:     </p>
                   9793:     <p>
1.492     albertel 9794: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9795: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9796:     </p>
1.492     albertel 9797: ');
1.202     albertel 9798:     return '';
                   9799: }
1.157     albertel 9800: 
1.523     raeburn  9801: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9802:0):     my ($r,$symb) = @_;
1.523     raeburn  9803:     if (!$symb) {return '';}
                   9804:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9805:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9806:     my $numletts = scalar(keys(%lettdig));
                   9807:     my $cnum = $env{'course.'.$cid.'.num'};
                   9808:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9809:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9810:     my %record;
                   9811:     my %scantron_config =
1.596.2.12.2.  9(raebur 9812:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9813:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9814:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9815:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9816:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9817:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9818:     unless (ref($navmap)) {
                   9819:         $r->print(&navmap_errormsg());
                   9820:         return '';
                   9821:     }
1.523     raeburn  9822:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9823:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9824:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9825:2):     if (ref($map)) {
                   9826:2):         $randomorder=$map->randomorder();
          7(raebur 9827:3):         $randompick=$map->randompick();
          0(raebur 9828:2):         unless ($randomorder || $randompick) {
                   9829:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9830:2):                 if ($res->randomorder()) {
                   9831:2):                     $randomorder = 1;
                   9832:2):                 }
                   9833:2):                 if ($res->randompick()) {
                   9834:2):                     $randompick = 1;
                   9835:2):                 }
                   9836:2):                 last if ($randomorder || $randompick);
                   9837:2):             }
                   9838:2):         }
          1(raebur 9839:2):     }
1.557     raeburn  9840:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9841:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9842:3):     if ($nav_error) {
                   9843:3):         $r->print(&navmap_errormsg());
                   9844:3):         return '';
          1(raebur 9845:2):     }
          (raeburn 9846:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9847:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9848:     my ($uname,$udom);
1.523     raeburn  9849:     my (%scandata,%lastname,%bylast);
                   9850:     $r->print('
                   9851: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9852: 
                   9853:     my @delayqueue;
                   9854:     my %completedstudents;
                   9855: 
1.596.2.12.2.  6(raebur 9856:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9857:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9858:3):     my ($username,$domain,$started);
          (raeburn 9859:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9860:     if ($nav_error) {
                   9861:         $r->print(&navmap_errormsg());
                   9862:         return '';
                   9863:     }
1.523     raeburn  9864: 
                   9865:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9866:                                           'Processing first student');
                   9867:     my $start=&Time::HiRes::time();
                   9868:     my $i=-1;
                   9869: 
                   9870:     while ($i<$scanlines->{'count'}) {
                   9871:         ($username,$domain,$uname)=('','','');
                   9872:         $i++;
                   9873:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9874:         if ($line=~/^[\s\cz]*$/) { next; }
                   9875:         if ($started) {
                   9876:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9877:                                                      'last student');
                   9878:         }
                   9879:         $started=1;
                   9880:         my $scan_record=
                   9881:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9882:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9883:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9884:3):                                               \%idmap,$i)) {
1.523     raeburn  9885:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9886:                                 'Unable to find a student that matches',1);
                   9887:             next;
                   9888:         }
                   9889:         if (exists $completedstudents{$uname}) {
                   9890:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9891:                                 'Student '.$uname.' has multiple sheets',2);
                   9892:             next;
                   9893:         }
                   9894:         my $pid = $scan_record->{'scantron.ID'};
                   9895:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9896:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9897:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9898:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9899:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9900:2): 
                   9901:2):         my $scancode;
                   9902:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9903:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9904:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9905:2):         } else {
                   9906:2):             $scancode = '';
                   9907:2):         }
                   9908:2): 
                   9909:2):         my @mapresources = @resources;
          6(raebur 9910:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9911:3):         my %respnumlookup=();
                   9912:3):         my %startline=();
                   9913:3):         if ($randomorder || $randompick) {
          1(raebur 9914:2):             @mapresources =
          6(raebur 9915:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9916:3):                              \%orderedforcode);
                   9917:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9918:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9919:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9920:3):                                              \%respnumlookup,\%startline);
                   9921:3):             if ($randompick && $total) {
                   9922:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9923:3):             }
          1(raebur 9924:2):         }
          6(raebur 9925:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9926:3):         chomp($scandata{$pid});
                   9927:3):         $scandata{$pid} =~ s/\r$//;
                   9928:3): 
1.523     raeburn  9929:         my $counter = -1;
1.596.2.12.2.  1(raebur 9930:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9931:             my $parts;
1.554     raeburn  9932:             my $ressymb = $resource->symb();
1.557     raeburn  9933:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9934:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9935:7):                 my $currcode;
                   9936:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9937:7):                     $currcode = $scancode;
                   9938:7):                 }
1.557     raeburn  9939:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9940:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9941:):                                               $username,$domain,undef,
          1(raebur 9942:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9943:             } else {
                   9944:                 $parts = $grader_partids_by_symb{$ressymb};
                   9945:             }
1.542     raeburn  9946:             ($counter,my $recording) =
                   9947:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9948:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9949:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9950:3):                                          $randomorder,$randompick,
                   9951:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9952:             $record{$pid} .= $recording;
1.523     raeburn  9953:         }
                   9954:     }
                   9955:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9956:     $r->print('<br />');
                   9957:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9958:     $passed = 0;
                   9959:     $failed = 0;
                   9960:     $numstudents = 0;
                   9961:     foreach my $last (sort(keys(%bylast))) {
                   9962:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9963:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9964:                 my $showscandata = $scandata{$pid};
                   9965:                 my $showrecord = $record{$pid};
                   9966:                 $showscandata =~ s/\s/&nbsp;/g;
                   9967:                 $showrecord =~ s/\s/&nbsp;/g;
                   9968:                 if ($scandata{$pid} eq $record{$pid}) {
                   9969:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9970:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9971: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9972: '</tr>'."\n".
                   9973: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9974:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9975:                     $passed ++;
                   9976:                 } else {
                   9977:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9978:                     $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".
1.523     raeburn  9979: '</tr>'."\n".
                   9980: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9981:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9982: '</tr>'."\n";
                   9983:                     $failed ++;
                   9984:                 }
                   9985:                 $numstudents ++;
                   9986:             }
                   9987:         }
                   9988:     }
1.596.2.4  raeburn  9989:     $r->print('<p>'.
1.596.2.8  raeburn  9990:               &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).',
1.596.2.4  raeburn  9991:                   '<b>',
                   9992:                   $numstudents,
                   9993:                   '</b>',
                   9994:                   $env{'form.scantron_maxbubble'}).
                   9995:               '</p>'
                   9996:     );
1.596.2.12.2.  2(raebur 9997:2):     $r->print('<p>'
                   9998:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9999:2):              .'<br />'
                   10000:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10001:2):              .'</p>');
1.523     raeburn  10002:     if ($passed) {
1.572     www      10003:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10004:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10005:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10006:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10007:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10008:                  $okstudents."\n".
                   10009:                  &Apache::loncommon::end_data_table().'<br />');
                   10010:     }
                   10011:     if ($failed) {
1.572     www      10012:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10013:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10014:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10015:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10016:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10017:                  $badstudents."\n".
                   10018:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10019:                  &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.');  
1.523     raeburn  10020:     }
1.596.2.12.2.  1(raebur 10021:0):     $r->print('</form><br />');
1.523     raeburn  10022:     return;
                   10023: }
                   10024: 
1.542     raeburn  10025: sub verify_scantron_grading {
1.554     raeburn  10026:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 10027:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10028:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  10029:     my ($record,%expected,%startpos);
                   10030:     return ($counter,$record) if (!ref($resource));
                   10031:     return ($counter,$record) if (!$resource->is_problem());
                   10032:     my $symb = $resource->symb();
1.554     raeburn  10033:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10034:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10035:         $counter ++;
                   10036:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 10037:3):         my $respnum = $counter;
                   10038:3):         if ($randomorder || $randompick) {
                   10039:3):             $respnum = $respnumlookup->{$counter};
                   10040:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   10041:3):         } else {
                   10042:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10043:3):         }
                   10044:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10045:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10046:             foreach my $item (@sub_lines) {
                   10047:                 $expected{$part_id} += $item;
                   10048:             }
                   10049:         } else {
1.596.2.12.2.  6(raebur 10050:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10051:         }
                   10052:     }
                   10053:     if ($symb) {
                   10054:         my %recorded;
                   10055:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10056:         if ($returnhash{'version'}) {
                   10057:             my %lasthash=();
                   10058:             my $version;
                   10059:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10060:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10061:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10062:                 }
                   10063:             }
                   10064:             foreach my $key (keys(%lasthash)) {
                   10065:                 if ($key =~ /\.scantron$/) {
                   10066:                     my $value = &unescape($lasthash{$key});
                   10067:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10068:                     if ($value eq '') {
                   10069:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10070:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10071:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10072:                             }
                   10073:                         }
                   10074:                     } else {
                   10075:                         my @tocheck;
                   10076:                         my @items = split(//,$value);
                   10077:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10078:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10079:                             if (@items < $expected{$part_id}) {
                   10080:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10081:                                 my @singles = split(//,$fragment);
                   10082:                                 foreach my $pos (@singles) {
                   10083:                                     if ($pos eq ' ') {
                   10084:                                         push(@tocheck,$pos);
                   10085:                                     } else {
                   10086:                                         my $next = shift(@items);
                   10087:                                         push(@tocheck,$next);
                   10088:                                     }
                   10089:                                 }
                   10090:                             } else {
                   10091:                                 @tocheck = @items;
                   10092:                             }
                   10093:                             foreach my $letter (@tocheck) {
                   10094:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10095:                                     if ($letter !~ /^[A-J]$/) {
                   10096:                                         $letter = $scantron_config->{'Qoff'};
                   10097:                                     }
                   10098:                                     $recorded{$part_id} .= $letter;
                   10099:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10100:                                     my $digit;
                   10101:                                     if ($letter !~ /^[A-J]$/) {
                   10102:                                         $digit = $scantron_config->{'Qoff'};
                   10103:                                     } else {
                   10104:                                         $digit = $lettdig->{$letter};
                   10105:                                     }
                   10106:                                     $recorded{$part_id} .= $digit;
                   10107:                                 }
                   10108:                             }
                   10109:                         } else {
                   10110:                             @tocheck = @items;
                   10111:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10112:                                 my $curr_sub = shift(@tocheck);
                   10113:                                 my $digit;
                   10114:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10115:                                     $digit = $lettdig->{$curr_sub}-1;
                   10116:                                 }
                   10117:                                 if ($curr_sub eq 'J') {
                   10118:                                     $digit += scalar($numletts);
                   10119:                                 }
                   10120:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10121:                                     if ($j == $digit) {
                   10122:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10123:                                     } else {
                   10124:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10125:                                     }
                   10126:                                 }
                   10127:                             }
                   10128:                         }
                   10129:                     }
                   10130:                 }
                   10131:             }
                   10132:         }
1.554     raeburn  10133:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10134:             if ($recorded{$part_id} eq '') {
                   10135:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10136:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10137:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10138:                     }
                   10139:                 }
                   10140:             }
                   10141:             $record .= $recorded{$part_id};
                   10142:         }
                   10143:     }
                   10144:     return ($counter,$record);
                   10145: }
                   10146: 
1.75      albertel 10147: #-------- end of section for handling grading scantron forms -------
                   10148: #
                   10149: #-------------------------------------------------------------------
                   10150: 
1.72      ng       10151: #-------------------------- Menu interface -------------------------
                   10152: #
1.596.2.12.2.  (raeburn 10153:): #--- Href with symb and command ---
                   10154:): 
                   10155:): sub href_symb_cmd {
                   10156:):     my ($symb,$cmd)=@_;
                   10157:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   10158:): }
                   10159:): 
1.443     banghart 10160: sub grading_menu {
1.596.2.12.2.  1(raebur 10161:0):     my ($request,$symb) = @_;
1.443     banghart 10162:     if (!$symb) {return '';}
                   10163: 
                   10164:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 10165:0):                   'command'=>'individual');
                   10166:0): 
                   10167:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10168:0): 
                   10169:0):     $fields{'command'}='ungraded';
                   10170:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10171:0): 
                   10172:0):     $fields{'command'}='table';
                   10173:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10174:0): 
                   10175:0):     $fields{'command'}='all_for_one';
                   10176:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10177:0): 
                   10178:0):     $fields{'command'}='downloadfilesselect';
                   10179:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10180:     
1.443     banghart 10181:     $fields{'command'} = 'csvform';
1.538     schulted 10182:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10183:     
1.443     banghart 10184:     $fields{'command'} = 'processclicker';
1.538     schulted 10185:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10186:     
1.443     banghart 10187:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10188:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 10189:0): 
                   10190:0):     $fields{'command'} = 'initialverifyreceipt';
                   10191:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
          6(raebur 10192:1): 
                   10193:1):     my %permissions;
                   10194:1):     if ($perm{'mgr'}) {
                   10195:1):         $permissions{'either'} = 'F';
                   10196:1):         $permissions{'mgr'} = 'F';
                   10197:1):     }
                   10198:1):     if ($perm{'vgr'}) {
                   10199:1):         $permissions{'either'} = 'F';
                   10200:1):         $permissions{'vgr'} = 'F';
                   10201:1):     }
                   10202:1): 
          1(raebur 10203:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10204:             items =>[
1.596.2.12.2.  1(raebur 10205:0):                         {       linktext => 'Select individual students to grade',
                   10206:0):                                 url => $url1a,
          6(raebur 10207:1):                                 permission => $permissions{'either'},
          1(raebur 10208:0):                                 icon => 'grade_students.png',
                   10209:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   10210:0):                         },
                   10211:0):                         {       linktext => 'Grade ungraded submissions',
                   10212:0):                                 url => $url1b,
          6(raebur 10213:1):                                 permission => $permissions{'either'},
          1(raebur 10214:0):                                 icon => 'ungrade_sub.png',
                   10215:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   10216:0):                         },
                   10217:0): 
                   10218:0):                         {       linktext => 'Grading table',
                   10219:0):                                 url => $url1c,
          6(raebur 10220:1):                                 permission => $permissions{'either'},
          1(raebur 10221:0):                                 icon => 'grading_table.png',
                   10222:0):                                 linktitle => 'Grade current resource for all students.'
                   10223:0):                         },
                   10224:0):                         {       linktext => 'Grade page/folder for one student',
                   10225:0):                                 url => $url1d,
          6(raebur 10226:1):                                 permission => $permissions{'either'},
          1(raebur 10227:0):                                 icon => 'grade_PageFolder.png',
                   10228:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 10229:                         },
1.596.2.12.2.  3(raebur 10230:0):                         {       linktext => 'Download submitted files',
          1(raebur 10231:0):                                 url => $url1e,
          6(raebur 10232:1):                                 permission => $permissions{'either'},
          1(raebur 10233:0):                                 icon => 'download_sub.png',
          3(raebur 10234:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 10235:0):                         }]},
                   10236:0):                          { categorytitle=>'Automated Grading',
                   10237:0):                items =>[
                   10238:0): 
1.538     schulted 10239:                 	    {	linktext => 'Upload Scores',
                   10240:                     		url => $url2,
1.596.2.12.2.  6(raebur 10241:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10242:                     		icon => 'uploadscores.png',
                   10243:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10244:                 	    },
                   10245:                 	    {	linktext => 'Process Clicker',
                   10246:                     		url => $url3,
1.596.2.12.2.  6(raebur 10247:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10248:                     		icon => 'addClickerInfoFile.png',
                   10249:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10250:                 	    },
1.587     raeburn  10251:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10252:                     		url => $url4,
1.596.2.12.2.  6(raebur 10253:1):                     		permission => $permissions{'mgr'},
          1(raebur 10254:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  10255:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 10256:0):                 	    },
                   10257:0):                             {   linktext => 'Verify Receipt Number',
                   10258:0):                                 url => $url5,
          6(raebur 10259:1):                                 permission => $permissions{'either'},
          1(raebur 10260:0):                                 icon => 'receipt_number.png',
                   10261:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10262:0):                             }
                   10263:0): 
1.538     schulted 10264:                     ]
                   10265:             });
                   10266: 
1.443     banghart 10267:     # Create the menu
                   10268:     my $Str;
1.445     banghart 10269:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10270:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 10271:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 10272: 
1.596.2.12.2.  1(raebur 10273:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10274:     return $Str;    
                   10275: }
                   10276: 
1.596.2.12.2.  1(raebur 10277:0): sub ungraded {
                   10278:0):     my ($request)=@_;
                   10279:0):     &submit_options($request);
                   10280:0): }
1.443     banghart 10281: 
1.596.2.12.2.  1(raebur 10282:0): sub submit_options_sequence {
                   10283:0):     my ($request,$symb) = @_;
1.72      ng       10284:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 10285:0):     &commonJSfunctions($request);
                   10286:0):     my $result;
1.72      ng       10287: 
1.596.2.12.2.  1(raebur 10288:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10289:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10290:0):     $result.=&selectfield(0).
                   10291:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   10292:0):             <div>
                   10293:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10294:0):             </div>
                   10295:0):         </div>
                   10296:0):   </form>';
                   10297:0):     return $result;
                   10298:0): }
                   10299:0): 
                   10300:0): sub submit_options_table {
                   10301:0):     my ($request,$symb) = @_;
                   10302:0):     if (!$symb) {return '';}
1.118     ng       10303:     &commonJSfunctions($request);
1.596.2.12.2.  0.2.4(ra 10304:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
1.473     albertel 10305:     my $result;
1.596.2.12.2.  1(raebur 10306:0): 
                   10307:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10308:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10309:0): 
          0.2.4(ra 10310:ul-23):     $result.=&selectfield(1,$is_tool).
          1(raebur 10311:0):             '<input type="hidden" name="command" value="viewgrades" />
                   10312:0):             <div>
                   10313:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10314:0):             </div>
                   10315:0):         </div>
                   10316:0):   </form>';
                   10317:0):     return $result;
                   10318:0): }
                   10319:0): 
                   10320:0): sub submit_options_download {
                   10321:0):     my ($request,$symb) = @_;
                   10322:0):     if (!$symb) {return '';}
                   10323:0): 
                   10324:0):     my $res_error;
                   10325:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10326:0):         &response_type($symb,\$res_error);
                   10327:0):     if ($res_error) {
                   10328:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10329:0):         return;
                   10330:0):     }
                   10331:0):     unless ($numessay) {
                   10332:0):         $request->print(&mt('No essayresponse items found'));
                   10333:0):         return;
                   10334:0):     }
                   10335:0):     my $table;
                   10336:0):     if (ref($partlist) eq 'ARRAY') {
                   10337:0):         if (scalar(@$partlist) > 1 ) {
                   10338:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10339:         }
                   10340:     }
                   10341: 
1.596.2.12.2.  0.2.4(ra 10342:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          1(raebur 10343:0):     &commonJSfunctions($request);
1.72      ng       10344: 
1.596.2.12.2.  1(raebur 10345:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10346:0):         $table."\n".
                   10347:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10348:     $result.='
1.533     bisitz   10349: <h2>
1.596.2.12.2.  3(raebur 10350:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          0.2.4(ra 10351:ul-23): </h2>'.&selectfield(1,$is_tool).'
          1(raebur 10352:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10353:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10354:0):             </div>
                   10355:0):           </div>
                   10356:0): 
                   10357:0): 
                   10358:0):   </form>';
                   10359:0):     return $result;
                   10360:0): }
                   10361:0): 
                   10362:0): #--- Displays the submissions first page -------
                   10363:0): sub submit_options {
                   10364:0):     my ($request,$symb) = @_;
                   10365:0):     if (!$symb) {return '';}
                   10366:0): 
          0.2.4(ra 10367:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          1(raebur 10368:0):     &commonJSfunctions($request);
                   10369:0):     my $result;
                   10370:0): 
                   10371:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10372:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
          0.2.4(ra 10373:ul-23):     $result.=&selectfield(1,$is_tool).'
          1(raebur 10374:0):                 <input type="hidden" name="command" value="submission" />
                   10375:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10376:0):             </div>
                   10377:0):           </div>
                   10378:0):   </form>';
                   10379:0):     return $result;
                   10380:0): }
                   10381:0): 
                   10382:0): sub selectfield {
          0.2.4(ra 10383:ul-23):    my ($full,$is_tool)=@_;
                   10384:ul-23):    my %options;
                   10385:ul-23):    if ($is_tool) {
                   10386:ul-23):        %options =
                   10387:ul-23):            (&transtatus_options,
                   10388:ul-23):             'select_form_order' => ['yes','incorrect','all']);
                   10389:ul-23):    } else {
                   10390:ul-23):        %options =
                   10391:ul-23):            (&substatus_options,
                   10392:ul-23):             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10393:ul-23):    }
          7(raebur 10394:1): 
                   10395:1):   #
                   10396:1):   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10397:1):   # for a different course from the @Sections global in lonstatistics.pm,
                   10398:1):   # populated by an earlier request.
                   10399:1):   #
                   10400:1):    &Apache::lonstatistics::PrepareClasslist();
                   10401:1): 
          1(raebur 10402:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10403: 
                   10404:     <fieldset>
                   10405:       <legend>
                   10406:        '.&mt('Sections').'
                   10407:       </legend>
1.596.2.12.2.  1(raebur 10408:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10409:     </fieldset>
1.596.2.12.2.  1(raebur 10410:0): 
1.533     bisitz   10411:     <fieldset>
                   10412:       <legend>
                   10413:         '.&mt('Groups').'
                   10414:       </legend>
                   10415:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10416:     </fieldset>
1.596.2.12.2.  1(raebur 10417:0):  
1.533     bisitz   10418:     <fieldset>
                   10419:       <legend>
                   10420:         '.&mt('Access Status').'
                   10421:       </legend>
1.596.2.12.2.  1(raebur 10422:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10423:0):     </fieldset>';
                   10424:0):     if ($full) {
          0.2.4(ra 10425:ul-23):         my $heading = &mt('Submission Status');
                   10426:ul-23):         if ($is_tool) {
                   10427:ul-23):             $heading = &mt('Transaction Status');
                   10428:ul-23):         }
          1(raebur 10429:0):         $result.='
1.533     bisitz   10430:     <fieldset>
                   10431:       <legend>
1.596.2.12.2.  0.2.4(ra 10432:ul-23):         '.$heading.'
          1(raebur 10433:0):       </legend>'.
                   10434:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10435:0):    '</fieldset>';
                   10436:0):     }
                   10437:0):     $result.='</div><br />';
1.44      ng       10438:     return $result;
1.2       albertel 10439: }
                   10440: 
1.596.2.12.2.  7(raebur 10441:6): sub substatus_options {
                   10442:6):     return &Apache::lonlocal::texthash(
                   10443:6):                                       'yes'       => 'with submissions',
                   10444:6):                                       'queued'    => 'in grading queue',
                   10445:6):                                       'graded'    => 'with ungraded submissions',
                   10446:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10447:7):                                       'all'       => 'with any status',
                   10448:7):                                       );
          7(raebur 10449:6): }
                   10450:6): 
          1(raebur 10451:0): sub transtatus_options {
                   10452:0):     return &Apache::lonlocal::texthash(
                   10453:0):                                        'yes'       => 'with score transactions',
                   10454:0):                                        'incorrect' => 'with less than full credit',
                   10455:0):                                        'all'       => 'with any status',
                   10456:0):                                       );
                   10457:0): }
                   10458:0): 
1.285     albertel 10459: sub reset_perm {
                   10460:     undef(%perm);
                   10461: }
                   10462: 
                   10463: sub init_perm {
                   10464:     &reset_perm();
1.300     albertel 10465:     foreach my $test_perm ('vgr','mgr','opa') {
                   10466: 
                   10467: 	my $scope = $env{'request.course.id'};
                   10468: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10469: 
                   10470: 	    $scope .= '/'.$env{'request.course.sec'};
                   10471: 	    if ( $perm{$test_perm}=
                   10472: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10473: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10474: 	    } else {
                   10475: 		delete($perm{$test_perm});
                   10476: 	    }
1.285     albertel 10477: 	}
                   10478:     }
                   10479: }
                   10480: 
1.596.2.12.2.  (raeburn 10481:): sub init_old_essays {
                   10482:):     my ($symb,$apath,$adom,$aname) = @_;
                   10483:):     if ($symb ne '') {
                   10484:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10485:):         if (keys(%essays) > 0) {
                   10486:):             $old_essays{$symb} = \%essays;
                   10487:):         }
                   10488:):     }
                   10489:):     return;
                   10490:): }
                   10491:): 
                   10492:): sub reset_old_essays {
                   10493:):     undef(%old_essays);
                   10494:): }
                   10495:): 
1.400     www      10496: sub gather_clicker_ids {
1.408     albertel 10497:     my %clicker_ids;
1.400     www      10498: 
                   10499:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10500: 
                   10501:     # Set up a couple variables.
1.407     albertel 10502:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10503:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10504:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10505: 
1.407     albertel 10506:     foreach my $student (keys(%$classlist)) {
1.438     www      10507:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10508:         my $username = $classlist->{$student}->[$username_idx];
                   10509:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10510:         my $clickers =
1.408     albertel 10511: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10512:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10513:             $id=~s/^[\#0]+//;
1.421     www      10514:             $id=~s/[\-\:]//g;
1.407     albertel 10515:             if (exists($clicker_ids{$id})) {
1.408     albertel 10516: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10517:             } else {
1.408     albertel 10518: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10519:             }
                   10520:         }
                   10521:     }
1.407     albertel 10522:     return %clicker_ids;
1.400     www      10523: }
                   10524: 
1.402     www      10525: sub gather_adv_clicker_ids {
1.408     albertel 10526:     my %clicker_ids;
1.402     www      10527:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10528:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10529:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10530:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10531:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10532:             my ($puname,$pudom)=split(/\:/,$person);
                   10533:             my $clickers =
1.408     albertel 10534: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10535:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10536: 		$id=~s/^[\#0]+//;
1.421     www      10537:                 $id=~s/[\-\:]//g;
1.408     albertel 10538: 		if (exists($clicker_ids{$id})) {
                   10539: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10540: 		} else {
                   10541: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10542: 		}
1.405     www      10543:             }
1.402     www      10544:         }
                   10545:     }
1.407     albertel 10546:     return %clicker_ids;
1.402     www      10547: }
                   10548: 
1.413     www      10549: sub clicker_grading_parameters {
                   10550:     return ('gradingmechanism' => 'scalar',
                   10551:             'upfiletype' => 'scalar',
                   10552:             'specificid' => 'scalar',
                   10553:             'pcorrect' => 'scalar',
                   10554:             'pincorrect' => 'scalar');
                   10555: }
                   10556: 
1.400     www      10557: sub process_clicker {
1.596.2.12.2.  1(raebur 10558:0):     my ($r,$symb)=@_;
1.400     www      10559:     if (!$symb) {return '';}
                   10560:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10561:0):     $result.=&Apache::loncommon::start_data_table().
                   10562:0):              &Apache::loncommon::start_data_table_header_row().
                   10563:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10564:0):              &Apache::loncommon::end_data_table_header_row().
                   10565:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10566: # Attempt to restore parameters from last session, set defaults if not present
                   10567:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10568:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10569:                                                  \%Saveable_Parameters);
                   10570:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10571:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10572:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10573:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10574: 
                   10575:     my %checked;
1.521     www      10576:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10577:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10578:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10579:        }
                   10580:     }
                   10581: 
1.596.2.12.2.  1(raebur 10582:0):     my $upload=&mt("Evaluate File");
1.400     www      10583:     my $type=&mt("Type");
1.402     www      10584:     my $attendance=&mt("Award points just for participation");
                   10585:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10586:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10587:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10588:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10589:     my $pcorrect=&mt("Percentage points for correct solution");
                   10590:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10591:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10592:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10593:):                                                     'interwrite' => 'interwrite PRS',
                   10594:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10595:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10596:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10597: function sanitycheck() {
                   10598: // Accept only integer percentages
                   10599:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10600:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10601: // Find out grading choice
                   10602:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10603:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10604:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10605:       }
                   10606:    }
                   10607: // By default, new choice equals user selection
                   10608:    newgradingchoice=gradingchoice;
                   10609: // Not good to give more points for false answers than correct ones
                   10610:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10611:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10612:    }
                   10613: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10614:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10615:       document.forms.gradesupload.pcorrect.value=100;
                   10616:       document.forms.gradesupload.pincorrect.value=100;
                   10617:    }
                   10618: // If the values are different, cannot be attendance only
                   10619:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10620:        (gradingchoice=='attendance')) {
                   10621:        newgradingchoice='personnel';
                   10622:    }
                   10623: // Change grading choice to new one
                   10624:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10625:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10626:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10627:       } else {
                   10628:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10629:       }
                   10630:    }
                   10631: // Remember the old state
                   10632:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10633: }
1.596.2.12.2.  1(raebur 10634:0): ENDUPFORM
                   10635:0):     $result.= <<ENDUPFORM;
1.400     www      10636: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10637: <input type="hidden" name="symb" value="$symb" />
                   10638: <input type="hidden" name="command" value="processclickerfile" />
                   10639: <input type="file" name="upfile" size="50" />
                   10640: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10641:0): ENDUPFORM
                   10642:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10643:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10644:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10645: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10646: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10647: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10648: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10649: <br />&nbsp;&nbsp;&nbsp;
                   10650: <input type="text" name="givenanswer" size="50" />
1.413     www      10651: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10652:0): ENDGRADINGFORM
                   10653:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10654:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10655:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10656: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10657: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10658: </form>
1.596.2.12.2.  1(raebur 10659:0): ENDPERCFORM
                   10660:0):     $result.='</td>'.
                   10661:0):              &Apache::loncommon::end_data_table_row().
                   10662:0):              &Apache::loncommon::end_data_table();
1.400     www      10663:     return $result;
                   10664: }
                   10665: 
                   10666: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10667:0):     my ($r,$symb) = @_;
1.400     www      10668:     if (!$symb) {return '';}
1.413     www      10669: 
                   10670:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10671:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10672:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10673:0):     my $result='';
1.404     www      10674:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10675: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10676:0): 	return $result;
1.404     www      10677:     }
1.522     www      10678:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10679:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10680:0):         return $result;
1.521     www      10681:     }
1.522     www      10682:     my $foundgiven=0;
1.521     www      10683:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10684:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10685:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10686:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10687:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10688:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10689:         $foundgiven=$#answers+1;
1.521     www      10690:     }
1.407     albertel 10691:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10692:     my %correct_ids;
1.404     www      10693:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10694: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10695:     }
                   10696:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10697: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10698: 	   $correct_id=~tr/a-z/A-Z/;
                   10699: 	   $correct_id=~s/\s//gs;
                   10700: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10701:            $correct_id=~s/[\-\:]//g;
1.414     www      10702:            if ($correct_id) {
                   10703: 	      $correct_ids{$correct_id}='specified';
                   10704:            }
                   10705:         }
1.400     www      10706:     }
1.404     www      10707:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10708: 	$result.=&mt('Score based on attendance only');
1.521     www      10709:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10710:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10711:     } else {
1.408     albertel 10712: 	my $number=0;
1.411     www      10713: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10714: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10715: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10716: 	    if ($correct_ids{$id} eq 'specified') {
                   10717: 		$result.=&mt('specified');
                   10718: 	    } else {
                   10719: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10720: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10721: 	    }
                   10722: 	    $number++;
                   10723: 	}
1.411     www      10724:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10725:3):         if ($number==0) {
                   10726:3):             $result .=
                   10727:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10728:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10729:0):             return $result;
          5(raebur 10730:3):         }
1.404     www      10731:     }
1.405     www      10732:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10733:3):         $result .=
                   10734:3):             &Apache::lonhtmlcommon::confirm_success(
                   10735:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10736:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10737:0):         return $result;
1.405     www      10738:     }
1.596.2.12.2.  7(raebur 10739:9):     my $mimetype;
                   10740:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10741:9):         my $mm = new File::MMagic;
                   10742:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10743:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10744:9):             $result.= '<p>'.
                   10745:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10746:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10747:0):             return $result;
          7(raebur 10748:9):         }
                   10749:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10750:9):         $result .= '<p>'.
                   10751:9):             &Apache::lonhtmlcommon::confirm_success(
                   10752:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10753:0):         return $result;
          7(raebur 10754:9):     }
1.410     www      10755: 
                   10756: # Were able to get all the info needed, now analyze the file
                   10757: 
1.411     www      10758:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10759:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10760:0):     $result.=&Apache::loncommon::start_data_table().
                   10761:0):              &Apache::loncommon::start_data_table_header_row().
                   10762:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10763:0):              &Apache::loncommon::end_data_table_header_row().
                   10764:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10765:0): <td>
1.410     www      10766: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10767: <input type="hidden" name="symb" value="$symb" />
                   10768: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10769: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10770: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10771: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10772: ENDHEADER
1.522     www      10773:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10774:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10775:     } 
1.408     albertel 10776:     my %responses;
                   10777:     my @questiontitles;
1.405     www      10778:     my $errormsg='';
                   10779:     my $number=0;
                   10780:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10781:9):         if ($mimetype eq 'text/plain') {
                   10782:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10783:9):         } elsif ($mimetype eq 'text/html') {
                   10784:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10785:9):         }
                   10786:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10787:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10788:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10789:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10790:):     }
1.411     www      10791:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10792:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10793:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10794:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10795:              '<br />';
1.522     www      10796:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10797:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.596.2.12.2.  1(raebur 10798:0):        return $result;
1.522     www      10799:     } 
1.414     www      10800: # Remember Question Titles
                   10801: # FIXME: Possibly need delimiter other than ":"
                   10802:     for (my $i=0;$i<$number;$i++) {
                   10803:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10804:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10805:     }
1.411     www      10806:     my $correct_count=0;
                   10807:     my $student_count=0;
                   10808:     my $unknown_count=0;
1.414     www      10809: # Match answers with usernames
                   10810: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10811:     foreach my $id (keys(%responses)) {
1.410     www      10812:        if ($correct_ids{$id}) {
1.414     www      10813:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10814:           $correct_count++;
1.410     www      10815:        } elsif ($clicker_ids{$id}) {
1.437     www      10816:           if ($clicker_ids{$id}=~/\,/) {
                   10817: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10818:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10819:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10820:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10821:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10822:                            "<select name='multi".$id."'>";
                   10823:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10824:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10825:              }
                   10826:              $result.='</select>';
                   10827:              $unknown_count++;
                   10828:           } else {
                   10829: # Good: found one and only one user with the right clicker
                   10830:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10831:              $student_count++;
                   10832:           }
1.410     www      10833:        } else {
1.596.2.12.2.  1(raebur 10834:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10835:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10836:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10837:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10838:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10839:                    "\n".&mt("Domain").": ".
                   10840:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10841:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10842:           $unknown_count++;
1.410     www      10843:        }
1.405     www      10844:     }
1.412     www      10845:     $result.='<hr />'.
                   10846:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10847:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10848:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10849:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10850:        } elsif ($correct_count>1) {
1.414     www      10851:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10852:        }
                   10853:     }
1.428     www      10854:     if ($number<1) {
                   10855:        $errormsg.="Found no questions.";
                   10856:     }
1.412     www      10857:     if ($errormsg) {
                   10858:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10859:     } else {
                   10860:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10861:     }
1.596.2.12.2.  1(raebur 10862:0):     $result.='</form></td>'.
                   10863:0):              &Apache::loncommon::end_data_table_row().
                   10864:0):              &Apache::loncommon::end_data_table();
                   10865:0):     return $result;
1.400     www      10866: }
                   10867: 
1.405     www      10868: sub iclicker_eval {
1.406     www      10869:     my ($questiontitles,$responses)=@_;
1.405     www      10870:     my $number=0;
                   10871:     my $errormsg='';
                   10872:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10873:         my %components=&Apache::loncommon::record_sep($line);
                   10874:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10875: 	if ($entries[0] eq 'Question') {
                   10876: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10877: 		$$questiontitles[$number]=$entries[$i];
                   10878: 		$number++;
                   10879: 	    }
                   10880: 	}
                   10881: 	if ($entries[0]=~/^\#/) {
                   10882: 	    my $id=$entries[0];
                   10883: 	    my @idresponses;
                   10884: 	    $id=~s/^[\#0]+//;
                   10885: 	    for (my $i=0;$i<$number;$i++) {
                   10886: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10887:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10888: 		push(@idresponses,$entries[$idx]);
                   10889: 	    }
                   10890: 	    $$responses{$id}=join(',',@idresponses);
                   10891: 	}
1.405     www      10892:     }
                   10893:     return ($errormsg,$number);
                   10894: }
                   10895: 
1.596.2.12.2.  7(raebur 10896:9): sub iclickerxml_eval {
                   10897:9):     my ($questiontitles,$responses)=@_;
                   10898:9):     my $number=0;
                   10899:9):     my $errormsg='';
                   10900:9):     my @state;
                   10901:9):     my %respbyid;
                   10902:9):     my $p = HTML::Parser->new
                   10903:9):     (
                   10904:9):         xml_mode => 1,
                   10905:9):         start_h =>
                   10906:9):             [sub {
                   10907:9):                  my ($tagname,$attr) = @_;
                   10908:9):                  push(@state,$tagname);
                   10909:9):                  if ("@state" eq "ssn p") {
                   10910:9):                      my $title = $attr->{qn};
                   10911:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10912:9):                      $questiontitles->[$number]=$title;
                   10913:9):                  } elsif ("@state" eq "ssn p v") {
                   10914:9):                      my $id = $attr->{id};
                   10915:9):                      my $entry = $attr->{ans};
                   10916:9):                      $id=~s/^[\#0]+//;
                   10917:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10918:9):                      $respbyid{$id}[$number] = $entry;
                   10919:9):                  }
                   10920:9):             }, "tagname, attr"],
                   10921:9):          end_h =>
                   10922:9):                [sub {
                   10923:9):                    my ($tagname) = @_;
                   10924:9):                    if ("@state" eq "ssn p") {
                   10925:9):                        $number++;
                   10926:9):                    }
                   10927:9):                    pop(@state);
                   10928:9):                 }, "tagname"],
                   10929:9):     );
                   10930:9): 
                   10931:9):     $p->parse($env{'form.upfile'});
                   10932:9):     $p->eof;
                   10933:9):     foreach my $id (keys(%respbyid)) {
                   10934:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10935:9):     }
                   10936:9):     return ($errormsg,$number);
                   10937:9): }
                   10938:9): 
1.419     www      10939: sub interwrite_eval {
                   10940:     my ($questiontitles,$responses)=@_;
                   10941:     my $number=0;
                   10942:     my $errormsg='';
1.420     www      10943:     my $skipline=1;
                   10944:     my $questionnumber=0;
                   10945:     my %idresponses=();
1.419     www      10946:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10947:         my %components=&Apache::loncommon::record_sep($line);
                   10948:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10949:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10950:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10951:         next if $skipline;
                   10952:         if ($entries[0]!=$questionnumber) {
                   10953:            $questionnumber=$entries[0];
                   10954:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10955:            $number++;
1.419     www      10956:         }
1.420     www      10957:         my $id=$entries[4];
                   10958:         $id=~s/^[\#0]+//;
1.421     www      10959:         $id=~s/^v\d*\://i;
                   10960:         $id=~s/[\-\:]//g;
1.420     www      10961:         $idresponses{$id}[$number]=$entries[6];
                   10962:     }
1.524     raeburn  10963:     foreach my $id (keys(%idresponses)) {
1.420     www      10964:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10965:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10966:     }
                   10967:     return ($errormsg,$number);
                   10968: }
                   10969: 
1.596.2.12.2.  (raeburn 10970:): sub turning_eval {
                   10971:):     my ($questiontitles,$responses)=@_;
                   10972:):     my $number=0;
                   10973:):     my $errormsg='';
                   10974:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10975:):         my %components=&Apache::loncommon::record_sep($line);
                   10976:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10977:):         if ($#entries>$number) { $number=$#entries; }
                   10978:):         my $id=$entries[0];
                   10979:):         my @idresponses;
                   10980:):         $id=~s/^[\#0]+//;
                   10981:):         unless ($id) { next; }
                   10982:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10983:):             $entries[$idx]=~s/\,/\;/g;
                   10984:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10985:):             push(@idresponses,$entries[$idx]);
                   10986:):         }
                   10987:):         $$responses{$id}=join(',',@idresponses);
                   10988:):     }
                   10989:):     for (my $i=1; $i<=$number; $i++) {
                   10990:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10991:):     }
                   10992:):     return ($errormsg,$number);
                   10993:): }
                   10994:): 
1.414     www      10995: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10996:0):     my ($r,$symb) = @_;
1.414     www      10997:     if (!$symb) {return '';}
1.416     www      10998: # See which part we are saving to
1.582     raeburn  10999:     my $res_error;
                   11000:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11001:     if ($res_error) {
                   11002:         return &navmap_errormsg();
                   11003:     }
1.416     www      11004: # FIXME: This should probably look for the first handgradeable part
                   11005:     my $part=$$partlist[0];
                   11006: # Start screen output
1.596.2.12.2.  1(raebur 11007:0):     my $result = &Apache::loncommon::start_data_table(). 
                   11008:0):                  &Apache::loncommon::start_data_table_header_row().
                   11009:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11010:0):                  &Apache::loncommon::end_data_table_header_row().
                   11011:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11012: # Get correct result
                   11013: # FIXME: Possibly need delimiter other than ":"
                   11014:     my @correct=();
1.415     www      11015:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11016:     my $number=$env{'form.number'};
                   11017:     if ($gradingmechanism ne 'attendance') {
1.414     www      11018:        foreach my $key (keys(%env)) {
                   11019:           if ($key=~/^form\.correct\:/) {
                   11020:              my @input=split(/\,/,$env{$key});
                   11021:              for (my $i=0;$i<=$#input;$i++) {
                   11022:                  if (($correct[$i]) && ($input[$i]) &&
                   11023:                      ($correct[$i] ne $input[$i])) {
                   11024:                     $result.='<br /><span class="LC_warning">'.
                   11025:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11026:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  11027:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11028:                     $correct[$i]=$input[$i];
                   11029:                  }
                   11030:              }
                   11031:           }
                   11032:        }
1.415     www      11033:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  11034:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11035:              $result.='<br /><span class="LC_error">'.
                   11036:                       &mt('No correct result given for question "[_1]"!',
                   11037:                           $env{'form.question:'.$i}).'</span>';
                   11038:           }
                   11039:        }
1.596.2.4  raeburn  11040:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11041:     }
                   11042: # Start grading
1.415     www      11043:     my $pcorrect=$env{'form.pcorrect'};
                   11044:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11045:     my $storecount=0;
1.596.2.4  raeburn  11046:     my %users=();
1.415     www      11047:     foreach my $key (keys(%env)) {
1.420     www      11048:        my $user='';
1.415     www      11049:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11050:           $user=$1;
                   11051:        }
                   11052:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11053:           my $id=$1;
                   11054:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11055:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11056:           } elsif ($env{'form.multi'.$id}) {
                   11057:              $user=$env{'form.multi'.$id};
1.420     www      11058:           }
                   11059:        }
1.596.2.4  raeburn  11060:        if ($user) {
                   11061:           if ($users{$user}) {
                   11062:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 11063:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  11064:                       '</span><br />';
                   11065:           }
                   11066:           $users{$user}=1;
1.415     www      11067:           my @answer=split(/\,/,$env{$key});
                   11068:           my $sum=0;
1.522     www      11069:           my $realnumber=$number;
1.415     www      11070:           for (my $i=0;$i<$number;$i++) {
1.576     www      11071:              if  ($correct[$i] eq '-') {
                   11072:                 $realnumber--;
1.596.2.12.2.  1(raebur 11073:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11074:                 if ($gradingmechanism eq 'attendance') {
                   11075:                    $sum+=$pcorrect;
1.576     www      11076:                 } elsif ($correct[$i] eq '*') {
1.522     www      11077:                    $sum+=$pcorrect;
1.415     www      11078:                 } else {
1.596.2.4  raeburn  11079: # We actually grade if correct or not
                   11080:                    my $increment=$pincorrect;
                   11081: # Special case: numerical answer "0"
                   11082:                    if ($correct[$i] eq '0') {
                   11083:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11084:                          $increment=$pcorrect;
                   11085:                       }
                   11086: # General numerical answer, both evaluate to something non-zero
                   11087:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11088:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11089:                          $increment=$pcorrect;
                   11090:                       }
                   11091: # Must be just alphanumeric
                   11092:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11093:                       $increment=$pcorrect;
1.415     www      11094:                    }
1.596.2.4  raeburn  11095:                    $sum+=$increment;
1.415     www      11096:                 }
                   11097:              }
                   11098:           }
1.522     www      11099:           my $ave=$sum/(100*$realnumber);
1.416     www      11100: # Store
                   11101:           my ($username,$domain)=split(/\:/,$user);
                   11102:           my %grades=();
                   11103:           $grades{"resource.$part.solved"}='correct_by_override';
                   11104:           $grades{"resource.$part.awarded"}=$ave;
                   11105:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11106:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11107:                                                  $env{'request.course.id'},
                   11108:                                                  $domain,$username);
                   11109:           if ($returncode ne 'ok') {
                   11110:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11111:           } else {
                   11112:              $storecount++;
                   11113:           }
1.415     www      11114:        }
                   11115:     }
                   11116: # We are done
1.549     hauer    11117:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  11118:              '</td>'.
                   11119:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 11120:0):              &Apache::loncommon::end_data_table();
                   11121:0):     return $result;
1.414     www      11122: }
                   11123: 
1.582     raeburn  11124: sub navmap_errormsg {
                   11125:     return '<div class="LC_error">'.
                   11126:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11127:            &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>').
1.582     raeburn  11128:            '</div>';
                   11129: }
                   11130: 
1.596.2.12.2.  (raeburn 11131:): sub startpage {
          5(raebur 11132:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
          9(raebur 11133:9):     my %args;
                   11134:9):     if ($onload) {
                   11135:9):          my %loaditems = (
                   11136:9):                         'onload' => $onload,
                   11137:9):                       );
                   11138:9):          $args{'add_entries'} = \%loaditems;
                   11139:9):     }
          (raeburn 11140:):     if ($nomenu) {
          9(raebur 11141:9):         $args{'only_body'} = 1;
          5(raebur 11142:0):         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
          (raeburn 11143:):     } else {
          8(raebur 11144:1):         if ($env{'request.course.id'}) {
                   11145:1):             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11146:1):         }
          9(raebur 11147:9):         $args{'bread_crumbs'} = $crumbs;
          5(raebur 11148:0):         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
          (raeburn 11149:):     }
                   11150:):     unless ($nodisplayflag) {
          1(raebur 11151:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 11152:):     }
                   11153:): }
                   11154:): 
          1(raebur 11155:0): sub select_problem {
                   11156:0):     my ($r)=@_;
                   11157:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   11158:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   11159:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11160:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11161:0): }
                   11162:0): 
          0.2.5(ra 11163:ep-23): #----- display problem, answer, and submissions for a single student (no grading)
                   11164:ep-23): 
                   11165:ep-23): sub view_as_user {
                   11166:ep-23):     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   11167:ep-23):     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   11168:ep-23):     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   11169:ep-23):     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   11170:ep-23):                                                       $env{'request.course.id'},
                   11171:ep-23):                                                       undef,{'disable_submit' => 1}).
                   11172:ep-23):                  "\n\n".
                   11173:ep-23):                  '<div class="LC_grade_show_user">'.
                   11174:ep-23):                  '<h2>'.$displayname.'</h2>'.
                   11175:ep-23):                  "\n".
                   11176:ep-23):                  &Apache::loncommon::track_student_link('View recent activity',
                   11177:ep-23):                                                         $vuname,$vudom,'check').' '.
                   11178:ep-23):                  "\n";
                   11179:ep-23):     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   11180:ep-23):         (($env{'request.course.sec'} ne '') &&
                   11181:ep-23):          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   11182:ep-23):         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   11183:ep-23):                                                $vuname,$vudom,$symb,'check');
                   11184:ep-23):     }
                   11185:ep-23):     $output .= "\n";
                   11186:ep-23):     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   11187:ep-23):                                                              $env{'request.course.id'});
                   11188:ep-23):     $companswer=~s|<form(.*?)>||g;
                   11189:ep-23):     $companswer=~s|</form>||g;
                   11190:ep-23):     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   11191:ep-23):     $output .= '<div class="LC_Box">'.
                   11192:ep-23):                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   11193:ep-23):                $companswer.
                   11194:ep-23):                '</div>'."\n";
                   11195:ep-23):     my $is_tool = ($symb =~ /ext\.tool$/);
                   11196:ep-23):     my ($essayurl,%coursedesc_by_cid);
                   11197:ep-23):     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   11198:ep-23):     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   11199:ep-23):     my $res_error;
                   11200:ep-23):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   11201:ep-23):         &response_type($symb,\$res_error);
                   11202:ep-23):     my $fullname;
                   11203:ep-23):     my $collabinfo;
                   11204:ep-23):     if ($numessay) {
                   11205:ep-23):         unless ($hasperm) {
                   11206:ep-23):             &init_perm();
                   11207:ep-23):         }
                   11208:ep-23):         ($collabinfo,$fullname)=
                   11209:ep-23):             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   11210:ep-23):         unless ($hasperm) {
                   11211:ep-23):             &reset_perm();
                   11212:ep-23):         }
                   11213:ep-23):     }
                   11214:ep-23):     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   11215:ep-23):                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   11216:ep-23):                     '/check.gif" height="16" border="0" />';
                   11217:ep-23):     my ($lastsubonly,$partinfo) =
                   11218:ep-23):         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   11219:ep-23):                               '',$fullname,\%record,\%coursedesc_by_cid);
                   11220:ep-23):     $output .= '<div class="LC_Box">'.
                   11221:ep-23):                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   11222:ep-23):     if (($numresp > $numessay) & !$is_tool) {
                   11223:ep-23):         $output .='<p class="LC_info">'.
                   11224:ep-23):                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   11225:ep-23):                   "</p>\n";
                   11226:ep-23):     }
                   11227:ep-23):     $output .= $partinfo;
                   11228:ep-23):     $output .= $lastsubonly;
                   11229:ep-23):     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   11230:ep-23):     $output .= '</div></div>'."\n";
                   11231:ep-23):     return $output;
                   11232:ep-23): }
                   11233:ep-23): 
1.1       albertel 11234: sub handler {
1.41      ng       11235:     my $request=$_[0];
1.434     albertel 11236:     &reset_caches();
1.596.2.4  raeburn  11237:     if ($request->header_only) {
                   11238:         &Apache::loncommon::content_type($request,'text/html');
                   11239:         $request->send_http_header;
                   11240:         return OK;
1.41      ng       11241:     }
                   11242:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  11243: 
1.596.2.12.2.  1(raebur 11244:0): # see what command we need to execute
                   11245:0):  
1.160     albertel 11246:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11247:     my $command=$commands[0];
1.447     foxr     11248: 
1.596.2.12.2.  1(raebur 11249:0):     &init_perm();
                   11250:0):     if (!$env{'request.course.id'}) {
                   11251:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11252:0):                 ($command =~ /^scantronupload/)) {
                   11253:0):             # Not in a course.
                   11254:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11255:0):             return HTTP_NOT_ACCEPTABLE;
                   11256:0):         }
                   11257:0):     } elsif (!%perm) {
                   11258:0):         $request->internal_redirect('/adm/quickgrades');
                   11259:0):         return OK;
                   11260:0):     }
                   11261:0):     &Apache::loncommon::content_type($request,'text/html');
                   11262:0):     $request->send_http_header;
                   11263:0): 
1.160     albertel 11264:     if ($#commands > 0) {
                   11265: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11266:     }
1.447     foxr     11267: 
1.596.2.12.2.  1(raebur 11268:0): # see what the symb is
                   11269:0): 
                   11270:0):     my $symb=$env{'form.symb'};
                   11271:0):     unless ($symb) {
                   11272:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11273:0):        $symb=&Apache::lonnet::symbread($url);
                   11274:0):     }
                   11275:0):     &Apache::lonenc::check_decrypt(\$symb);
                   11276:0): 
1.513     foxr     11277:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 11278:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   11279:0): #
                   11280:0): # Not called from a resource, but inside a course
                   11281:0): #
                   11282:0):         &startpage($request,undef,[],1,1);
                   11283:0):         &select_problem($request);
1.41      ng       11284:     } else {
1.596.2.12.2.  1(raebur 11285:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   11286:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 11287:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11288:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11289:):                     &choose_task_version_form($symb,$env{'form.student'},
                   11290:):                                               $env{'form.userdom'});
                   11291:):             }
          1(raebur 11292:0):             my $divforres;
                   11293:0):             if ($env{'form.student'} eq '') {
                   11294:0):                 $js .= &part_selector_js();
                   11295:0):                 $onload = "toggleParts('gradesub');";
                   11296:0):             } else {
                   11297:0):                 $divforres = 1;
                   11298:0):             }
          5(raebur 11299:0):             my $head_extra = $js;
                   11300:0):             unless ($env{'form.vProb'} eq 'no') {
                   11301:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11302:0):                 if ($csslinks) {
                   11303:0):                     $head_extra .= "\n$csslinks";
                   11304:0):                 }
                   11305:0):             }
                   11306:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11307:0):                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
          (raeburn 11308:):             if ($versionform) {
          2(raebur 11309:0):                 if ($divforres) {
                   11310:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11311:0):                 }
          (raeburn 11312:):                 $request->print($versionform);
                   11313:):             }
          1(raebur 11314:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 11315:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11316:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11317:):                 &choose_task_version_form($symb,$env{'form.student'},
                   11318:):                                           $env{'form.userdom'},
                   11319:):                                           $env{'form.inhibitmenu'});
          5(raebur 11320:0):             my $head_extra = $js;
                   11321:0):             unless ($env{'form.vProb'} eq 'no') {
                   11322:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11323:0):                 if ($csslinks) {
                   11324:0):                     $head_extra .= "\n$csslinks";
                   11325:0):                 }
                   11326:0):             }
                   11327:0):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11328:0):                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
          (raeburn 11329:):             if ($versionform) {
                   11330:):                 $request->print($versionform);
                   11331:):             }
                   11332:):             $request->print('<br clear="all" />');
                   11333:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 11334:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   11335:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11336:0):                                        {href=>'',text=>'Select student'}],1,1);
                   11337:0):             &pickStudentPage($request,$symb);
                   11338:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
          5(raebur 11339:0):             my $csslinks;
                   11340:0):             unless ($env{'form.vProb'} eq 'no') {
                   11341:0):                 $csslinks = &Apache::loncommon::css_links($symb,'map');
                   11342:0):             }
          1(raebur 11343:0):             &startpage($request,$symb,
                   11344:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11345:0):                                        {href=>'',text=>'Select student'},
          5(raebur 11346:0):                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
          1(raebur 11347:0):             &displayPage($request,$symb);
                   11348:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   11349:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11350:0):                                        {href=>'',text=>'Select student'},
                   11351:0):                                        {href=>'',text=>'Grade student'},
                   11352:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   11353:0):             &updateGradeByPage($request,$symb);
                   11354:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
          5(raebur 11355:0):             my $csslinks;
                   11356:0):             unless ($env{'form.vProb'} eq 'no') {
                   11357:0):                 $csslinks = &Apache::loncommon::css_links($symb);
                   11358:0):             }
          1(raebur 11359:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
          5(raebur 11360:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
          1(raebur 11361:0):             &processGroup($request,$symb);
                   11362:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   11363:0):             &startpage($request,$symb);
                   11364:0):             $request->print(&grading_menu($request,$symb));
                   11365:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   11366:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   11367:0):             $request->print(&submit_options($request,$symb));
                   11368:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   11369:0):             my $js = &part_selector_js();
                   11370:0):             my $onload = "toggleParts('gradesub');";
                   11371:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11372:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11373:0):             $request->print(&listStudents($request,$symb,'graded'));
                   11374:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   11375:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   11376:0):             $request->print(&submit_options_table($request,$symb));
                   11377:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   11378:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   11379:0):             $request->print(&submit_options_sequence($request,$symb));
                   11380:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   11381:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   11382:0):             $request->print(&viewgrades($request,$symb));
                   11383:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   11384:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11385:0):                                        {href=>'',text=>'Store grades'}]);
                   11386:0):             $request->print(&processHandGrade($request,$symb));
                   11387:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   11388:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11389:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11390:0):                                                                              text=>"Modify grades"},
                   11391:0):                                        {href=>'', text=>"Store grades"}]);
                   11392:0):             $request->print(&editgrades($request,$symb));
                   11393:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   11394:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   11395:0):             $request->print(&initialverifyreceipt($request,$symb));
                   11396:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   11397:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11398:0):                                        {href=>'',text=>'Verification Result'}]);
                   11399:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      11400:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11401:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   11402:0):             $request->print(&process_clicker($request,$symb));
1.400     www      11403:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11404:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11405:0):                                        {href=>'', text=>'Process clicker file'}]);
                   11406:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      11407:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11408:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11409:0):                                        {href=>'', text=>'Process clicker file'},
                   11410:0):                                        {href=>'', text=>'Store grades'}]);
                   11411:0):             $request->print(&assign_clicker_grades($request,$symb));
                   11412:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   11413:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11414:0):             $request->print(&upcsvScores_form($request,$symb));
                   11415:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   11416:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11417:0):             $request->print(&csvupload($request,$symb));
                   11418:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   11419:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11420:0):             $request->print(&csvuploadmap($request,$symb));
                   11421:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   11422:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   11423:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11424:0):                 $request->print(&csvuploadoptions($request,$symb));
                   11425:0):             } else {
                   11426:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11427:0):                     $env{'form.upfile_associate'} = 'reverse';
                   11428:0):                 } else {
                   11429:0):                     $env{'form.upfile_associate'} = 'forward';
                   11430:0):                 }
                   11431:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11432:0):                 $request->print(&csvuploadmap($request,$symb));
                   11433:0):             }
                   11434:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   11435:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11436:0):             $request->print(&csvuploadassign($request,$symb));
                   11437:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   11438:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11439:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11440:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   11441:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   11442:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11443:0):             $request->print(&scantron_do_warning($request,$symb));
                   11444:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11445:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11446:0):             $request->print(&scantron_validate_file($request,$symb));
                   11447:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11448:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11449:0):             $request->print(&scantron_process_students($request,$symb));
                   11450:0):         } elsif ($command eq 'scantronupload' &&
                   11451:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11452:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11453:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11454:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11455:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11456:0):         } elsif ($command eq 'scantronupload_save' &&
                   11457:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11458:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11459:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11460:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11461:0):         } elsif ($command eq 'scantron_download' &&
                   11462:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11463:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11464:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11465:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11466:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11467:0):             $request->print(&checkscantron_results($request,$symb));
                   11468:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11469:0):             my $js = &part_selector_js();
                   11470:0):             my $onload = "toggleParts('gradingMenu');";
                   11471:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11472:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11473:0):             $request->print(&submit_options_download($request,$symb));
                   11474:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11475:0):             &startpage($request,$symb,
                   11476:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11477:0):     {href=>'', text=>'Download submitted files'}],
                   11478:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11479:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11480:0):             &submit_download_link($request,$symb);
                   11481:0):         } elsif ($command) {
                   11482:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11483:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11484:0):         }
1.2       albertel 11485:     }
1.513     foxr     11486:     if ($ssi_error) {
                   11487: 	&ssi_print_error($request);
                   11488:     }
1.353     albertel 11489:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11490:     &reset_caches();
1.596.2.4  raeburn  11491:     return OK;
1.44      ng       11492: }
                   11493: 
1.1       albertel 11494: 1;
                   11495: 
1.13      albertel 11496: __END__;
1.531     jms      11497: 
                   11498: 
                   11499: =head1 NAME
                   11500: 
                   11501: Apache::grades
                   11502: 
                   11503: =head1 SYNOPSIS
                   11504: 
                   11505: Handles the viewing of grades.
                   11506: 
                   11507: This is part of the LearningOnline Network with CAPA project
                   11508: described at http://www.lon-capa.org.
                   11509: 
                   11510: =head1 OVERVIEW
                   11511: 
                   11512: Do an ssi with retries:
                   11513: While I'd love to factor out this with the vesrion in lonprintout,
                   11514: 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
                   11515: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11516: 
                   11517: At least the logic that drives this has been pulled out into loncommon.
                   11518: 
                   11519: 
                   11520: 
                   11521: ssi_with_retries - Does the server side include of a resource.
                   11522:                      if the ssi call returns an error we'll retry it up to
                   11523:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11524:4):                      If we still have a problem, no text is appended to the
1.531     jms      11525:                      output and we set some global variables.
                   11526:                      to indicate to the caller an SSI error occurred.  
                   11527:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11528:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11529:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11530:                      by informing the user that this happened.
                   11531: 
                   11532: Parameters:
                   11533:   resource   - The resource to include.  This is passed directly, without
                   11534:                interpretation to lonnet::ssi.
                   11535:   form       - The form hash parameters that guide the interpretation of the resource
                   11536:                
                   11537:   retries    - Number of retries allowed before giving up completely.
                   11538: Returns:
                   11539:   On success, returns the rendered resource identified by the resource parameter.
                   11540: Side Effects:
                   11541:   The following global variables can be set:
                   11542:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11543:                               It is up to the caller to initialize this to false
                   11544:                               if desired.
                   11545:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11546:                               of the resource that could not be rendered by the ssi
                   11547:                               call.
                   11548:    ssi_error_message   - The error string fetched from the ssi response
                   11549:                               in the event of an error.
                   11550: 
                   11551: 
                   11552: =head1 HANDLER SUBROUTINE
                   11553: 
                   11554: ssi_with_retries()
                   11555: 
                   11556: =head1 SUBROUTINES
                   11557: 
                   11558: =over
                   11559: 
                   11560: =item scantron_get_correction() : 
                   11561: 
                   11562:    Builds the interface screen to interact with the operator to fix a
                   11563:    specific error condition in a specific scanline
                   11564: 
                   11565:  Arguments:
                   11566:     $r           - Apache request object
                   11567:     $i           - number of the current scanline
                   11568:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11569:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11570:     $line        - full contents of the current scanline
                   11571:     $error       - error condition, valid values are
                   11572:                    'incorrectCODE', 'duplicateCODE',
                   11573:                    'doublebubble', 'missingbubble',
                   11574:                    'duplicateID', 'incorrectID'
                   11575:     $arg         - extra information needed
                   11576:        For errors:
                   11577:          - duplicateID   - paper number that this studentID was seen before on
                   11578:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11579:                            seen on before
                   11580:          - incorrectCODE - current incorrect CODE 
                   11581:          - doublebubble  - array ref of the bubble lines that have double
                   11582:                            bubble errors
                   11583:          - missingbubble - array ref of the bubble lines that have missing
                   11584:                            bubble errors
                   11585: 
1.596.2.12.2.  0(raebur 11586:2):    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   11587:2):    $randompick  - True if exam folder (or a sub-folder) has randompick set
          6(raebur 11588:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11589:3):                      for current line to question number used for same question
                   11590:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11591:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11592:3):                   and value is number of first bubble line for current student
                   11593:3):                   or code-based randompick and/or randomorder.
                   11594:3): 
                   11595:3): 
1.531     jms      11596: =item  scantron_get_maxbubble() : 
                   11597: 
1.582     raeburn  11598:    Arguments:
                   11599:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11600:                       failure to retrieve a navmap object.
                   11601:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11602:        calling routine should trap the error condition and display the warning
                   11603:        found in &navmap_errormsg().
                   11604: 
1.596.2.12.2.  (raeburn 11605:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11606:): 
1.531     jms      11607:    Returns the maximum number of bubble lines that are expected to
                   11608:    occur. Does this by walking the selected sequence rendering the
                   11609:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11610:    for what the current value of the problem counter is.
                   11611: 
                   11612:    Caches the results to $env{'form.scantron_maxbubble'},
                   11613:    $env{'form.scantron.bubble_lines.n'}, 
                   11614:    $env{'form.scantron.first_bubble_line.n'} and
                   11615:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11616:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11617:    lines for response n and number of the first bubble line for response n,
                   11618:    and a comma separated list of numbers of bubble lines for sub-questions
                   11619:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11620: 
                   11621: 
                   11622: =item  scantron_validate_missingbubbles() : 
                   11623: 
                   11624:    Validates all scanlines in the selected file to not have any
                   11625:     answers that don't have bubbles that have not been verified
                   11626:     to be bubble free.
                   11627: 
                   11628: =item  scantron_process_students() : 
                   11629: 
1.596.2.6  raeburn  11630:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11631: 
                   11632:    The parsed scanline hash is added to %env 
                   11633: 
                   11634:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11635:    foreach resource , with the form data of
                   11636: 
                   11637: 	'submitted'     =>'scantron' 
                   11638: 	'grade_target'  =>'grade',
                   11639: 	'grade_username'=> username of student
                   11640: 	'grade_domain'  => domain of student
                   11641: 	'grade_courseid'=> of course
                   11642: 	'grade_symb'    => symb of resource to grade
                   11643: 
                   11644:     This triggers a grading pass. The problem grading code takes care
                   11645:     of converting the bubbled letter information (now in %env) into a
                   11646:     valid submission.
                   11647: 
                   11648: =item  scantron_upload_scantron_data() :
                   11649: 
1.596.2.6  raeburn  11650:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11651: 
                   11652: =item  scantron_upload_scantron_data_save() : 
                   11653: 
                   11654:    Adds a provided bubble information data file to the course if user
                   11655:    has the correct privileges to do so. 
                   11656: 
                   11657: =item  valid_file() :
                   11658: 
                   11659:    Validates that the requested bubble data file exists in the course.
                   11660: 
                   11661: =item  scantron_download_scantron_data() : 
                   11662: 
                   11663:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11664:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11665:    course.
                   11666: 
                   11667: =item  scantron_validate_ID() : 
                   11668: 
                   11669:    Validates all scanlines in the selected file to not have any
1.556     weissno  11670:    invalid or underspecified student/employee IDs
1.531     jms      11671: 
1.582     raeburn  11672: =item navmap_errormsg() :
                   11673: 
                   11674:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11675:    Should be called whenever the request to instantiate a navmap object fails.  
                   11676: 
1.531     jms      11677: =back
                   11678: 
                   11679: =cut

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