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

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.6(ra    4:ug-24): # $Id: grades.pm,v 1.596.2.12.2.60.2.5 2023/09/07 17:38:56 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):             }
1.46      ng       2965: 	}
1.596.2.12.2.  0.2.6(ra 2966:ug-24): #
                   2967:ug-24): # Timestamp is for last transaction for this resource, which does not
                   2968:ug-24): # necessarily correspond to the time of last submission for problem (or part).
                   2969:ug-24): #
                   2970:ug-24):         if ($lasthash{'timestamp'} ne '') {
                   2971:ug-24):             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
                   2972:ug-24):         }
1.596.2.2  raeburn  2973:         my (%typeparts,%randombytry);
1.596     raeburn  2974:         my $showsurv = 
                   2975:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2976:         foreach my $key (sort(keys(%lasthash))) {
                   2977:             if ($key =~ /\.type$/) {
                   2978:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2979:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2980:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2981:                     my ($ign,@parts) = split(/\./,$key);
                   2982:                     pop(@parts);
1.596.2.3  raeburn  2983:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2984:                     if ($lasthash{$key} eq 'randomizetry') {
                   2985:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2986:                     } else {
                   2987:                         unless ($showsurv) {
                   2988:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2989:                         }
1.596     raeburn  2990:                     }
                   2991:                     delete($lasthash{$key});
                   2992:                 }
                   2993:             }
                   2994:         }
                   2995:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2996:         my @randomize = keys(%randombytry);
1.397     albertel 2997: 	foreach my $key (keys(%lasthash)) {
                   2998: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2999:             my $hide;
                   3000:             if (@hidden) {
                   3001:                 foreach my $id (@hidden) {
                   3002:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  3003:                         $hide = 'anon';
1.596     raeburn  3004:                         last;
                   3005:                     }
                   3006:                 }
                   3007:             }
1.596.2.2  raeburn  3008:             unless ($hide) {
                   3009:                 if (@randomize) {
1.596.2.12.2.  3(raebur 3010:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  3011:                         if ($key =~ /^\Q$id\E/) {
                   3012:                             $hide = 'rand';
                   3013:                             last;
                   3014:                         }
                   3015:                     }
                   3016:                 }
                   3017:             }
1.397     albertel 3018: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 3019:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 3020:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 3021:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3022:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3023: 	}
                   3024:     }
1.397     albertel 3025:     if (!@string) {
1.596.2.12.2.  0.2.4(ra 3026:ul-23):         my $msg;
                   3027:ul-23):         if ($is_tool) {
                   3028:ul-23):             $msg = &mt('No grade passed back.');
                   3029:ul-23):         } else {
                   3030:ul-23):             $msg = &mt('Nothing submitted - no attempts.');
                   3031:ul-23):         }
1.397     albertel 3032: 	$string[0] =
1.596.2.12.2.  0.2.4(ra 3033:ul-23): 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3034:     }
1.596.2.12.2.  0.2.2(ra 3035:ar-23):     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3036: }
1.35      ng       3037: 
1.44      ng       3038: #--- High light keywords, with style choosen by user.
1.38      ng       3039: sub keywords_highlight {
1.44      ng       3040:     my $string    = shift;
1.257     albertel 3041:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3042:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3043:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3044:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3045:     foreach my $keyword (@keylist) {
                   3046: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3047:     }
                   3048:     return $string;
1.38      ng       3049: }
1.36      ng       3050: 
1.596.2.12.2.  (raeburn 3051:): # For Tasks provide a mechanism to display previous version for one specific student
                   3052:): 
                   3053:): sub show_previous_task_version {
                   3054:):     my ($request,$symb) = @_;
                   3055:):     if ($symb eq '') {
          8(raebur 3056:4):         $request->print(
                   3057:4):             '<span class="LC_error">'.
                   3058:4):             &mt('Unable to handle ambiguous references.').
                   3059:4):             '</span>');
          (raeburn 3060:):         return '';
                   3061:):     }
                   3062:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3063:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3064:):     if (!&canview($usec)) {
          8(raebur 3065:4):         $request->print('<span class="LC_warning">'.
                   3066:4):                         &mt('Unable to view previous version for requested student.').
                   3067:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 3068:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 3069:4):                         '</span>');
          (raeburn 3070:):         return;
                   3071:):     }
                   3072:):     my $mode = 'both';
                   3073:):     my $isTask = ($symb =~/\.task$/);
                   3074:):     if ($isTask) {
                   3075:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3076:):             if ($env{'form.fullname'} eq '') {
                   3077:):                 $env{'form.fullname'} =
                   3078:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3079:):             }
                   3080:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3081:):             $request->print("\n\n".
                   3082:):                             '<div class="LC_grade_show_user">'.
                   3083:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3084:):                             '</h2>'."\n");
                   3085:):             &Apache::lonxml::clear_problem_counter();
                   3086:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3087:):                             {'previousversion' => $env{'form.previousversion'} }));
                   3088:):             $request->print("\n</div>");
                   3089:):         }
                   3090:):     }
                   3091:):     return;
                   3092:): }
                   3093:): 
                   3094:): sub choose_task_version_form {
                   3095:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   3096:):     my $isTask = ($symb =~/\.task$/);
                   3097:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3098:):     if ($isTask) {
                   3099:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3100:):                                               $udom,$uname);
                   3101:):         if (($record{'resource.0.version'} eq '') ||
                   3102:):             ($record{'resource.0.version'} < 2)) {
                   3103:):             return ($record{'resource.0.version'},
                   3104:):                     $record{'resource.0.version'},$result,$js);
                   3105:):         } else {
                   3106:):             $current = $record{'resource.0.version'};
                   3107:):         }
                   3108:):         if ($env{'form.previousversion'}) {
                   3109:):             $displayed = $env{'form.previousversion'};
                   3110:):             $rowtitle = &mt('Choose another version:')
                   3111:):         } else {
                   3112:):             $displayed = $current;
                   3113:):             $rowtitle = &mt('Show earlier version:');
                   3114:):         }
                   3115:):         $result = '<div class="LC_left_float">';
                   3116:):         my $list;
                   3117:):         my $numversions = 0;
                   3118:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3119:):             if ($i == $current) {
                   3120:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   3121:):                     next;
                   3122:):                 } else {
                   3123:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3124:):                     $numversions ++;
                   3125:):                 }
                   3126:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3127:):                 unless ($i == $env{'form.previousversion'}) {
                   3128:):                     $numversions ++;
                   3129:):                 }
                   3130:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3131:):             }
                   3132:):         }
                   3133:):         if ($numversions) {
                   3134:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3135:):             $result .=
                   3136:):                 '<form name="getprev" method="post" action=""'.
                   3137:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3138:):                 &Apache::loncommon::start_data_table().
                   3139:):                 &Apache::loncommon::start_data_table_row().
                   3140:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3141:):                 '<td><select name="version">'.
                   3142:):                 '<option>'.&mt('Select').'</option>'.
                   3143:):                 $list.
                   3144:):                 '</select></td>'.
                   3145:):                 &Apache::loncommon::end_data_table_row();
                   3146:):             unless ($nomenu) {
                   3147:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3148:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3149:):                 '<td><span class="LC_nobreak">'.
                   3150:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3151:):                 &mt('Yes').'</label>'.
                   3152:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3153:):                 '</span></td>'.
                   3154:):                 &Apache::loncommon::end_data_table_row();
                   3155:):             }
                   3156:):             $result .=
                   3157:):                 &Apache::loncommon::start_data_table_row().
                   3158:):                 '<th align="left">&nbsp;</th>'.
                   3159:):                 '<td>'.
                   3160:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3161:):                 '</td>'.
                   3162:):                 &Apache::loncommon::end_data_table_row().
                   3163:):                 &Apache::loncommon::end_data_table().
                   3164:):                 '</form>';
                   3165:):             $js = &previous_display_javascript($nomenu,$current);
                   3166:):         } elsif ($displayed && $nomenu) {
                   3167:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3168:):         } else {
                   3169:):             $result .= &mt('No previous versions to show for this student');
                   3170:):         }
                   3171:):         $result .= '</div>';
                   3172:):     }
                   3173:):     return ($current,$displayed,$result,$js);
                   3174:): }
                   3175:): 
                   3176:): sub previous_display_javascript {
                   3177:):     my ($nomenu,$current) = @_;
                   3178:):     my $js = <<"JSONE";
                   3179:): <script type="text/javascript">
                   3180:): // <![CDATA[
                   3181:): function previousVersion(uname,udom,symb) {
                   3182:):     var current = '$current';
                   3183:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3184:):     var prevstr = new RegExp("^\\\\d+\$");
                   3185:):     if (!prevstr.test(version)) {
                   3186:):         return false;
                   3187:):     }
                   3188:):     var url = '';
                   3189:):     if (version == current) {
                   3190:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3191:):     } else {
                   3192:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3193:):     }
                   3194:): JSONE
                   3195:):     if ($nomenu) {
                   3196:):         $js .= <<"JSTWO";
                   3197:):     document.location.href = url;
                   3198:): JSTWO
                   3199:):     } else {
                   3200:):         $js .= <<"JSTHREE";
                   3201:):     var newwin = 0;
                   3202:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3203:):         if (document.getprev.prevwin[i].checked == true) {
                   3204:):             newwin = document.getprev.prevwin[i].value;
                   3205:):         }
                   3206:):     }
                   3207:):     if (newwin == 1) {
                   3208:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3209:):         url = url+'&inhibitmenu=yes';
                   3210:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3211:):             previousWin = window.open(url,'',options,1);
                   3212:):         } else {
                   3213:):             previousWin.location.href = url;
                   3214:):         }
                   3215:):         previousWin.focus();
                   3216:):         return false;
                   3217:):     } else {
                   3218:):         document.location.href = url;
                   3219:):         return false;
                   3220:):     }
                   3221:): JSTHREE
                   3222:):     }
                   3223:):     $js .= <<"ENDJS";
                   3224:):     return false;
                   3225:): }
                   3226:): // ]]>
                   3227:): </script>
                   3228:): ENDJS
                   3229:): 
                   3230:): }
                   3231:): 
1.44      ng       3232: #--- Called from submission routine
1.38      ng       3233: sub processHandGrade {
1.596.2.12.2.  1(raebur 3234:0):     my ($request,$symb) = @_;
1.324     albertel 3235:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3236:     my $button = $env{'form.gradeOpt'};
                   3237:     my $ngrade = $env{'form.NCT'};
                   3238:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3239:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3240:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  8(raebur 3241:1):     my ($res_error,%queueable);
                   3242:1):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3243:1):     if ($res_error) {
                   3244:1):         $request->print(&navmap_errormsg());
                   3245:1):         return;
                   3246:1):     } else {
                   3247:1):         foreach my $part (@{$partlist}) {
                   3248:1):             if (ref($responseType->{$part}) eq 'HASH') {
                   3249:1):                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3250:1):                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3251:1):                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3252:1):                         $queueable{$part} = 1;
                   3253:1):                         last;
                   3254:1):                     }
                   3255:1):                 }
                   3256:1):             }
                   3257:1):         }
                   3258:1):     }
1.301     albertel 3259: 
1.44      ng       3260:     if ($button eq 'Save & Next') {
                   3261: 	my $ctr = 0;
                   3262: 	while ($ctr < $ngrade) {
1.257     albertel 3263: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3264:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
          8(raebur 3265:1):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3266: 	    if ($errorflag eq 'no_score') {
                   3267: 		$ctr++;
                   3268: 		next;
                   3269: 	    }
1.104     albertel 3270: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3271:4):                 $request->print(
                   3272:4):                     '<span class="LC_error">'
                   3273:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3274:4):                    .'</span>');
1.104     albertel 3275: 		$ctr++;
                   3276: 		next;
                   3277: 	    }
1.596.2.12.2.  1(raebur 3278:5):             if ($numhidden) {
                   3279:5):                 $request->print(
                   3280:5):                     '<span class="LC_info">'
                   3281:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3282:5):                    .'</span><br />');
                   3283:5):             }
1.257     albertel 3284: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3285: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3286: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3287:             my ($feedurl,$showsymb) =
                   3288: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3289: 	    my $messagetail;
1.62      albertel 3290: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3291: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3292: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3293: 		$subject.=' ['.$restitle.']';
1.44      ng       3294: 		my (@msgnum) = split(/,/,$includemsg);
                   3295: 		foreach (@msgnum) {
1.257     albertel 3296: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3297: 		}
1.80      ng       3298: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3299: 		if ($env{'form.withgrades'.$ctr}) {
                   3300: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3301: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3302:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3303: 		}
                   3304: 		$msgstatus = 
                   3305:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3306: 						     $message.$messagetail,
1.418     albertel 3307:                                                      undef,$feedurl,undef,
1.386     raeburn  3308:                                                      undef,undef,$showsymb,
                   3309:                                                      $restitle);
1.574     bisitz   3310: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3311: 				$msgstatus.'<br />');
1.44      ng       3312: 	    }
1.257     albertel 3313: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3314: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3315: 		foreach my $collabstr (@collabstrs) {
                   3316: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3317: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3318: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3319: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.596.2.12.2.  8(raebur 3320:1): 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3321: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3322: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3323: 			    next;
1.418     albertel 3324: 			} elsif ($message ne '') {
                   3325: 			    my ($baseurl,$showsymb) = 
                   3326: 				&get_feedurl_and_symb($symb,$collaborator,
                   3327: 						      $udom);
                   3328: 			    if ($env{'form.withgrades'.$ctr}) {
                   3329: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3330:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3331: 			    }
1.418     albertel 3332: 			    $msgstatus = 
                   3333: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3334: 			}
1.44      ng       3335: 		    }
                   3336: 		}
                   3337: 	    }
                   3338: 	    $ctr++;
                   3339: 	}
                   3340:     }
                   3341: 
1.596.2.12.2.  1(raebur 3342:0):     my %keyhash = ();
                   3343:0):     if ($numessay) {
1.119     ng       3344: 	# Keywords sorted in alphabatical order
1.257     albertel 3345: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3346: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3347:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3348: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3349: 	$env{'form.keywords'} = join(' ',@keywords);
                   3350: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3351: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3352: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3353: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3354: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3355:0):     }
1.119     ng       3356: 
1.596.2.12.2.  1(raebur 3357:0):     if ($env{'form.compmsg'}) {
1.119     ng       3358: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3359: 	# New messages are saved in env for the next student.
1.119     ng       3360: 	# All messages are saved in nohist_handgrade.db
                   3361: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3362: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3363: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3364: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3365: 		$idx++;
                   3366: 	    }
                   3367: 	    $ctr++;
1.41      ng       3368: 	}
1.119     ng       3369: 	$ctr = 0;
                   3370: 	while ($ctr < $ngrade) {
1.257     albertel 3371: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3372: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3373: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3374: 		$idx++;
                   3375: 	    }
                   3376: 	    $ctr++;
1.41      ng       3377: 	}
1.257     albertel 3378: 	$env{'form.savemsgN'} = --$idx;
                   3379: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3380:0):     }
                   3381:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3382: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3383: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3384:     }
1.596.2.12.2.  1(raebur 3385:0): 
1.44      ng       3386:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3387:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3388:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3389: 	my ($ctr,$total) = (0,0);
                   3390: 	while ($ctr < $ngrade) {
1.257     albertel 3391: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3392: 	    $ctr++;
                   3393: 	}
1.257     albertel 3394: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3395: 	$ctr = 0;
                   3396: 	while ($ctr < $total) {
1.257     albertel 3397: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3398: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3399: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3400:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3401: 	    $ctr++;
                   3402: 	}
                   3403: 	return '';
                   3404:     }
1.36      ng       3405: 
1.44      ng       3406:     # Get the next/previous one or group of students
1.257     albertel 3407:     my $firststu = $env{'form.unamedom0'};
                   3408:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3409:     my $ctr = 2;
1.41      ng       3410:     while ($laststu eq '') {
1.257     albertel 3411: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3412: 	$ctr++;
                   3413: 	$laststu = $firststu if ($ctr > $ngrade);
                   3414:     }
1.44      ng       3415: 
1.41      ng       3416:     my (@parsedlist,@nextlist);
                   3417:     my ($nextflg) = 0;
1.524     raeburn  3418:     foreach my $item (sort 
1.294     albertel 3419: 	     {
                   3420: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3421: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3422: 		 }
                   3423: 		 return $a cmp $b;
                   3424: 	     } (keys(%$fullname))) {
1.41      ng       3425: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3426: 	    push(@parsedlist,$item);
1.41      ng       3427: 	}
1.524     raeburn  3428: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3429: 	if ($button eq 'Previous') {
1.524     raeburn  3430: 	    last if ($item eq $firststu);
                   3431: 	    push(@parsedlist,$item);
1.41      ng       3432: 	}
                   3433:     }
                   3434:     $ctr = 0;
                   3435:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3436:     foreach my $student (@parsedlist) {
1.257     albertel 3437: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3438: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3439: 	
                   3440: 	if ($submitonly eq 'queued') {
                   3441: 	    my %queue_status = 
                   3442: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3443: 							$udom,$uname);
                   3444: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3445: 	}
                   3446: 
1.156     albertel 3447: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3448: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3449: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3450: 	    my $submitted = 0;
1.248     albertel 3451: 	    my $ungraded = 0;
                   3452: 	    my $incorrect = 0;
1.524     raeburn  3453: 	    foreach my $item (keys(%status)) {
                   3454: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3455: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3456: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3457: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3458: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3459: 		    $submitted = 0;
                   3460: 		}
1.41      ng       3461: 	    }
1.156     albertel 3462: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3463: 				     $submitonly eq 'incorrect' ||
                   3464: 				     $submitonly eq 'graded'));
1.248     albertel 3465: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3466: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3467: 	}
1.524     raeburn  3468: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3469: 	last if ($ctr == $ntstu);
1.41      ng       3470: 	$ctr++;
                   3471:     }
1.36      ng       3472: 
1.41      ng       3473:     $ctr = 0;
                   3474:     my $total = scalar(@nextlist)-1;
1.39      ng       3475: 
1.524     raeburn  3476:     foreach (sort(@nextlist)) {
1.41      ng       3477: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3478: 	$env{'form.student'}  = $uname;
                   3479: 	$env{'form.userdom'}  = $udom;
                   3480: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3481:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3482: 	$ctr++;
                   3483:     }
                   3484:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3485:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3486: 	$request->print($the_end);
                   3487:     }
                   3488:     return '';
1.38      ng       3489: }
1.36      ng       3490: 
1.44      ng       3491: #---- Save the score and award for each student, if changed
1.38      ng       3492: sub saveHandGrade {
1.596.2.12.2.  8(raebur 3493:1):     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3494:     my @version_parts;
1.104     albertel 3495:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3496: 					   $env{'request.course.id'});
1.104     albertel 3497:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3498:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3499:     my @parts_graded;
1.77      ng       3500:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3501:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3502:     my %aggregate = ();
                   3503:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3504:5):     if ($env{'form.HIDE'.$newflg}) {
                   3505:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3506:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3507:5):         $totchg += $numchgs;
                   3508:5):     }
1.301     albertel 3509:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3510:     foreach my $new_part (@parts) {
1.337     banghart 3511: 	#collaborator ($submi may vary for different parts
1.259     banghart 3512: 	if ($submitter && $new_part ne $part) { next; }
                   3513: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3514: 	if ($dropMenu eq 'excused') {
1.259     banghart 3515: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3516: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3517: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3518: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3519: 		}
1.364     banghart 3520: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3521: 	    }
1.125     ng       3522: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3523: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3524: 	    foreach my $key (keys(%record)) {
1.259     banghart 3525: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3526: 	    }
1.259     banghart 3527: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3528: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3529:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3530: 
                   3531:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3532: 					       [$new_part]);
                   3533:             my $aggtries =$totaltries;
1.269     raeburn  3534:             if ($last_resets{$new_part}) {
1.270     albertel 3535:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3536: 					   $new_part);
1.269     raeburn  3537:             }
1.270     albertel 3538: 
                   3539:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3540:             if ($aggtries > 0) {
1.327     albertel 3541:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3542:                 $aggregateflag = 1;
                   3543:             }
1.125     ng       3544: 	} elsif ($dropMenu eq '') {
1.259     banghart 3545: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3546: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3547: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3548: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3549: 		next;
                   3550: 	    }
1.259     banghart 3551: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3552: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3553: 	    my $partial= $pts/$wgt;
1.259     banghart 3554: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3555: 		#do not update score for part if not changed.
1.346     banghart 3556:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3557: 		next;
1.251     banghart 3558: 	    } else {
1.524     raeburn  3559: 	        push(@parts_graded,$new_part);
1.153     albertel 3560: 	    }
1.259     banghart 3561: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3562: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3563: 	    }
1.259     banghart 3564: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3565: 	    if ($partial == 0) {
1.153     albertel 3566: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3567: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3568: 		}
1.41      ng       3569: 	    } else {
1.153     albertel 3570: 		if ($record{$reckey} ne 'correct_by_override') {
                   3571: 		    $newrecord{$reckey} = 'correct_by_override';
                   3572: 		}
                   3573: 	    }	    
                   3574: 	    if ($submitter && 
1.259     banghart 3575: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3576: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3577: 	    }
1.259     banghart 3578: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3579: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3580: 	}
1.259     banghart 3581: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3582: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3583: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3584: 	        $dropMenu eq 'reset status')
                   3585: 	   {
1.524     raeburn  3586: 	    push(@version_parts,$new_part);
1.259     banghart 3587: 	}
1.41      ng       3588:     }
1.301     albertel 3589:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3590:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3591: 
1.344     albertel 3592:     if (%newrecord) {
                   3593:         if (@version_parts) {
1.364     banghart 3594:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3595:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3596: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3597: 	    foreach my $new_part (@version_parts) {
                   3598: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3599: 				$new_part,\%newrecord);
                   3600: 	    }
1.259     banghart 3601:         }
1.44      ng       3602: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3603: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3604: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.596.2.12.2.  8(raebur 3605:1): 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3606:     }
1.269     raeburn  3607:     if ($aggregateflag) {
                   3608:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3609: 			      $cdom,$cnum);
1.269     raeburn  3610:     }
1.596.2.12.2.  1(raebur 3611:5):     return ('',$pts,$wgt,$totchg);
                   3612:5): }
                   3613:5): 
                   3614:5): sub makehidden {
                   3615:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3616:5):     return unless (ref($record) eq 'HASH');
                   3617:5):     my %modified;
                   3618:5):     my $numchanged = 0;
                   3619:5):     if (exists($record->{$version.':keys'})) {
                   3620:5):         my $partsregexp = $parts;
                   3621:5):         $partsregexp =~ s/,/|/g;
                   3622:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3623:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3624:5):                  my $item = $1;
                   3625:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3626:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3627:5):                  }
                   3628:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3629:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3630:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3631:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3632:5):             }
                   3633:5):         }
                   3634:5):         if (keys(%modified)) {
                   3635:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3636:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3637:5):                 $numchanged ++;
                   3638:5):             }
                   3639:5):         }
                   3640:5):     }
                   3641:5):     return $numchanged;
1.36      ng       3642: }
1.322     albertel 3643: 
1.380     albertel 3644: sub check_and_remove_from_queue {
1.596.2.12.2.  8(raebur 3645:1):     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3646:     my @ungraded_parts;
                   3647:     foreach my $part (@{$parts}) {
                   3648: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3649: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3650: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3651: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3652: 		) {
1.596.2.12.2.  8(raebur 3653:1):             if ($queueable->{$part}) {
                   3654:1): 	        push(@ungraded_parts, $part);
                   3655:1):             }
1.380     albertel 3656: 	}
                   3657:     }
                   3658:     if ( !@ungraded_parts ) {
                   3659: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3660: 					       $cnum,$domain,$stuname);
                   3661:     }
                   3662: }
                   3663: 
1.337     banghart 3664: sub handback_files {
                   3665:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3666:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3667:     my $res_error;
                   3668:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3669:     if ($res_error) {
                   3670:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3671:         return;
                   3672:     }
1.596.2.4  raeburn  3673:     my @handedback;
                   3674:     my $file_msg;
1.375     albertel 3675:     my @part_response_id = &flatten_responseType($responseType);
                   3676:     foreach my $part_response_id (@part_response_id) {
                   3677:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3678: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3679:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3680:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3681:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3682: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3683:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3684:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3685:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3686:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3687: 		        &file_name_version_ext($answer_file);
1.355     banghart 3688: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3689:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3690:):                     my ($dir_list,$listerror) =
                   3691:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3692:):                                                  $domain,$stuname,$getpropath);
                   3693:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3694:3):                     # fix filename
1.355     banghart 3695:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3696:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3697:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3698:             	                                $save_file_name);
1.337     banghart 3699:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3700:                         $request->print('<br /><span class="LC_error">'.
                   3701:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3702:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3703:                                         '</span>');
1.356     banghart 3704:                     } else {
1.360     banghart 3705:                         # mark the file as read only
1.596.2.4  raeburn  3706:                         push(@handedback,$save_file_name);
1.367     albertel 3707: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3708: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3709: 			}
                   3710:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3711: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3712: 
1.337     banghart 3713:                     }
1.596.2.12.2.  3(raebur 3714: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 3715:                 }
                   3716:             }
                   3717:         }
1.596.2.4  raeburn  3718:     }
                   3719:     if (@handedback > 0) {
                   3720:         $request->print('<br />');
                   3721:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3722:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3723:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3724:         my ($subject,$message);
                   3725:         if (scalar(@handedback) == 1) {
                   3726:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3727:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3728:         } else {
                   3729:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3730:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3731:         }
                   3732:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3733:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3734:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3735:         my ($feedurl,$showsymb) =
                   3736:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3737:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3738:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3739:         my $msgstatus =
                   3740:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3741:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3742:                  $restitle);
                   3743:         if ($msgstatus) {
                   3744:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3745:         }
                   3746:     }
1.338     banghart 3747:     return;
1.337     banghart 3748: }
                   3749: 
1.418     albertel 3750: sub get_feedurl_and_symb {
                   3751:     my ($symb,$uname,$udom) = @_;
                   3752:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3753:     $url = &Apache::lonnet::clutter($url);
                   3754:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3755: 					$symb,$udom,$uname);
                   3756:     if ($encrypturl =~ /^yes$/i) {
                   3757: 	&Apache::lonenc::encrypted(\$url,1);
                   3758: 	&Apache::lonenc::encrypted(\$symb,1);
                   3759:     }
                   3760:     return ($url,$symb);
                   3761: }
                   3762: 
1.313     banghart 3763: sub get_submitted_files {
                   3764:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3765:     my @files;
                   3766:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3767:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3768:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3769:     	    push(@files,$file_url.$file);
                   3770:         }
                   3771:     }
                   3772:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3773:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3774:     }
                   3775:     return (\@files);
                   3776: }
1.322     albertel 3777: 
1.269     raeburn  3778: # ----------- Provides number of tries since last reset.
                   3779: sub get_num_tries {
                   3780:     my ($record,$last_reset,$part) = @_;
                   3781:     my $timestamp = '';
                   3782:     my $num_tries = 0;
                   3783:     if ($$record{'version'}) {
                   3784:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3785:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3786:                 $timestamp = $$record{$version.':timestamp'};
                   3787:                 if ($timestamp > $last_reset) {
                   3788:                     $num_tries ++;
                   3789:                 } else {
                   3790:                     last;
                   3791:                 }
                   3792:             }
                   3793:         }
                   3794:     }
                   3795:     return $num_tries;
                   3796: }
                   3797: 
                   3798: # ----------- Determine decrements required in aggregate totals 
                   3799: sub decrement_aggs {
                   3800:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3801:     my %decrement = (
                   3802:                         attempts => 0,
                   3803:                         users => 0,
                   3804:                         correct => 0
                   3805:                     );
                   3806:     $decrement{'attempts'} = $aggtries;
                   3807:     if ($solvedstatus =~ /^correct/) {
                   3808:         $decrement{'correct'} = 1;
                   3809:     }
                   3810:     if ($aggtries == $totaltries) {
                   3811:         $decrement{'users'} = 1;
                   3812:     }
1.524     raeburn  3813:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3814:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3815:     }
                   3816:     return;
                   3817: }
                   3818: 
                   3819: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3820: sub get_last_resets {
1.270     albertel 3821:     my ($symb,$courseid,$partids) =@_;
                   3822:     my %last_resets;
1.269     raeburn  3823:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3824:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3825:     my @keys;
                   3826:     foreach my $part (@{$partids}) {
                   3827: 	push(@keys,"$symb\0$part\0resettime");
                   3828:     }
                   3829:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3830: 				     $cdom,$cname);
                   3831:     foreach my $part (@{$partids}) {
                   3832: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3833:     }
1.270     albertel 3834:     return %last_resets;
1.269     raeburn  3835: }
                   3836: 
1.251     banghart 3837: # ----------- Handles creating versions for portfolio files as answers
                   3838: sub version_portfiles {
1.343     banghart 3839:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3840:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3841:     my @returned_keys;
1.255     banghart 3842:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3843:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3844:     foreach my $key (keys(%$record)) {
1.259     banghart 3845:         my $new_portfiles;
1.263     banghart 3846:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3847:             my @versioned_portfiles;
1.367     albertel 3848:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3849:             foreach my $file (@portfiles) {
1.306     banghart 3850:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3851:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3852: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3853: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3854:):                 my $getpropath = 1;
                   3855:):                 my ($dir_list,$listerror) =
                   3856:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3857:):                                              $stu_name,$getpropath);
                   3858:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3859:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3860:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3861:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3862:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3863:                         [$directory.$new_answer],
1.306     banghart 3864:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3865:                 }
1.252     banghart 3866:             }
1.343     banghart 3867:             $$record{$key} = join(',',@versioned_portfiles);
                   3868:             push(@returned_keys,$key);
1.251     banghart 3869:         }
1.596.2.12.2.  0.2.6(ra 3870:ug-24):     }
                   3871:ug-24):     return (@returned_keys);
1.305     banghart 3872: }
                   3873: 
1.307     banghart 3874: sub get_next_version {
1.341     banghart 3875:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3876:     my $version;
1.596.2.12.2.  (raeburn 3877:):     if (ref($dir_list) eq 'ARRAY') {
                   3878:):         foreach my $row (@{$dir_list}) {
                   3879:):             my ($file) = split(/\&/,$row,2);
                   3880:):             my ($file_name,$file_version,$file_ext) =
                   3881:): 	        &file_name_version_ext($file);
                   3882:):             if (($file_name eq $answer_name) && 
                   3883:): 	        ($file_ext eq $answer_ext)) {
                   3884:):                 # gets here if filename and extension match, 
                   3885:):                 # regardless of version
1.307     banghart 3886:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3887:):                     # a versioned file is found  so save it for later
                   3888:):                     if ($file_version > $version) {
                   3889:): 		        $version = $file_version;
                   3890:):                     }
1.307     banghart 3891: 	        }
                   3892:             }
                   3893:         }
1.596.2.12.2.  (raeburn 3894:):     }
1.307     banghart 3895:     $version ++;
                   3896:     return($version);
                   3897: }
                   3898: 
1.305     banghart 3899: sub version_selected_portfile {
1.306     banghart 3900:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3901:     my ($answer_name,$answer_ver,$answer_ext) =
                   3902:         &file_name_version_ext($file_name);
                   3903:     my $new_answer;
                   3904:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3905:     if($env{'form.copy'} eq '-1') {
                   3906:         $new_answer = 'problem getting file';
                   3907:     } else {
                   3908:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3909:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3910:                             $stu_name,$domain,'copy',
                   3911: 		        '/portfolio'.$directory.$new_answer);
                   3912:     }    
                   3913:     return ($new_answer);
1.251     banghart 3914: }
                   3915: 
1.304     albertel 3916: sub file_name_version_ext {
                   3917:     my ($file)=@_;
                   3918:     my @file_parts = split(/\./, $file);
                   3919:     my ($name,$version,$ext);
                   3920:     if (@file_parts > 1) {
                   3921: 	$ext=pop(@file_parts);
                   3922: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3923: 	    $version=pop(@file_parts);
                   3924: 	}
                   3925: 	$name=join('.',@file_parts);
                   3926:     } else {
                   3927: 	$name=join('.',@file_parts);
                   3928:     }
                   3929:     return($name,$version,$ext);
                   3930: }
                   3931: 
1.44      ng       3932: #--------------------------------------------------------------------------------------
                   3933: #
                   3934: #-------------------------- Next few routines handles grading by section or whole class
                   3935: #
                   3936: #--- Javascript to handle grading by section or whole class
1.42      ng       3937: sub viewgrades_js {
                   3938:     my ($request) = shift;
                   3939: 
1.539     riegler  3940:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3941:6):     &js_escape(\$alertmsg);
          1(raebur 3942:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3943:    function writePoint(partid,weight,point) {
1.125     ng       3944: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3945: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3946: 	if (point == "textval") {
1.125     ng       3947: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3948: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3949: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3950: 		var resetbox = false;
                   3951: 		for (var i=0; i<radioButton.length; i++) {
                   3952: 		    if (radioButton[i].checked) {
                   3953: 			textbox.value = i;
                   3954: 			resetbox = true;
                   3955: 		    }
                   3956: 		}
                   3957: 		if (!resetbox) {
                   3958: 		    textbox.value = "";
                   3959: 		}
                   3960: 		return;
                   3961: 	    }
1.109     matthew  3962: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3963: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3964: 				   ") greater than the weight for the part. Accept?");
                   3965: 		if (resp == false) {
                   3966: 		    textbox.value = "";
                   3967: 		    return;
                   3968: 		}
                   3969: 	    }
1.42      ng       3970: 	    for (var i=0; i<radioButton.length; i++) {
                   3971: 		radioButton[i].checked=false;
1.109     matthew  3972: 		if (parseFloat(point) == i) {
1.42      ng       3973: 		    radioButton[i].checked=true;
                   3974: 		}
                   3975: 	    }
1.41      ng       3976: 
1.42      ng       3977: 	} else {
1.125     ng       3978: 	    textbox.value = parseFloat(point);
1.42      ng       3979: 	}
1.41      ng       3980: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3981: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3982: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3983: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3984: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3985: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3986: 	    if (saveval != "correct") {
                   3987: 		scorename.value = point;
1.43      ng       3988: 		if (selname[0].selected != true) {
                   3989: 		    selname[0].selected = true;
                   3990: 		}
1.42      ng       3991: 	    }
                   3992: 	}
1.125     ng       3993: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3994:     }
                   3995: 
                   3996:     function writeRadText(partid,weight) {
1.125     ng       3997: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3998: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3999:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       4000: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   4001: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       4002: 	    for (var i=0; i<radioButton.length; i++) {
                   4003: 		radioButton[i].checked=false;
                   4004: 
                   4005: 	    }
                   4006: 	    textbox.value = "";
                   4007: 
                   4008: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4009: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4010: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4011: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4012: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4013: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4014: 		if ((saveval != "correct") || override) {
1.42      ng       4015: 		    scorename.value = "";
1.125     ng       4016: 		    if (selval[1].selected) {
                   4017: 			selname[1].selected = true;
                   4018: 		    } else {
                   4019: 			selname[2].selected = true;
                   4020: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   4021: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4022: 		    }
1.42      ng       4023: 		}
                   4024: 	    }
1.43      ng       4025: 	} else {
                   4026: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4027: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4028: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4029: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4030: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4031: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4032: 		if ((saveval != "correct") || override) {
1.125     ng       4033: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4034: 		    selname[0].selected = true;
                   4035: 		}
                   4036: 	    }
                   4037: 	}	    
1.42      ng       4038:     }
                   4039: 
                   4040:     function changeSelect(partid,user) {
1.125     ng       4041: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4042: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4043: 	var point  = textbox.value;
1.125     ng       4044: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4045: 
1.109     matthew  4046: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4047: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4048: 	    textbox.value = "";
                   4049: 	    return;
                   4050: 	}
1.109     matthew  4051: 	if (parseFloat(point) > parseFloat(weight)) {
                   4052: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4053: 			       ") greater than the weight of the part. Accept?");
                   4054: 	    if (resp == false) {
                   4055: 		textbox.value = "";
                   4056: 		return;
                   4057: 	    }
                   4058: 	}
1.42      ng       4059: 	selval[0].selected = true;
                   4060:     }
                   4061: 
                   4062:     function changeOneScore(partid,user) {
1.125     ng       4063: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4064: 	if (selval[1].selected || selval[2].selected) {
                   4065: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4066: 	    if (selval[2].selected) {
                   4067: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4068: 	    }
1.269     raeburn  4069:         }
1.42      ng       4070:     }
                   4071: 
                   4072:     function resetEntry(numpart) {
                   4073: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4074: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4075: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4076: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4077: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4078: 	    for (var i=0; i<radioButton.length; i++) {
                   4079: 		radioButton[i].checked=false;
                   4080: 
                   4081: 	    }
                   4082: 	    textbox.value = "";
                   4083: 	    selval[0].selected = true;
                   4084: 
                   4085: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4086: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4087: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4088: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4089: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4090: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4091: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4092: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4093: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4094: 		if (saveselval == "excused") {
1.43      ng       4095: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4096: 		} else {
1.43      ng       4097: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4098: 		}
                   4099: 	    }
1.41      ng       4100: 	}
1.42      ng       4101:     }
                   4102: 
1.41      ng       4103: VIEWJAVASCRIPT
1.42      ng       4104: }
                   4105: 
1.44      ng       4106: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4107: sub viewgrades {
1.596.2.12.2.  1(raebur 4108:0):     my ($request,$symb) = @_;
          0.2.4(ra 4109:ul-23):     my ($is_tool,$toolsymb);
                   4110:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4111:ul-23):         $is_tool = 1;
                   4112:ul-23):         $toolsymb = $symb;
                   4113:ul-23):     }
1.42      ng       4114:     &viewgrades_js($request);
1.41      ng       4115: 
1.168     albertel 4116:     #need to make sure we have the correct data for later EXT calls, 
                   4117:     #thus invalidate the cache
                   4118:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4119:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4120:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4121:     &Apache::lonnet::clear_EXT_cache_status();
                   4122: 
1.398     albertel 4123:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4124: 
                   4125:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4126:     $result.=&jscriptNform($symb);
1.41      ng       4127: 
1.44      ng       4128:     #beginning of class grading form
1.442     banghart 4129:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4130:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4131: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4132: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4133: 	&build_section_inputs().
1.442     banghart 4134: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4135: 
1.596.2.12.2.  7(raebur 4136:6):     #retrieve selected groups
                   4137:6):     my (@groups,$group_display);
          8(raebur 4138:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 4139:6):     if (grep(/^all$/,@groups)) {
                   4140:6):         @groups = ('all');
                   4141:6):     } elsif (grep(/^none$/,@groups)) {
                   4142:6):         @groups = ('none');
                   4143:6):     } elsif (@groups > 0) {
                   4144:6):         $group_display = join(', ',@groups);
                   4145:6):     }
                   4146:6): 
                   4147:6):     my ($common_header,$specific_header,@sections,$section_display);
          6(raebur 4148:1):     if ($env{'request.course.sec'} ne '') {
                   4149:1):         @sections = ($env{'request.course.sec'});
                   4150:1):     } else {
                   4151:1):         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4152:1):     }
                   4153:1): 
                   4154:1): # Check if Save button should be usable
                   4155:1):     my $disabled = ' disabled="disabled"';
                   4156:1):     if ($perm{'mgr'}) {
                   4157:1):         if (grep(/^all$/,@sections)) {
                   4158:1):             undef($disabled);
                   4159:1):         } else {
                   4160:1):             foreach my $sec (@sections) {
                   4161:1):                 if (&canmodify($sec)) {
                   4162:1):                     undef($disabled);
                   4163:1):                     last;
                   4164:1):                 }
                   4165:1):             }
                   4166:1):         }
                   4167:1):     }
          7(raebur 4168:6):     if (grep(/^all$/,@sections)) {
                   4169:6):         @sections = ('all');
                   4170:6):         if ($group_display) {
                   4171:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4172:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4173:6):         } elsif (grep(/^none$/,@groups)) {
                   4174:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4175:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4176:6):         } else {
                   4177:6):             $common_header = &mt('Assign Common Grade to Class');
                   4178:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4179:6):         }
                   4180:6):     } elsif (grep(/^none$/,@sections)) {
                   4181:6):         @sections = ('none');
                   4182:6):         if ($group_display) {
                   4183:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4184:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4185:6):         } elsif (grep(/^none$/,@groups)) {
                   4186:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4187:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4188:6):         } else {
                   4189:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4190:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4191:6):         }
                   4192:6):     } else {
                   4193:6):         $section_display = join (", ",@sections);
                   4194:6):         if ($group_display) {
                   4195:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4196:6):                                  $section_display,$group_display);
                   4197:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4198:6):                                    $section_display,$group_display);
                   4199:6):         } elsif (grep(/^none$/,@groups)) {
                   4200:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4201:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4202:6):         } else {
                   4203:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4204:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4205:6):         }
1.52      albertel 4206:     }
1.596.2.12.2.  7(raebur 4207:6):     my %submit_types = &substatus_options();
                   4208:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4209:6): 
                   4210:6):     if ($env{'form.submitonly'} eq 'all') {
                   4211:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4212:6):     } else {
          0.2.4(ra 4213:ul-23):         my $text;
                   4214:ul-23):         if ($is_tool) {
                   4215:ul-23):             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4216:ul-23):         } else {
                   4217:ul-23):             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4218:ul-23):         }
                   4219:ul-23):         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
          7(raebur 4220:6):     }
                   4221:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4222:     #radio buttons/text box for assigning points for a section or class.
                   4223:     #handles different parts of a problem
1.582     raeburn  4224:     my $res_error;
                   4225:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4226:     if ($res_error) {
                   4227:         return &navmap_errormsg();
                   4228:     }
1.42      ng       4229:     my %weight = ();
                   4230:     my $ctsparts = 0;
1.45      ng       4231:     my %seen = ();
1.596.2.12.2.  0.2.4(ra 4232:ul-23):     my @part_response_id;
                   4233:ul-23):     if ($is_tool) {
                   4234:ul-23):         @part_response_id = ([0,'']);
                   4235:ul-23):     } else {
                   4236:ul-23):         @part_response_id = &flatten_responseType($responseType);
                   4237:ul-23):     }
1.375     albertel 4238:     foreach my $part_response_id (@part_response_id) {
                   4239:     	my ($partid,$respid) = @{ $part_response_id };
                   4240: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4241: 	next if $seen{$partid};
                   4242: 	$seen{$partid}++;
1.42      ng       4243: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4244: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4245: 
1.324     albertel 4246: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4247: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4248: 	my $ctr = 0;
1.42      ng       4249: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4250: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4251: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4252: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4253: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4254: 	    $ctr++;
                   4255: 	}
1.485     albertel 4256: 	$radio.='</tr></table>';
                   4257: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4258: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4259: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4260: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4261:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4262:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4263:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4264: 		$weight{$partid}.')"> '.
1.401     albertel 4265: 	    '<option selected="selected"> </option>'.
1.485     albertel 4266: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4267: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4268: 	    '</select></td>'.
                   4269:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4270: 	$line.='<input type="hidden" name="partid_'.
                   4271: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4272: 	$line.='<input type="hidden" name="weight_'.
                   4273: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4274: 
                   4275: 	$result.=
                   4276: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4277: 	    '<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 4278: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4279: 	$ctsparts++;
1.41      ng       4280:     }
1.474     albertel 4281:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4282: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4283:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4284: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4285: 
1.44      ng       4286:     #table listing all the students in a section/class
                   4287:     #header of table
1.596.2.12.2.  0.2.4(ra 4288:ul-23):     if ($env{'form.submitonly'} eq 'all') {
          7(raebur 4289:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4290:6):     } else {
          0.2.4(ra 4291:ul-23):         my $text;
                   4292:ul-23):         if ($is_tool) {
                   4293:ul-23):             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4294:ul-23):         } else {
                   4295:ul-23):             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4296:ul-23):         }
                   4297:ul-23):         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
          7(raebur 4298:6):     }
                   4299:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4300: 	      &Apache::loncommon::start_data_table_header_row().
                   4301: 	      '<th>'.&mt('No.').'</th>'.
                   4302: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4303:     my $partserror;
                   4304:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4305:     if ($partserror) {
                   4306:         return &navmap_errormsg();
                   4307:     }
1.324     albertel 4308:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4309:     my @partids = ();
1.41      ng       4310:     foreach my $part (@parts) {
1.596.2.12.2.  0.2.4(ra 4311:ul-23): 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4312:         my $narrowtext = &mt('Tries');
                   4313: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.596.2.12.2.  0.2.4(ra 4314:ul-23): 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4315: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4316:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4317:0): #
                   4318:0): # FIXME: Looks like $display looks at English text
                   4319:0): #
1.324     albertel 4320: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4321: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4322: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4323:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4324:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4325: 	    next;
1.485     albertel 4326: 	    
1.207     albertel 4327: 	} else {
1.485     albertel 4328: 	    if ($display =~ /Problem Status/) {
                   4329: 		my $grade_status_mt = &mt('Grade Status');
                   4330: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4331: 	    }
                   4332: 	    my $part_mt = &mt('Part:');
                   4333: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4334: 	}
1.485     albertel 4335: 
1.474     albertel 4336: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4337:     }
1.474     albertel 4338:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4339: 
1.270     albertel 4340:     my %last_resets = 
                   4341: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4342: 
1.41      ng       4343:     #get info for each student
1.44      ng       4344:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4345:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4346:     my $ctr = 0;
1.294     albertel 4347:     foreach (sort 
                   4348: 	     {
                   4349: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4350: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4351: 		 }
                   4352: 		 return $a cmp $b;
                   4353: 	     } (keys(%$fullname))) {
1.324     albertel 4354: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  0.2.4(ra 4355:ul-23): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4356:     }
1.474     albertel 4357:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4358:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.596.2.12.2.  6(raebur 4359:1):     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4360: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4361:6):     if ($ctr == 0) {
1.442     banghart 4362:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4363:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4364:6):                 '<span class="LC_warning">';
                   4365:6):         if ($env{'form.submitonly'} eq 'all') {
                   4366:6):             if (grep(/^all$/,@sections)) {
                   4367:6):                 if (grep(/^all$/,@groups)) {
                   4368:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4369:6):                                    $stu_status);
                   4370:6):                 } elsif (grep(/^none$/,@groups)) {
                   4371:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4372:6):                                    $stu_status);
                   4373:6):                 } else {
                   4374:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4375:6):                                    $group_display,$stu_status);
                   4376:6):                 }
                   4377:6):             } elsif (grep(/^none$/,@sections)) {
                   4378:6):                 if (grep(/^all$/,@groups)) {
                   4379:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4380:6):                                    $stu_status);
                   4381:6):                 } elsif (grep(/^none$/,@groups)) {
                   4382:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4383:6):                                    $stu_status);
                   4384:6):                 } else {
                   4385:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4386:6):                                    $group_display,$stu_status);
                   4387:6):                 }
                   4388:6):             } else {
                   4389:6):                 if (grep(/^all$/,@groups)) {
                   4390:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4391:6):                                    $section_display,$stu_status);
                   4392:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4393:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4394:6):                                    $section_display,$stu_status);
                   4395:6):                 } else {
                   4396:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4397:6):                                    $section_display,$group_display,$stu_status);
                   4398:6):                 }
                   4399:6):             }
                   4400:6):         } else {
                   4401:6):             if (grep(/^all$/,@sections)) {
                   4402:6):                 if (grep(/^all$/,@groups)) {
                   4403:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4404:6):                                    $stu_status,$submission_status);
                   4405:6):                 } elsif (grep(/^none$/,@groups)) {
                   4406:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4407:6):                                    $stu_status,$submission_status);
                   4408:6):                 } else {
                   4409:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4410:6):                                    $group_display,$stu_status,$submission_status);
                   4411:6):                 }
                   4412:6):             } elsif (grep(/^none$/,@sections)) {
                   4413:6):                 if (grep(/^all$/,@groups)) {
                   4414:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4415:6):                                    $stu_status,$submission_status);
                   4416:6):                 } elsif (grep(/^none$/,@groups)) {
                   4417: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.',
                   4418:6):                                    $stu_status,$submission_status);
                   4419:6):                 } else {
                   4420: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.',
                   4421:6):                                    $group_display,$stu_status,$submission_status);
                   4422:6):                 }
                   4423:6):             } else {
                   4424:6):                 if (grep(/^all$/,@groups)) {
                   4425:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4426:6):                                    $section_display,$stu_status,$submission_status);
                   4427:6):                 } elsif (grep(/^none$/,@groups)) {
                   4428: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.',
                   4429:6):                                    $section_display,$stu_status,$submission_status);
                   4430:6):                 } else {
                   4431: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.',
                   4432:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4433:6):                 }
                   4434:6):             }
                   4435:6): 	}
                   4436:6): 	$result .= '</span><br />';
1.96      albertel 4437:     }
1.41      ng       4438:     return $result;
                   4439: }
                   4440: 
1.596.2.12.2.  7(raebur 4441:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4442: sub viewstudentgrade {
1.596.2.12.2.  0.2.4(ra 4443:ul-23):     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4444:     my ($uname,$udom) = split(/:/,$student);
                   4445:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4446:6):     my $submitonly = $env{'form.submitonly'};
                   4447:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4448:6):         my %partstatus = ();
                   4449:6):         if (ref($parts) eq 'ARRAY') {
                   4450:6):             foreach my $apart (@{$parts}) {
                   4451:6):                 my ($part,$type) = &split_part_type($apart);
                   4452:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4453:6):                 $status = 'nothing' if ($status eq '');
                   4454:6):                 $partstatus{$part}      = $status;
                   4455:6):                 my $subkey = "resource.$part.submitted_by";
                   4456:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4457:6):             }
                   4458:6):             my $submitted = 0;
                   4459:6):             my $graded = 0;
                   4460:6):             my $incorrect = 0;
                   4461:6):             foreach my $key (keys(%partstatus)) {
                   4462:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4463:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4464:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4465:6): 
                   4466:6):                 my $partid = (split(/\./,$key))[1];
                   4467:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4468:6):                     $submitted = 0;
                   4469:6):                 }
                   4470:6):             }
                   4471:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4472:6):                                        $submitonly eq 'incorrect' ||
                   4473:6):                                        $submitonly eq 'graded'));
                   4474:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4475:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4476:6):         }
                   4477:6):     }
                   4478:6):     if ($submitonly eq 'queued') {
                   4479:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4480:6):         my %queue_status =
                   4481:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4482:6):                                                     $udom,$uname);
                   4483:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4484:6):     }
                   4485:6):     $$ctr++;
                   4486:6):     my %aggregates = ();
1.474     albertel 4487:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4488:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4489:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4490: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4491: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4492: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4493:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4494:     foreach my $apart (@$parts) {
                   4495: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4496: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4497:         $result.='<td align="center">';
1.269     raeburn  4498:         my ($aggtries,$totaltries);
                   4499:         unless (exists($aggregates{$part})) {
1.270     albertel 4500: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4501: 	    $aggtries = $totaltries;
1.269     raeburn  4502:             if ($$last_resets{$part}) {  
1.270     albertel 4503:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4504: 					   $part);
                   4505:             }
1.269     raeburn  4506:             $result.='<input type="hidden" name="'.
                   4507:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4508:             $result.='<input type="hidden" name="'.
                   4509:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4510:             $aggregates{$part} = 1;
                   4511:         }
1.41      ng       4512: 	if ($type eq 'awarded') {
1.320     albertel 4513: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4514: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4515: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4516: 	    $result.='<input type="text" name="'.
1.89      albertel 4517: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4518:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4519: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4520: 	} elsif ($type eq 'solved') {
                   4521: 	    my ($status,$foo)=split(/_/,$score,2);
                   4522: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4523: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4524: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4525: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4526: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4527:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4528: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4529: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4530: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4531: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4532: 	} else {
                   4533: 	    $result.='<input type="hidden" name="'.
                   4534: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4535: 		    "\n";
1.233     albertel 4536: 	    $result.='<input type="text" name="'.
1.122     ng       4537: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4538: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4539: 	}
                   4540:     }
1.474     albertel 4541:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4542:     return $result;
1.38      ng       4543: }
                   4544: 
1.44      ng       4545: #--- change scores for all the students in a section/class
                   4546: #    record does not get update if unchanged
1.38      ng       4547: sub editgrades {
1.596.2.12.2.  1(raebur 4548:0):     my ($request,$symb) = @_;
          0.2.4(ra 4549:ul-23):     my $toolsymb;
                   4550:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4551:ul-23):         $toolsymb = $symb;
                   4552:ul-23):     }
1.41      ng       4553: 
1.433     banghart 4554:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4555:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4556:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4557: 
1.477     albertel 4558:     my $result= &Apache::loncommon::start_data_table().
                   4559: 	&Apache::loncommon::start_data_table_header_row().
                   4560: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4561: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4562:     my %scoreptr = (
                   4563: 		    'correct'  =>'correct_by_override',
                   4564: 		    'incorrect'=>'incorrect_by_override',
                   4565: 		    'excused'  =>'excused',
                   4566: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4567:                     'credited' =>'credit_attempted',
1.43      ng       4568: 		    'nothing'  => '',
                   4569: 		    );
1.257     albertel 4570:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4571: 
1.44      ng       4572:     my (@partid);
                   4573:     my %weight = ();
1.54      albertel 4574:     my %columns = ();
1.44      ng       4575:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4576: 
1.582     raeburn  4577:     my $partserror;
                   4578:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4579:     if ($partserror) {
                   4580:         return &navmap_errormsg();
                   4581:     }
1.54      albertel 4582:     my $header;
1.257     albertel 4583:     while ($ctr < $env{'form.totalparts'}) {
                   4584: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4585: 	push(@partid,$partid);
1.257     albertel 4586: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4587: 	$ctr++;
1.54      albertel 4588:     }
1.324     albertel 4589:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4590:8):     my $totcolspan = 0;
1.54      albertel 4591:     foreach my $partid (@partid) {
1.478     albertel 4592: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4593: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4594: 	$columns{$partid}=2;
                   4595: 	foreach my $stores (@parts) {
                   4596: 	    my ($part,$type) = &split_part_type($stores);
                   4597: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4598: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.596.2.12.2.  0.2.4(ra 4599:ul-23): 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4600: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4601:             my $narrowtext = &mt('Tries');
                   4602: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4603: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4604: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4605: 	    $columns{$partid}+=2;
                   4606: 	}
1.596.2.12.2.  2(raebur 4607:8):         $totcolspan += $columns{$partid};
1.54      albertel 4608:     }
                   4609:     foreach my $partid (@partid) {
1.324     albertel 4610: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4611: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4612: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4613: 	    '</th>';
1.54      albertel 4614: 
1.44      ng       4615:     }
1.477     albertel 4616:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4617: 	&Apache::loncommon::start_data_table_header_row().
                   4618: 	$header.
                   4619: 	&Apache::loncommon::end_data_table_header_row();
                   4620:     my @noupdate;
1.126     ng       4621:     my ($updateCtr,$noupdateCtr) = (1,1);
1.596.2.12.2.  8(raebur 4622:1):     my ($got_types,%queueable);
1.257     albertel 4623:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4624: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4625: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4626: 	my %newrecord;
                   4627: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4628:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4629:8):         my $canmodify = &canmodify($usec);
                   4630:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4631:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4632:8):         if (!$canmodify) {
                   4633:8):             push(@noupdate,
                   4634:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4635:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4636:8):             next;
                   4637:8):         }
1.269     raeburn  4638:         my %aggregate = ();
                   4639:         my $aggregateflag = 0;
1.281     albertel 4640: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4641: 	foreach (@partid) {
1.257     albertel 4642: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4643: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4644: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4645: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4646: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4647: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4648: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4649: 	    my $score;
                   4650: 	    if ($partial eq '') {
1.257     albertel 4651: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4652: 	    } elsif ($partial > 0) {
                   4653: 		$score = 'correct_by_override';
                   4654: 	    } elsif ($partial == 0) {
                   4655: 		$score = 'incorrect_by_override';
                   4656: 	    }
1.257     albertel 4657: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4658: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4659: 
1.292     albertel 4660: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4661: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4662: 	    if ($dropMenu eq 'reset status' &&
                   4663: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4664: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4665: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4666: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4667: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4668: 		$updateflag = 1;
1.269     raeburn  4669:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4670:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4671:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4672:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4673:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4674:                     $aggregateflag = 1;
                   4675:                 }
1.139     albertel 4676: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4677: 		$updateflag = 1;
                   4678: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4679: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4680: 		$rec_update++;
1.125     ng       4681: 	    }
                   4682: 
1.93      albertel 4683: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4684: 		'<td align="center">'.$awarded.
                   4685: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4686: 
1.54      albertel 4687: 
                   4688: 	    my $partid=$_;
                   4689: 	    foreach my $stores (@parts) {
                   4690: 		my ($part,$type) = &split_part_type($stores);
                   4691: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4692: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4693: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4694: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4695: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4696: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4697: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4698: 		    $updateflag=1;
                   4699: 		}
1.93      albertel 4700: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4701: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4702: 	    }
1.44      ng       4703: 	}
1.477     albertel 4704: 	$line.="\n";
1.301     albertel 4705: 
                   4706: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4707: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4708: 
1.44      ng       4709: 	if ($updateflag) {
                   4710: 	    $count++;
1.257     albertel 4711: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4712: 				    $udom,$uname);
1.301     albertel 4713: 
                   4714: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4715: 					      $cnum,$udom,$uname)) {
                   4716: 		# need to figure out if should be in queue.
                   4717: 		my %record =  
                   4718: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4719: 					     $udom,$uname);
                   4720: 		my $all_graded = 1;
                   4721: 		my $none_graded = 1;
1.596.2.12.2.  8(raebur 4722:1):                 unless ($got_types) {
                   4723:1):                     my $error;
                   4724:1):                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4725:1):                     unless ($error) {
                   4726:1):                         foreach my $part (@parts) {
                   4727:1):                             if (ref($resptype->{$part}) eq 'HASH') {
                   4728:1):                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4729:1):                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4730:1):                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4731:1):                                         $queueable{$part} = 1;
                   4732:1):                                         last;
                   4733:1):                                     }
                   4734:1):                                 }
                   4735:1):                             }
                   4736:1):                         }
                   4737:1):                     }
                   4738:1):                     $got_types = 1;
                   4739:1):                 }
1.301     albertel 4740: 		foreach my $part (@parts) {
1.596.2.12.2.  8(raebur 4741:1):                     if ($queueable{$part}) {
                   4742:1): 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4743:1): 			    $all_graded = 0;
                   4744:1): 		        } else {
                   4745:1): 			    $none_graded = 0;
                   4746:1): 		        }
                   4747:1):                     }
1.301     albertel 4748: 		}
                   4749: 
                   4750: 		if ($all_graded || $none_graded) {
                   4751: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4752: 							   $symb,$cdom,$cnum,
                   4753: 							   $udom,$uname);
                   4754: 		}
                   4755: 	    }
                   4756: 
1.477     albertel 4757: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4758: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4759: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4760: 	    $updateCtr++;
1.93      albertel 4761: 	} else {
1.477     albertel 4762: 	    push(@noupdate,
                   4763: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4764: 	    $noupdateCtr++;
1.44      ng       4765: 	}
1.269     raeburn  4766:         if ($aggregateflag) {
                   4767:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4768: 				  $cdom,$cnum);
1.269     raeburn  4769:         }
1.93      albertel 4770:     }
1.477     albertel 4771:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4772:8):         my $numcols=$totcolspan+2;
1.477     albertel 4773: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4774: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4775: 	    &mt('No Changes Occurred For the Students Below').
                   4776: 	    '</td>'.
1.477     albertel 4777: 	    &Apache::loncommon::end_data_table_row();
                   4778: 	foreach my $line (@noupdate) {
                   4779: 	    $result.=
                   4780: 		&Apache::loncommon::start_data_table_row().
                   4781: 		$line.
                   4782: 		&Apache::loncommon::end_data_table_row();
                   4783: 	}
1.44      ng       4784:     }
1.596.2.12.2.  1(raebur 4785:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4786:     my $msg = '<p><b>'.
                   4787: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4788: 	    $rec_update,$count).'</b><br />'.
                   4789: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4790: 	'</b></p>';
1.44      ng       4791:     return $title.$msg.$result;
1.5       albertel 4792: }
1.54      albertel 4793: 
                   4794: sub split_part_type {
                   4795:     my ($partstr) = @_;
                   4796:     my ($temp,@allparts)=split(/_/,$partstr);
                   4797:     my $type=pop(@allparts);
1.439     albertel 4798:     my $part=join('_',@allparts);
1.54      albertel 4799:     return ($part,$type);
                   4800: }
                   4801: 
1.44      ng       4802: #------------- end of section for handling grading by section/class ---------
                   4803: #
                   4804: #----------------------------------------------------------------------------
                   4805: 
1.5       albertel 4806: 
1.44      ng       4807: #----------------------------------------------------------------------------
                   4808: #
                   4809: #-------------------------- Next few routines handles grading by csv upload
                   4810: #
                   4811: #--- Javascript to handle csv upload
1.27      albertel 4812: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4813:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4814:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4815:6):   &js_escape(\$error1);
                   4816:6):   &js_escape(\$error2);
1.27      albertel 4817:   return(<<ENDPICK);
                   4818:   function verify(vf) {
                   4819:     var foundsomething=0;
                   4820:     var founduname=0;
1.243     albertel 4821:     var foundID=0;
1.27      albertel 4822:     for (i=0;i<=vf.nfields.value;i++) {
                   4823:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4824:       if (i==0 && tw!=0) { foundID=1; }
                   4825:       if (i==1 && tw!=0) { founduname=1; }
                   4826:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4827:     }
1.246     albertel 4828:     if (founduname==0 && foundID==0) {
                   4829: 	alert('$error1');
                   4830: 	return;
1.27      albertel 4831:     }
                   4832:     if (foundsomething==0) {
1.246     albertel 4833: 	alert('$error2');
                   4834: 	return;
1.27      albertel 4835:     }
                   4836:     vf.submit();
                   4837:   }
                   4838:   function flip(vf,tf) {
                   4839:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4840:     var i;
                   4841:     for (i=0;i<=vf.nfields.value;i++) {
                   4842:       //can not pick the same destination field for both name and domain
                   4843:       if (((i ==0)||(i ==1)) && 
                   4844:           ((tf==0)||(tf==1)) && 
                   4845:           (i!=tf) &&
                   4846:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4847:         eval('vf.f'+i+'.selectedIndex=0;')
                   4848:       }
                   4849:     }
                   4850:   }
                   4851: ENDPICK
                   4852: }
                   4853: 
                   4854: sub csvupload_javascript_forward_associate {
1.573     bisitz   4855:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4856:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4857:6):   &js_escape(\$error1);
                   4858:6):   &js_escape(\$error2);
1.27      albertel 4859:   return(<<ENDPICK);
                   4860:   function verify(vf) {
                   4861:     var foundsomething=0;
                   4862:     var founduname=0;
1.243     albertel 4863:     var foundID=0;
1.27      albertel 4864:     for (i=0;i<=vf.nfields.value;i++) {
                   4865:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4866:       if (tw==1) { foundID=1; }
                   4867:       if (tw==2) { founduname=1; }
                   4868:       if (tw>3) { foundsomething=1; }
1.27      albertel 4869:     }
1.246     albertel 4870:     if (founduname==0 && foundID==0) {
                   4871: 	alert('$error1');
                   4872: 	return;
1.27      albertel 4873:     }
                   4874:     if (foundsomething==0) {
1.246     albertel 4875: 	alert('$error2');
                   4876: 	return;
1.27      albertel 4877:     }
                   4878:     vf.submit();
                   4879:   }
                   4880:   function flip(vf,tf) {
                   4881:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4882:     var i;
                   4883:     //can not pick the same destination field twice
                   4884:     for (i=0;i<=vf.nfields.value;i++) {
                   4885:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4886:         eval('vf.f'+i+'.selectedIndex=0;')
                   4887:       }
                   4888:     }
                   4889:   }
                   4890: ENDPICK
                   4891: }
                   4892: 
1.26      albertel 4893: sub csvuploadmap_header {
1.324     albertel 4894:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4895:     my $javascript;
1.257     albertel 4896:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4897: 	$javascript=&csvupload_javascript_reverse_associate();
                   4898:     } else {
                   4899: 	$javascript=&csvupload_javascript_forward_associate();
                   4900:     }
1.45      ng       4901: 
1.257     albertel 4902:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4903:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4904:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4905:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4906:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4907:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4908:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4909:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4910:0): <br />
                   4911:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4912: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4913: <input type="hidden" name="associate"  value="" />
                   4914: <input type="hidden" name="phase"      value="three" />
                   4915: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4916: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4917: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4918: <input type="hidden" name="upfile_associate" 
1.257     albertel 4919:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4920: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4921: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4922: <hr />
                   4923: ENDPICK
1.596.2.12.2.  1(raebur 4924:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4925:     return '';
1.26      albertel 4926: 
                   4927: }
                   4928: 
                   4929: sub csvupload_fields {
1.582     raeburn  4930:     my ($symb,$errorref) = @_;
1.596.2.12.2.  0.2.4(ra 4931:ul-23):     my $toolsymb;
                   4932:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4933:ul-23):         $toolsymb = $symb;
                   4934:ul-23):     }
1.582     raeburn  4935:     my (@parts) = &getpartlist($symb,$errorref);
                   4936:     if (ref($errorref)) {
                   4937:         if ($$errorref) {
                   4938:             return;
                   4939:         }
                   4940:     }
                   4941: 
1.556     weissno  4942:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4943: 		['username','Student Username'],
                   4944: 		['domain','Student Domain']);
1.324     albertel 4945:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4946:     foreach my $part (sort(@parts)) {
                   4947: 	my @datum;
1.596.2.12.2.  0.2.4(ra 4948:ul-23): 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4949: 	my $name=$part;
                   4950: 	if  (!$display) { $display = $name; }
                   4951: 	@datum=($name,$display);
1.244     albertel 4952: 	if ($name=~/^stores_(.*)_awarded/) {
                   4953: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4954: 	}
1.41      ng       4955: 	push(@fields,\@datum);
                   4956:     }
                   4957:     return (@fields);
1.26      albertel 4958: }
                   4959: 
                   4960: sub csvuploadmap_footer {
1.41      ng       4961:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4962:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4963:     $request->print(<<ENDPICK);
1.26      albertel 4964: </table>
                   4965: <input type="hidden" name="nfields" value="$i" />
                   4966: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4967:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4968: </form>
                   4969: ENDPICK
                   4970: }
                   4971: 
1.283     albertel 4972: sub checkforfile_js {
1.539     riegler  4973:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4974:6):     &js_escape(\$alertmsg);
          1(raebur 4975:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4976:     function checkUpload(formname) {
                   4977: 	if (formname.upfile.value == "") {
1.539     riegler  4978: 	    alert("$alertmsg");
1.86      ng       4979: 	    return false;
                   4980: 	}
                   4981: 	formname.submit();
                   4982:     }
                   4983: CSVFORMJS
1.283     albertel 4984:     return $result;
                   4985: }
                   4986: 
                   4987: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4988:0):     my ($request,$symb) = @_;
1.283     albertel 4989:     if (!$symb) {return '';}
                   4990:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4991:0):     $result.=&Apache::loncommon::start_data_table().
                   4992:0):              &Apache::loncommon::start_data_table_header_row().
                   4993:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4994:0):              &Apache::loncommon::end_data_table_header_row().
                   4995:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4996:     my $upload=&mt("Upload Scores");
1.86      ng       4997:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4998:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4999:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       5000:     $result.=<<ENDUPFORM;
1.106     albertel 5001: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       5002: <input type="hidden" name="symb" value="$symb" />
                   5003: <input type="hidden" name="command" value="csvuploadmap" />
                   5004: $upfile_select
1.589     bisitz   5005: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 5006: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       5007: </form>
                   5008: ENDUPFORM
1.370     www      5009:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 5010:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   5011:0):             '</td>'.
                   5012:0):             &Apache::loncommon::end_data_table_row().
                   5013:0):             &Apache::loncommon::end_data_table();
1.86      ng       5014:     return $result;
                   5015: }
                   5016: 
                   5017: 
1.26      albertel 5018: sub csvuploadmap {
1.596.2.12.2.  1(raebur 5019:0):     my ($request,$symb) = @_;
1.41      ng       5020:     if (!$symb) {return '';}
1.72      ng       5021: 
1.41      ng       5022:     my $datatoken;
1.257     albertel 5023:     if (!$env{'form.datatoken'}) {
1.41      ng       5024: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5025:     } else {
1.596.2.12.2.  3(raebur 5026:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5027:8):         if ($datatoken ne '') { 
                   5028:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5029:8):         }
1.26      albertel 5030:     }
1.41      ng       5031:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 5032:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 5033:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5034:     my ($i,$keyfields);
                   5035:     if (@records) {
1.582     raeburn  5036:         my $fieldserror;
                   5037: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5038:         if ($fieldserror) {
                   5039:             $request->print(&navmap_errormsg());
                   5040:             return;
                   5041:         }
1.257     albertel 5042: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5043: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5044: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5045: 							  \@fields);
                   5046: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5047: 	    chop($keyfields);
                   5048: 	} else {
                   5049: 	    unshift(@fields,['none','']);
                   5050: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5051: 							    \@fields);
1.311     banghart 5052:             foreach my $rec (@records) {
                   5053:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5054:                 if (%temp) {
                   5055:                     $keyfields=join(',',sort(keys(%temp)));
                   5056:                     last;
                   5057:                 }
                   5058:             }
1.41      ng       5059: 	}
                   5060:     }
                   5061:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5062: 
1.41      ng       5063:     return '';
1.27      albertel 5064: }
                   5065: 
1.246     albertel 5066: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 5067:0):     my ($request,$symb)= @_;
                   5068:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 5069:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 5070:     my $ignore=&mt('Ignore First Line');
                   5071:     $request->print(<<ENDPICK);
                   5072: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   5073: <input type="hidden" name="command"    value="csvuploadassign" />
                   5074: <p>
                   5075: <label>
                   5076:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 5077:0):    $overwrite
1.246     albertel 5078: </label>
                   5079: </p>
                   5080: ENDPICK
                   5081:     my %fields=&get_fields();
                   5082:     if (!defined($fields{'domain'})) {
1.257     albertel 5083: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 5084:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5085:     }
1.257     albertel 5086:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5087: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5088: 	my $cleankey=$1;
                   5089: 	if ($cleankey eq 'command') { next; }
                   5090: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5091: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5092:     }
                   5093:     # FIXME do a check for any duplicated user ids...
                   5094:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 5095:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5096: <hr /></form>'."\n");
1.246     albertel 5097:     return '';
                   5098: }
                   5099: 
                   5100: sub get_fields {
                   5101:     my %fields;
1.257     albertel 5102:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5103:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5104: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5105: 	    if ($env{'form.f'.$i} ne 'none') {
                   5106: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5107: 	    }
                   5108: 	} else {
1.257     albertel 5109: 	    if ($env{'form.f'.$i} ne 'none') {
                   5110: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       5111: 	    }
                   5112: 	}
1.27      albertel 5113:     }
1.246     albertel 5114:     return %fields;
                   5115: }
                   5116: 
                   5117: sub csvuploadassign {
1.596.2.12.2.  1(raebur 5118:0):     my ($request,$symb) = @_;
1.246     albertel 5119:     if (!$symb) {return '';}
1.345     bowersj2 5120:     my $error_msg = '';
1.596.2.12.2.  3(raebur 5121:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5122:8):     if ($datatoken ne '') {
                   5123:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5124:8):     }
1.246     albertel 5125:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 5126:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 5127:     my %fields=&get_fields();
1.257     albertel 5128:     my $courseid=$env{'request.course.id'};
1.97      albertel 5129:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 5130:     my @notallowed;
1.41      ng       5131:     my @skipped;
1.596.2.4  raeburn  5132:     my @warnings;
1.41      ng       5133:     my $countdone=0;
                   5134:     foreach my $grade (@gradedata) {
                   5135: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5136: 	my $domain;
                   5137: 	if ($entries{$fields{'domain'}}) {
                   5138: 	    $domain=$entries{$fields{'domain'}};
                   5139: 	} else {
1.257     albertel 5140: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5141: 	}
1.243     albertel 5142: 	$domain=~s/\s//g;
1.41      ng       5143: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5144: 	$username=~s/\s//g;
1.243     albertel 5145: 	if (!$username) {
                   5146: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5147: 	    $id=~s/\s//g;
1.243     albertel 5148: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   5149: 	    $username=$ids{$id};
                   5150: 	}
1.41      ng       5151: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5152: 	    my $id=$entries{$fields{'ID'}};
                   5153: 	    $id=~s/\s//g;
                   5154: 	    if ($id) {
                   5155: 		push(@skipped,"$id:$domain");
                   5156: 	    } else {
                   5157: 		push(@skipped,"$username:$domain");
                   5158: 	    }
1.41      ng       5159: 	    next;
                   5160: 	}
1.108     albertel 5161: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5162: 	if (!&canmodify($usec)) {
                   5163: 	    push(@notallowed,"$username:$domain");
                   5164: 	    next;
                   5165: 	}
1.244     albertel 5166: 	my %points;
1.41      ng       5167: 	my %grades;
                   5168: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5169: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5170: 		$dest eq 'domain') { next; }
                   5171: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5172: 	    if ($dest=~/stores_(.*)_points/) {
                   5173: 		my $part=$1;
                   5174: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5175: 					      $symb,$domain,$username);
1.345     bowersj2 5176:                 if ($wgt) {
                   5177:                     $entries{$fields{$dest}}=~s/\s//g;
                   5178:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5179:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5180:                                           : 'correct_by_override';
1.596.2.4  raeburn  5181:                     if ($pcr>1) {
                   5182:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   5183:                     }
1.345     bowersj2 5184:                     $grades{"resource.$part.awarded"}=$pcr;
                   5185:                     $grades{"resource.$part.solved"}=$award;
                   5186:                     $points{$part}=1;
                   5187:                 } else {
                   5188:                     $error_msg = "<br />" .
                   5189:                         &mt("Some point values were assigned"
                   5190:                             ." for problems with a weight "
                   5191:                             ."of zero. These values were "
                   5192:                             ."ignored.");
                   5193:                 }
1.244     albertel 5194: 	    } else {
                   5195: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5196: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5197: 		my $store_key=$dest;
                   5198: 		$store_key=~s/^stores/resource/;
                   5199: 		$store_key=~s/_/\./g;
                   5200: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5201: 	    }
1.41      ng       5202: 	}
1.596.2.12.2.  1(raebur 5203:0): 	if (! %grades) {
1.508     www      5204:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5205:         } else {
                   5206: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5207: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5208: 					   $env{'request.course.id'},
                   5209: 					   $domain,$username);
1.508     www      5210: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 5211:0): # Successfully stored
1.508     www      5212: 	      $request->print('.');
1.596.2.4  raeburn  5213: # Remove from grading queue
                   5214:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5215:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5216:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5217:                                              $domain,$username);
1.508     www      5218: 	   } else {
                   5219: 	      $request->print("<p><span class=\"LC_error\">".
                   5220:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5221:                                   "$username:$domain",$result)."</span></p>");
                   5222: 	   }
                   5223: 	   $request->rflush();
                   5224: 	   $countdone++;
                   5225:         }
1.41      ng       5226:     }
1.570     www      5227:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5228:     if (@warnings) {
                   5229:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5230:         $request->print(join(', ',@warnings));
                   5231:     }
1.41      ng       5232:     if (@skipped) {
1.571     www      5233: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5234:         $request->print(join(', ',@skipped));
1.106     albertel 5235:     }
                   5236:     if (@notallowed) {
1.571     www      5237: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5238: 	$request->print(join(', ',@notallowed));
1.41      ng       5239:     }
1.106     albertel 5240:     $request->print("<br />\n");
1.345     bowersj2 5241:     return $error_msg;
1.26      albertel 5242: }
1.44      ng       5243: #------------- end of section for handling csv file upload ---------
                   5244: #
                   5245: #-------------------------------------------------------------------
                   5246: #
1.122     ng       5247: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5248: #
                   5249: #--- Select a page/sequence and a student to grade
1.68      ng       5250: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5251:0):     my ($request,$symb) = @_;
1.68      ng       5252: 
1.539     riegler  5253:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5254:6):     &js_escape(\$alertmsg);
          1(raebur 5255:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5256: 
                   5257: function checkPickOne(formname) {
1.76      ng       5258:     if (radioSelection(formname.student) == null) {
1.539     riegler  5259: 	alert("$alertmsg");
1.68      ng       5260: 	return;
                   5261:     }
1.125     ng       5262:     ptr = pullDownSelection(formname.selectpage);
                   5263:     formname.page.value = formname["page"+ptr].value;
                   5264:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5265:     formname.submit();
                   5266: }
                   5267: 
                   5268: LISTJAVASCRIPT
1.118     ng       5269:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5270:0): 
1.257     albertel 5271:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5272:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5273:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5274:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5275: 
1.398     albertel 5276:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5277: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5278: 
1.80      ng       5279:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5280:     my $map_error;
                   5281:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5282:     if ($map_error) {
                   5283:         $request->print(&navmap_errormsg());
                   5284:         return; 
                   5285:     }
1.137     albertel 5286:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5287: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5288: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5289: 
1.596.2.12.2.  1(raebur 5290:0):     # Collection of hidden fields
                   5291:0):     my $ctr=0;
1.70      ng       5292:     foreach (@$titles) {
                   5293: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5294: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5295: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5296: 	$ctr++;
                   5297:     }
1.72      ng       5298:     $result.='<input type="hidden" name="page" />'."\n".
                   5299: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5300: 
1.432     banghart 5301:     $result.=&build_section_inputs();
1.442     banghart 5302:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5303:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5304:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5305:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5306:0): 
                   5307:0):     # Show grading options
                   5308:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5309:0):     my $select = '<select name="selectpage">'."\n";
                   5310:0):     $ctr=0;
                   5311:0):     foreach (@$titles) {
                   5312:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5313:0):         $select.='<option value="'.$ctr.'"'.
                   5314:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5315:0):             '>'.$showtitle.'</option>'."\n";
                   5316:0):         $ctr++;
                   5317:0):     }
                   5318:0):     $select.= '</select>';
1.72      ng       5319: 
1.596.2.12.2.  1(raebur 5320:0):     $result.=
                   5321:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5322:0):        .$select
                   5323:0):        .&Apache::lonhtmlcommon::row_closure();
                   5324:0): 
                   5325:0):     $result.=
                   5326:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5327:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5328:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5329:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5330:0):            .&mt('yes').'</label>'."\n"
                   5331:0):        .&Apache::lonhtmlcommon::row_closure();
                   5332:0): 
                   5333:0):     $result.=
                   5334:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5335:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5336:0):            .&mt('none').' </label>'."\n"
                   5337:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5338:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5339:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5340:0):            .&mt('all submissions with details').' </label>'
                   5341:0):        .&Apache::lonhtmlcommon::row_closure();
                   5342:0): 
                   5343:0):     $result.=
                   5344:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5345:0):        .'<input type="text" name="CODE" value="" />'
                   5346:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5347:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5348: 
1.596.2.12.2.  1(raebur 5349:0):     # Show list of students to select for grading
                   5350:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5351:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5352: 
1.68      ng       5353:     $request->print($result);
                   5354: 
1.485     albertel 5355:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5356: 	&Apache::loncommon::start_data_table().
                   5357: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5358: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5359: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5360: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5361: 	'<th>'.&nameUserString('header').'</th>'.
                   5362: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5363:  
1.596.2.12.2.  8(raebur 5364:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5365:     my $ptr = 1;
1.294     albertel 5366:     foreach my $student (sort 
                   5367: 			 {
                   5368: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5369: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5370: 			     }
                   5371: 			     return $a cmp $b;
                   5372: 			 } (keys(%$fullname))) {
1.68      ng       5373: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5374: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5375:                                   : '</td>');
1.126     ng       5376: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5377: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5378: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5379: 	$studentTable.=
                   5380: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5381:                          : '');
1.68      ng       5382: 	$ptr++;
                   5383:     }
1.484     albertel 5384:     if ($ptr%2 == 0) {
                   5385: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5386: 	    &Apache::loncommon::end_data_table_row();
                   5387:     }
                   5388:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5389:     $studentTable.='<input type="button" '.
1.589     bisitz   5390:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5391: 
                   5392:     $request->print($studentTable);
                   5393: 
                   5394:     return '';
                   5395: }
                   5396: 
                   5397: sub getSymbMap {
1.582     raeburn  5398:     my ($map_error) = @_;
1.132     bowersj2 5399:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5400:     unless (ref($navmap)) {
                   5401:         if (ref($map_error)) {
                   5402:             $$map_error = 'navmap';
                   5403:         }
                   5404:         return;
                   5405:     }
1.68      ng       5406:     my %symbx = ();
                   5407:     my @titles = ();
1.117     bowersj2 5408:     my $minder = 0;
                   5409: 
                   5410:     # Gather every sequence that has problems.
1.240     albertel 5411:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5412: 					       1,0,1);
1.117     bowersj2 5413:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.596.2.12.2.  0.2.4(ra 5414:ul-23): 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5415: 	    my $title = $minder.'.'.
                   5416: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5417: 	    push(@titles, $title); # minder in case two titles are identical
                   5418: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5419: 	    $minder++;
1.241     albertel 5420: 	}
1.68      ng       5421:     }
                   5422:     return \@titles,\%symbx;
                   5423: }
                   5424: 
1.72      ng       5425: #
                   5426: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5427: sub displayPage {
1.596.2.12.2.  1(raebur 5428:0):     my ($request,$symb) = @_;
1.257     albertel 5429:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5430:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5431:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5432:     my $pageTitle = $env{'form.page'};
1.103     albertel 5433:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5434:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5435:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5436: 
                   5437:     #need to make sure we have the correct data for later EXT calls, 
                   5438:     #thus invalidate the cache
                   5439:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5440:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5441:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5442:     &Apache::lonnet::clear_EXT_cache_status();
                   5443: 
1.103     albertel 5444:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5445:0): 	$request->print(
                   5446:0):             '<span class="LC_warning">'.
                   5447:0):             &mt('Unable to view requested student. ([_1])',
                   5448:0):                 $env{'form.student'}).
                   5449:0):             '</span>');
          8(raebur 5450:4):         return;
1.103     albertel 5451:     }
1.398     albertel 5452:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5453:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5454: 	'</h3>'."\n";
1.500     albertel 5455:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5456:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5457: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5458:     } else {
                   5459: 	delete($env{'form.CODE'});
                   5460:     }
1.71      ng       5461:     &sub_page_js($request);
                   5462:     $request->print($result);
                   5463: 
1.132     bowersj2 5464:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5465:     unless (ref($navmap)) {
                   5466:         $request->print(&navmap_errormsg());
                   5467:         return;
                   5468:     }
1.257     albertel 5469:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5470:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5471:     if (!$map) {
1.485     albertel 5472: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5473: 	return; 
                   5474:     }
1.68      ng       5475:     my $iterator = $navmap->getIterator($map->map_start(),
                   5476: 					$map->map_finish());
                   5477: 
1.71      ng       5478:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5479: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5480: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5481: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5482: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5483: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5484: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5485:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5486: 
1.382     albertel 5487:     if (defined($env{'form.CODE'})) {
                   5488: 	$studentTable.=
                   5489: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5490:     }
1.381     albertel 5491:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5492: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5493: 
1.594     bisitz   5494:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5495:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5496:         '</span>'."\n".
1.484     albertel 5497: 	&Apache::loncommon::start_data_table().
                   5498: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5499:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5500: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5501: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5502: 
1.329     albertel 5503:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5504:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5505:     $iterator->next(); # skip the first BEGIN_MAP
                   5506:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5507:     while ($depth > 0) {
1.68      ng       5508:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5509:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5510: 
1.596.2.12.2.  0.2.4(ra 5511:ul-23):         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5512: 	    my $parts = $curRes->parts();
1.68      ng       5513:             my $title = $curRes->compTitle();
1.71      ng       5514: 	    my $symbx = $curRes->symb();
1.596.2.12.2.  0.2.4(ra 5515:ul-23):             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5516: 	    $studentTable.=
                   5517: 		&Apache::loncommon::start_data_table_row().
                   5518: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5519: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5520:2): 		                        : '<br />('.&mt('[_1]parts',
                   5521:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5522: 		 ).
                   5523: 		 '</td>';
1.71      ng       5524: 	    $studentTable.='<td valign="top">';
1.382     albertel 5525: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.596.2.12.2.  0.2.4(ra 5526:ul-23):             if ($is_tool) {
                   5527:ul-23):                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5528:ul-23):             } else {
                   5529:ul-23): 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5530:ul-23): 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5531:ul-23): 			   		         undef,'both',\%form);
                   5532:ul-23): 	        } else {
                   5533:ul-23): 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5534:ul-23): 		    $companswer =~ s|<form(.*?)>||g;
                   5535:ul-23): 		    $companswer =~ s|</form>||g;
                   5536:ul-23): #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5537:ul-23): #		        $companswer =~ s/$1/ /ms;
                   5538:ul-23): #		        $request->print('match='.$1."<br />\n");
                   5539:ul-23): #		    }
                   5540:ul-23): #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5541:ul-23): 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5542:ul-23):                 }
1.71      ng       5543: 	    }
                   5544: 
1.257     albertel 5545: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5546: 
1.257     albertel 5547: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5548: 		if ($record{'version'} eq '') {
1.596.2.12.2.  0.2.4(ra 5549:ul-23):                     my $msg = &mt('No recorded submission for this problem.');
                   5550:ul-23):                     if ($is_tool) {
                   5551:ul-23):                         $msg = &mt('No recorded transactions for this external tool');
                   5552:ul-23):                     }
                   5553:ul-23): 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5554: 		} else {
1.116     ng       5555: 		    my %responseType = ();
                   5556: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5557: 			my @responseIds =$curRes->responseIds($partid);
                   5558: 			my @responseType =$curRes->responseType($partid);
                   5559: 			my %responseIds;
                   5560: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5561: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5562: 			}
                   5563: 			$responseType{$partid} = \%responseIds;
1.116     ng       5564: 		    }
1.148     albertel 5565: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5566: 
1.71      ng       5567: 		}
1.257     albertel 5568: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5569: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5570:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5571: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5572: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5573:5): 									'','.submission',undef,
                   5574:5):                                                                         $usec,$identifier);
1.71      ng       5575:  
                   5576: 	    }
1.103     albertel 5577: 	    if (&canmodify($usec)) {
1.585     bisitz   5578:             $studentTable.=&gradeBox_start();
1.103     albertel 5579: 		foreach my $partid (@{$parts}) {
                   5580: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5581: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5582: 		    $question++;
                   5583: 		}
1.585     bisitz   5584:             $studentTable.=&gradeBox_end();
1.196     albertel 5585: 		$prob++;
1.71      ng       5586: 	    }
                   5587: 	    $studentTable.='</td></tr>';
1.68      ng       5588: 
1.103     albertel 5589: 	}
1.68      ng       5590:         $curRes = $iterator->next();
                   5591:     }
1.596.2.12.2.  6(raebur 5592:1):     my $disabled;
                   5593:1):     unless (&canmodify($usec)) {
                   5594:1):         $disabled = ' disabled="disabled"';
                   5595:1):     }
1.68      ng       5596: 
1.589     bisitz   5597:     $studentTable.=
                   5598:         '</table>'."\n".
1.596.2.12.2.  6(raebur 5599:1):         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5600:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5601:         '</form>'."\n";
1.71      ng       5602:     $request->print($studentTable);
                   5603: 
                   5604:     return '';
1.119     ng       5605: }
                   5606: 
                   5607: sub displaySubByDates {
1.148     albertel 5608:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5609:     my $isCODE=0;
1.335     albertel 5610:     my $isTask = ($symb =~/\.task$/);
1.596.2.12.2.  0.2.4(ra 5611:ul-23):     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5612:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5613:     my $studentTable=&Apache::loncommon::start_data_table().
                   5614: 	&Apache::loncommon::start_data_table_header_row().
                   5615: 	'<th>'.&mt('Date/Time').'</th>'.
                   5616: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5617:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
          0.2.4(ra 5618:ul-23): 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5619: 	'<th>'.&mt('Status').'</th>'.
                   5620: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5621:     my ($version);
                   5622:     my %mark;
1.148     albertel 5623:     my %orders;
1.119     ng       5624:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5625:     if (!exists($$record{'1:timestamp'})) {
1.596.2.12.2.  0.2.4(ra 5626:ul-23):         if ($is_tool) {
                   5627:ul-23):             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5628:ul-23):         } else {
                   5629:ul-23): 	    return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5630:ul-23):         }
1.147     albertel 5631:     }
1.335     albertel 5632: 
                   5633:     my $interaction;
1.525     raeburn  5634:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5635:5):     my (%lastrndseed,%lasttype);
1.119     ng       5636:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5637: 	my $timestamp = 
                   5638: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5639: 	if (exists($$record{$version.':resource.0.version'})) {
                   5640: 	    $interaction = $$record{$version.':resource.0.version'};
                   5641: 	}
1.596.2.12.2.  (raeburn 5642:):         if ($isTask && $env{'form.previousversion'}) {
                   5643:):             next unless ($interaction == $env{'form.previousversion'});
                   5644:):         }
1.335     albertel 5645: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5646: 		             : "$version:resource");
1.467     albertel 5647: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5648: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5649: 	if ($isCODE) {
                   5650: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5651: 	}
1.596.2.12.2.  (raeburn 5652:):         if ($isTask) {
                   5653:):             $studentTable.='<td>'.$interaction.'</td>';
                   5654:):         }
1.119     ng       5655: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5656: 	my @displaySub = ();
                   5657: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5658:             my ($hidden,$type);
                   5659:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5660:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5661:                 $hidden = 1;
                   5662:             }
1.596.2.12.2.  1(raebur 5663:0): 	    my @matchKey;
                   5664:0):             if ($isTask) {
                   5665:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
          0.2.4(ra 5666:ul-23):             } elsif ($is_tool) {
                   5667:ul-23):                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
          1(raebur 5668:0):             } else {
                   5669:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5670:0):             }
1.122     ng       5671: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5672: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5673: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5674: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5675: 		    $$record{$version.':'.$matchKey} ne '') {
1.596.2.12.2.  0.2.4(ra 5676:ul-23):                     if ($is_tool) {
                   5677:ul-23):                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5678:                     } else {
1.596.2.12.2.  0.2.4(ra 5679:ul-23): 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5680:ul-23): 			    	                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5681:ul-23):                         $displaySub[0].='<span class="LC_nobreak">';
                   5682:ul-23):                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5683:ul-23):                                        .' <span class="LC_internal_info">'
                   5684:ul-23):                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5685:ul-23):                                        .'</span>'
                   5686:ul-23):                                        .' <b>';
                   5687:ul-23):                         if ($hidden) {
                   5688:ul-23):                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5689:ul-23):                         } else {
                   5690:ul-23):                             my ($trial,$rndseed,$newvariation);
                   5691:ul-23):                             if ($type eq 'randomizetry') {
                   5692:ul-23):                                 $trial = $$record{"$where.$partid.tries"};
                   5693:ul-23):                                 $rndseed = $$record{"$where.$partid.rndseed"};
1.596.2.2  raeburn  5694:                             }
1.596.2.12.2.  0.2.4(ra 5695:ul-23): 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5696:ul-23): 			        $displaySub[0].=&mt('Trial not counted');
                   5697:ul-23): 		            } else {
                   5698:ul-23): 			        $displaySub[0].=&mt('Trial: [_1]',
                   5699:ul-23): 				    	        $$record{"$where.$partid.tries"});
                   5700:ul-23):                                 if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
                   5701:ul-23):                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5702:ul-23):                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5703:ul-23):                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5704:ul-23):                                     }
                   5705:ul-23):                                 }
                   5706:ul-23):                                 $lastrndseed{$partid} = $rndseed;
                   5707:ul-23):                                 $lasttype{$partid} = $type;
                   5708:ul-23): 		           }
                   5709:ul-23): 		           my $responseType=($isTask ? 'Task'
                   5710:ul-23):                                                   : $responseType->{$partid}->{$responseId});
                   5711:ul-23): 		           if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5712:ul-23): 		           if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5713:ul-23): 			       $orders{$partid}->{$responseId}=
                   5714:ul-23): 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5715:ul-23):                                                $no_increment,$type,$trial,$rndseed);
                   5716:ul-23): 		            }
                   5717:ul-23): 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5718:ul-23): 		            $displaySub[0].='&nbsp; '.
                   5719:ul-23): 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5720:ul-23):                         }
1.596     raeburn  5721:                     }
1.147     albertel 5722: 		}
                   5723: 	    }
1.335     albertel 5724: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5725: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5726: 				    $$record{"$where.$partid.checkedin"},
                   5727: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5728: 					'<br />';
1.335     albertel 5729: 	    }
                   5730: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5731: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5732: 		    lc($$record{"$where.$partid.award"}).' '.
                   5733: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5734: 		    '<br />';
1.596.2.12.2.  0.2.4(ra 5735:ul-23):             } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5736:ul-23):                 if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5737:ul-23):                     $displaySub[1].=&mt('Grade passed back by external tool');
                   5738:ul-23):                 }
1.147     albertel 5739: 	    }
1.335     albertel 5740: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.596.2.12.2.  0.2.4(ra 5741:ul-23): 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5742:ul-23):                 unless ($is_tool) {
                   5743:ul-23): 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5744:ul-23):                 }
1.335     albertel 5745: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5746: 		$displaySub[2].=
1.596.2.12.2.  0.2.4(ra 5747:ul-23): 		    $$record{"$version:resource.$partid.regrader"};
                   5748:ul-23):                 unless ($is_tool) {
                   5749:ul-23): 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5750:ul-23):                 }
1.147     albertel 5751: 	    }
                   5752: 	}
                   5753: 	# needed because old essay regrader has not parts info
                   5754: 	if (exists $$record{"$version:resource.regrader"}) {
                   5755: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5756: 	}
                   5757: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5758: 	if ($displaySub[2]) {
1.467     albertel 5759: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5760: 	}
1.467     albertel 5761: 	$studentTable.='&nbsp;</td>'.
                   5762: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5763:     }
1.467     albertel 5764:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5765:     return $studentTable;
1.71      ng       5766: }
                   5767: 
                   5768: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5769:0):     my ($request,$symb) = @_;
1.71      ng       5770: 
1.257     albertel 5771:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5772:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5773:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5774:     my $pageTitle = $env{'form.page'};
1.103     albertel 5775:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5776:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5777:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5778:     if (!&canmodify($usec)) {
1.526     raeburn  5779: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5780: 	return;
                   5781:     }
1.398     albertel 5782:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5783:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5784: 	'</h3>'."\n";
1.70      ng       5785: 
1.68      ng       5786:     $request->print($result);
                   5787: 
1.582     raeburn  5788: 
1.132     bowersj2 5789:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5790:     unless (ref($navmap)) {
                   5791:         $request->print(&navmap_errormsg());
                   5792:         return;
                   5793:     }
1.257     albertel 5794:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5795:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5796:     if (!$map) {
1.527     raeburn  5797: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5798: 	return; 
                   5799:     }
1.71      ng       5800:     my $iterator = $navmap->getIterator($map->map_start(),
                   5801: 					$map->map_finish());
1.70      ng       5802: 
1.484     albertel 5803:     my $studentTable=
                   5804: 	&Apache::loncommon::start_data_table().
                   5805: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5806: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5807: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5808: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5809: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5810: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5811: 
                   5812:     $iterator->next(); # skip the first BEGIN_MAP
                   5813:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5814:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5815:     while ($depth > 0) {
1.71      ng       5816:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5817:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5818: 
1.385     albertel 5819:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5820: 	    my $parts = $curRes->parts();
1.71      ng       5821:             my $title = $curRes->compTitle();
                   5822: 	    my $symbx = $curRes->symb();
1.484     albertel 5823: 	    $studentTable.=
                   5824: 		&Apache::loncommon::start_data_table_row().
                   5825: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5826: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5827:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5828: 		.')').'</td>';
1.71      ng       5829: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5830: 
                   5831: 	    my %newrecord=();
                   5832: 	    my @displayPts=();
1.269     raeburn  5833:             my %aggregate = ();
                   5834:             my $aggregateflag = 0;
1.596.2.12.2.  9(raebur 5835:1):             my %queueable;
          1(raebur 5836:5):             if ($env{'form.HIDE'.$prob}) {
                   5837:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5838:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5839:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5840:5):                 $hideflag += $numchgs;
                   5841:5):             }
1.71      ng       5842: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5843: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5844: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.596.2.12.2.  9(raebur 5845:1):                 my @types = $curRes->responseType($partid);
          8(raebur 5846:1):                 if (grep(/^essay$/,@types)) {
                   5847:1):                     $queueable{$partid} = 1;
                   5848:1):                 } else {
          9(raebur 5849:1):                     my @ids = $curRes->responseIds($partid);
          8(raebur 5850:1):                     for (my $i=0; $i < scalar(@ids); $i++) {
          9(raebur 5851:1):                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
          8(raebur 5852:1):                                                           '.handgrade',$symb);
                   5853:1):                         if (lc($hndgrd) eq 'yes') {
                   5854:1):                             $queueable{$partid} = 1;
                   5855:1):                             last;
                   5856:1):                         }
                   5857:1):                     }
                   5858:1):                 }
1.257     albertel 5859: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5860: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5861: 		my $partial = $newpts/$wgt;
                   5862: 		my $score;
                   5863: 		if ($partial > 0) {
                   5864: 		    $score = 'correct_by_override';
1.125     ng       5865: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5866: 		    $score = 'incorrect_by_override';
                   5867: 		}
1.257     albertel 5868: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5869: 		if ($dropMenu eq 'excused') {
1.71      ng       5870: 		    $partial = '';
                   5871: 		    $score = 'excused';
1.125     ng       5872: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5873: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5874: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5875: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5876: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5877: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5878: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5879: 		    $changeflag++;
                   5880: 		    $newpts = '';
1.269     raeburn  5881:                     
                   5882:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5883:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5884:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5885:                     if ($aggtries > 0) {
                   5886:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5887:                         $aggregateflag = 1;
                   5888:                     }
1.71      ng       5889: 		}
1.324     albertel 5890: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5891: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5892: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5893: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5894: 		    '&nbsp;<br />';
1.526     raeburn  5895: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5896: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5897: 		    '&nbsp;<br />';
1.71      ng       5898: 		$question++;
1.380     albertel 5899: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5900: 
1.71      ng       5901: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5902: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5903: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5904: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5905: 
                   5906: 		$changeflag++;
                   5907: 	    }
                   5908: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5909: 		my %record = 
                   5910: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5911: 					     $udom,$uname);
                   5912: 
                   5913: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5914: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5915: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5916: 		    $newrecord{'resource.CODE'} = '';
                   5917: 		}
1.257     albertel 5918: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5919: 					$udom,$uname);
1.382     albertel 5920: 		%record = &Apache::lonnet::restore($symbx,
                   5921: 						   $env{'request.course.id'},
                   5922: 						   $udom,$uname);
1.380     albertel 5923: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.596.2.12.2.  8(raebur 5924:1): 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5925: 	    }
1.380     albertel 5926: 	    
1.269     raeburn  5927:             if ($aggregateflag) {
                   5928:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5929:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5930:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5931:             }
1.125     ng       5932: 
1.71      ng       5933: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5934: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5935: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5936: 
1.196     albertel 5937: 	    $prob++;
1.68      ng       5938: 	}
1.71      ng       5939:         $curRes = $iterator->next();
1.68      ng       5940:     }
1.98      albertel 5941: 
1.484     albertel 5942:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5943:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5944: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5945:5): 		  $changeflag).'<br />');
                   5946:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5947:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5948:5):                      $hideflag).'<br />');
                   5949:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5950: 
1.70      ng       5951:     return '';
                   5952: }
                   5953: 
1.72      ng       5954: #-------- end of section for handling grading by page/sequence ---------
                   5955: #
                   5956: #-------------------------------------------------------------------
                   5957: 
1.581     www      5958: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5959: #
                   5960: #------ start of section for handling grading by page/sequence ---------
                   5961: 
1.423     albertel 5962: =pod
                   5963: 
                   5964: =head1 Bubble sheet grading routines
                   5965: 
1.424     albertel 5966:   For this documentation:
                   5967: 
                   5968:    'scanline' refers to the full line of characters
                   5969:    from the file that we are parsing that represents one entire sheet
                   5970: 
                   5971:    'bubble line' refers to the data
1.596.2.6  raeburn  5972:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5973: 
                   5974: 
1.596.2.6  raeburn  5975: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5976: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5977: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5978: one of the predefined configurations for what each scanline looks
                   5979: like.
                   5980: 
                   5981: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5982: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5983: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5984:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5985: invalid student/employee ID
1.424     albertel 5986: 
                   5987: If the CODE option is used that determines the randomization of the
1.556     weissno  5988: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5989: username:domain.
                   5990: 
                   5991: During the validation phase the instructor can choose to skip scanlines. 
                   5992: 
1.596.2.6  raeburn  5993: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5994: 
                   5995:   scantron_original_filename (unmodified original file)
                   5996:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5997:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5998: 
                   5999: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  6000: correction information that isn't representable in the bubblesheet
1.424     albertel 6001: file (see &scantron_getfile() for more information)
                   6002: 
                   6003: After all scanlines are either valid, marked as valid or skipped, then
                   6004: foreach line foreach problem in the picked sequence, an ssi request is
                   6005: made that simulates a user submitting their selected letter(s) against
                   6006: the homework problem.
1.423     albertel 6007: 
                   6008: =over 4
                   6009: 
                   6010: 
                   6011: 
                   6012: =item defaultFormData
                   6013: 
                   6014:   Returns html hidden inputs used to hold context/default values.
                   6015: 
                   6016:  Arguments:
                   6017:   $symb - $symb of the current resource 
                   6018: 
                   6019: =cut
1.422     foxr     6020: 
1.81      albertel 6021: sub defaultFormData {
1.324     albertel 6022:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 6023:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 6024: }
                   6025: 
1.447     foxr     6026: 
1.423     albertel 6027: =pod 
                   6028: 
                   6029: =item getSequenceDropDown
                   6030: 
                   6031:    Return html dropdown of possible sequences to grade
                   6032:  
                   6033:  Arguments:
1.582     raeburn  6034:    $symb - $symb of the current resource
                   6035:    $map_error - ref to scalar which will container error if
                   6036:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 6037: 
                   6038: =cut
1.422     foxr     6039: 
1.75      albertel 6040: sub getSequenceDropDown {
1.582     raeburn  6041:     my ($symb,$map_error)=@_;
1.75      albertel 6042:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  6043:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6044:     if (ref($map_error)) {
                   6045:         return if ($$map_error);
                   6046:     }
1.137     albertel 6047:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 6048:     my $ctr=0;
                   6049:     foreach (@$titles) {
                   6050: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6051: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 6052: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 6053: 	    '>'.$showtitle.'</option>'."\n";
                   6054: 	$ctr++;
                   6055:     }
                   6056:     $result.= '</select>';
                   6057:     return $result;
                   6058: }
                   6059: 
1.495     albertel 6060: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  6061:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 6062: 
                   6063: my %first_bubble_line;             # First bubble line no. for each bubble.
                   6064: 
1.509     raeburn  6065: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   6066:                                    # matchresponse or rankresponse, where 
                   6067:                                    # an individual response can have multiple 
                   6068:                                    # lines
1.503     raeburn  6069: 
                   6070: my %responsetype_per_response;     # responsetype for each response
                   6071: 
1.596.2.12.2.  6(raebur 6072:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   6073:3):                                    # numbered response. Needed when randomorder
                   6074:3):                                    # or randompick are in use. Key is ID, value 
                   6075:3):                                    # is response number.
                   6076:3): 
1.495     albertel 6077: # Save and restore the bubble lines array to the form env.
                   6078: 
                   6079: 
                   6080: sub save_bubble_lines {
                   6081:     foreach my $line (keys(%bubble_lines_per_response)) {
                   6082: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   6083: 	$env{"form.scantron.first_bubble_line.$line"} =
                   6084: 	    $first_bubble_line{$line};
1.503     raeburn  6085:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   6086:             $subdivided_bubble_lines{$line};
                   6087:         $env{"form.scantron.responsetype.$line"} =
                   6088:             $responsetype_per_response{$line};
1.495     albertel 6089:     }
1.596.2.12.2.  6(raebur 6090:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   6091:3):         my $line = $masterseq_id_responsenum{$resid};
                   6092:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   6093:3):     }
1.495     albertel 6094: }
                   6095: 
                   6096: 
                   6097: sub restore_bubble_lines {
                   6098:     my $line = 0;
                   6099:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 6100:3):     %masterseq_id_responsenum = ();
1.495     albertel 6101:     while ($env{"form.scantron.bubblelines.$line"}) {
                   6102: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   6103: 	$bubble_lines_per_response{$line} = $value;
                   6104: 	$first_bubble_line{$line}  =
                   6105: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  6106:         $subdivided_bubble_lines{$line} =
                   6107:             $env{"form.scantron.sub_bubblelines.$line"};
                   6108:         $responsetype_per_response{$line} =
                   6109:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 6110:3):         my $id = $env{"form.scantron.residpart.$line"};
                   6111:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 6112: 	$line++;
                   6113:     }
                   6114: }
                   6115: 
1.423     albertel 6116: =pod 
                   6117: 
                   6118: =item scantron_filenames
                   6119: 
                   6120:    Returns a list of the scantron files in the current course 
                   6121: 
                   6122: =cut
1.422     foxr     6123: 
1.202     albertel 6124: sub scantron_filenames {
1.257     albertel 6125:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6126:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6127:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 6128:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6129:):                                                         $cname,$getpropath);
1.202     albertel 6130:     my @possiblenames;
1.596.2.12.2.  (raeburn 6131:):     if (ref($dirlist) eq 'ARRAY') {
                   6132:):         foreach my $filename (sort(@{$dirlist})) {
                   6133:): 	    ($filename)=split(/&/,$filename);
                   6134:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6135:): 	    $filename=~s/^scantron_orig_//;
                   6136:): 	    push(@possiblenames,$filename);
                   6137:):         }
1.202     albertel 6138:     }
                   6139:     return @possiblenames;
                   6140: }
                   6141: 
1.423     albertel 6142: =pod 
                   6143: 
                   6144: =item scantron_uploads
                   6145: 
                   6146:    Returns  html drop-down list of scantron files in current course.
                   6147: 
                   6148:  Arguments:
                   6149:    $file2grade - filename to set as selected in the dropdown
                   6150: 
                   6151: =cut
1.422     foxr     6152: 
1.202     albertel 6153: sub scantron_uploads {
1.209     ng       6154:     my ($file2grade) = @_;
1.202     albertel 6155:     my $result=	'<select name="scantron_selectfile">';
                   6156:     $result.="<option></option>";
                   6157:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6158: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6159:     }
                   6160:     $result.="</select>";
                   6161:     return $result;
                   6162: }
                   6163: 
1.423     albertel 6164: =pod 
                   6165: 
                   6166: =item scantron_scantab
                   6167: 
                   6168:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6169:   file.
                   6170: 
                   6171: =cut
1.422     foxr     6172: 
1.82      albertel 6173: sub scantron_scantab {
                   6174:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6175:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 6176:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6177:     if (@lines > 0) {
                   6178:         foreach my $line (@lines) {
                   6179:             next if (($line =~ /^\#/) || ($line eq ''));
                   6180: 	    my ($name,$descrip)=split(/:/,$line);
                   6181: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6182:         }
1.82      albertel 6183:     }
                   6184:     $result.='</select>'."\n";
1.518     raeburn  6185:     return $result;
                   6186: }
                   6187: 
1.423     albertel 6188: =pod 
                   6189: 
                   6190: =item scantron_CODElist
                   6191: 
                   6192:   Returns html drop down of the saved CODE lists from current course,
                   6193:   generated from earlier printings.
                   6194: 
                   6195: =cut
1.422     foxr     6196: 
1.186     albertel 6197: sub scantron_CODElist {
1.257     albertel 6198:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6199:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6200:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6201:     my $namechoice='<option></option>';
1.225     albertel 6202:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6203: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6204: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6205: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6206:     }
                   6207:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6208:     return $namechoice;
                   6209: }
                   6210: 
1.423     albertel 6211: =pod 
                   6212: 
                   6213: =item scantron_CODEunique
                   6214: 
                   6215:   Returns the html for "Each CODE to be used once" radio.
                   6216: 
                   6217: =cut
1.422     foxr     6218: 
1.186     albertel 6219: sub scantron_CODEunique {
1.532     bisitz   6220:     my $result='<span class="LC_nobreak">
1.272     albertel 6221:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6222:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6223:                 </span>
1.532     bisitz   6224:                 <span class="LC_nobreak">
1.272     albertel 6225:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6226:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6227:                 </span>';
1.186     albertel 6228:     return $result;
                   6229: }
1.423     albertel 6230: 
                   6231: =pod 
                   6232: 
                   6233: =item scantron_selectphase
                   6234: 
1.596.2.6  raeburn  6235:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6236:   Allows for - starting a grading run.
1.424     albertel 6237:              - downloading existing scan data (original, corrected
1.423     albertel 6238:                                                 or skipped info)
                   6239: 
                   6240:              - uploading new scan data
                   6241: 
                   6242:  Arguments:
                   6243:   $r          - The Apache request object
                   6244:   $file2grade - name of the file that contain the scanned data to score
                   6245: 
                   6246: =cut
1.186     albertel 6247: 
1.75      albertel 6248: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 6249:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6250:     if (!$symb) {return '';}
1.582     raeburn  6251:     my $map_error;
                   6252:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6253:     if ($map_error) {
                   6254:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6255:         return;
                   6256:     }
1.324     albertel 6257:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6258:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6259:     my $format_selector=&scantron_scantab();
1.186     albertel 6260:     my $CODE_selector=&scantron_CODElist();
                   6261:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6262:     my $result;
1.422     foxr     6263: 
1.513     foxr     6264:     $ssi_error = 0;
                   6265: 
1.596.2.4  raeburn  6266:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6267:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6268: 
                   6269:         # Chunk of form to prompt for a scantron file upload.
                   6270: 
                   6271:         $r->print('
1.596.2.12.2.  9(raebur 6272:9):     <br />');
                   6273:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6274:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6275:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6276:9):         &js_escape(\$alertmsg);
                   6277:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6278:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6279:     function checkUpload(formname) {
                   6280:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6281:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6282:             return false;
                   6283:         }
                   6284:         formname.submit();
1.596.2.12.2.  9(raebur 6285:9):     }'."\n".$formatjs));
                   6286:9):         $r->print('
1.596.2.4  raeburn  6287:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6288:                 '.$default_form_data.'
                   6289:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6290:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6291:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6292:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6293:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6294:9):                 <th>
                   6295:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6296:9):                 </th>
                   6297:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6298:9):               '.&Apache::loncommon::start_data_table_row().'
                   6299:9):             <td>
                   6300:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6301:9):         if ($formatoptions) {
                   6302:9):             $r->print('</td>
                   6303:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6304:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6305:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6306:9):                  </td>
                   6307:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6308:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6309:9):                  <td>'
                   6310:9):             );
                   6311:9):         } else {
                   6312:9):             $r->print(' <br />');
                   6313:9):         }
                   6314:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6315:9):               </td>
                   6316:9):              '.&Apache::loncommon::end_data_table_row().'
                   6317:9):              '.&Apache::loncommon::end_data_table().'
                   6318:9):              </form>'
                   6319:9):         );
1.596.2.4  raeburn  6320: 
                   6321:     }
                   6322: 
1.422     foxr     6323:     # Chunk of form to prompt for a file to grade and how:
                   6324: 
1.489     albertel 6325:     $result.= '
                   6326:     <br />
                   6327:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6328:     <input type="hidden" name="command" value="scantron_warning" />
                   6329:     '.$default_form_data.'
                   6330:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6331:        '.&Apache::loncommon::start_data_table_header_row().'
                   6332:             <th colspan="2">
1.492     albertel 6333:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6334:             </th>
                   6335:        '.&Apache::loncommon::end_data_table_header_row().'
                   6336:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6337:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6338:        '.&Apache::loncommon::end_data_table_row().'
                   6339:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6340:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6341:        '.&Apache::loncommon::end_data_table_row().'
                   6342:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6343:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6344:        '.&Apache::loncommon::end_data_table_row().'
                   6345:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6346:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6347:        '.&Apache::loncommon::end_data_table_row().'
                   6348:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6349:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6350:        '.&Apache::loncommon::end_data_table_row().'
                   6351:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6352: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6353:             <td>
1.492     albertel 6354: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6355:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6356:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6357: 	    </td>
1.489     albertel 6358:        '.&Apache::loncommon::end_data_table_row().'
                   6359:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6360:             <td colspan="2">
1.572     www      6361:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6362:             </td>
1.489     albertel 6363:        '.&Apache::loncommon::end_data_table_row().'
                   6364:     '.&Apache::loncommon::end_data_table().'
                   6365:     </form>
                   6366: ';
1.162     albertel 6367:    
                   6368:     $r->print($result);
                   6369: 
1.422     foxr     6370:     # Chunk of the form that prompts to view a scoring office file,
                   6371:     # corrected file, skipped records in a file.
                   6372: 
1.489     albertel 6373:     $r->print('
                   6374:    <br />
                   6375:    <form action="/adm/grades" name="scantron_download">
                   6376:      '.$default_form_data.'
                   6377:      <input type="hidden" name="command" value="scantron_download" />
                   6378:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6379:        '.&Apache::loncommon::start_data_table_header_row().'
                   6380:               <th>
1.492     albertel 6381:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6382:               </th>
                   6383:        '.&Apache::loncommon::end_data_table_header_row().'
                   6384:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6385:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6386:                 <br />
1.492     albertel 6387:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6388:        '.&Apache::loncommon::end_data_table_row().'
                   6389:      '.&Apache::loncommon::end_data_table().'
                   6390:    </form>
                   6391:    <br />
                   6392: ');
1.162     albertel 6393: 
1.457     banghart 6394:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6395: 
1.596.2.12.2.  8(raebur 6396:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6397:              $default_form_data."\n".
                   6398:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6399:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6400:              '<th colspan="2">
1.572     www      6401:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6402:              '</th>'."\n".
                   6403:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6404:               &Apache::loncommon::start_data_table_row()."\n".
                   6405:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6406:               '<td> '.$sequence_selector.' </td>'.
                   6407:               &Apache::loncommon::end_data_table_row()."\n".
                   6408:               &Apache::loncommon::start_data_table_row()."\n".
                   6409:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6410:               '<td> '.$file_selector.' </td>'."\n".
                   6411:               &Apache::loncommon::end_data_table_row()."\n".
                   6412:               &Apache::loncommon::start_data_table_row()."\n".
                   6413:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6414:               '<td> '.$format_selector.' </td>'."\n".
                   6415:               &Apache::loncommon::end_data_table_row()."\n".
                   6416:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6417:               '<td> '.&mt('Options').' </td>'."\n".
                   6418:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6419:               &Apache::loncommon::end_data_table_row()."\n".
                   6420:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6421:               '<td colspan="2">'."\n".
                   6422:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6423:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6424:               '</td>'."\n".
                   6425:               &Apache::loncommon::end_data_table_row()."\n".
                   6426:               &Apache::loncommon::end_data_table()."\n".
                   6427:               '</form><br />');
                   6428:     return;
1.75      albertel 6429: }
                   6430: 
1.423     albertel 6431: =pod 
                   6432: 
                   6433: =item username_to_idmap
                   6434: 
1.556     weissno  6435:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6436:     student username:domain.
                   6437: 
                   6438:   Arguments:
                   6439: 
                   6440:     $classlist - reference to the class list hash. This is a hash
                   6441:                  keyed by student name:domain  whose elements are references
1.424     albertel 6442:                  to arrays containing various chunks of information
1.423     albertel 6443:                  about the student. (See loncoursedata for more info).
                   6444: 
                   6445:   Returns
                   6446:     %idmap - the constructed hash
                   6447: 
                   6448: =cut
                   6449: 
1.82      albertel 6450: sub username_to_idmap {
                   6451:     my ($classlist)= @_;
                   6452:     my %idmap;
                   6453:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6454:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6455:5):         unless ($id eq '') {
                   6456:5):             if (!exists($idmap{$id})) {
                   6457:5):                 $idmap{$id} = $student;
                   6458:5):             } else {
                   6459:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6460:5):                 if ($status eq 'Active') {
                   6461:5):                     $idmap{$id} = $student;
                   6462:5):                 }
                   6463:5):             }
                   6464:5):         }
1.82      albertel 6465:     }
                   6466:     return %idmap;
                   6467: }
1.423     albertel 6468: 
                   6469: =pod
                   6470: 
1.424     albertel 6471: =item scantron_fixup_scanline
1.423     albertel 6472: 
                   6473:    Process a requested correction to a scanline.
                   6474: 
                   6475:   Arguments:
1.596.2.12.2.  9(raebur 6476:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6477:     $scan_data         - hash of correction information 
                   6478:                           (see &scantron_getfile())
                   6479:     $line              - existing scanline
                   6480:     $whichline         - line number of the passed in scanline
                   6481:     $field             - type of change to process 
                   6482:                          (either 
1.573     bisitz   6483:                           'ID'     -> correct the student/employee ID
1.423     albertel 6484:                           'CODE'   -> correct the CODE
                   6485:                           'answer' -> fixup the submitted answers)
                   6486:     
                   6487:    $args               - hash of additional info,
                   6488:                           - 'ID' 
                   6489:                                'newid' -> studentID to use in replacement
1.424     albertel 6490:                                           of existing one
1.423     albertel 6491:                           - 'CODE' 
                   6492:                                'CODE_ignore_dup' - set to true if duplicates
                   6493:                                                    should be ignored.
                   6494: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6495:                                         if the existing unfound code should
1.423     albertel 6496:                                         be used as is
                   6497:                           - 'answer'
                   6498:                                'response' - new answer or 'none' if blank
                   6499:                                'question' - the bubble line to change
1.503     raeburn  6500:                                'questionnum' - the question identifier,
                   6501:                                                may include subquestion. 
1.423     albertel 6502: 
                   6503:   Returns:
                   6504:     $line - the modified scanline
                   6505: 
                   6506:   Side effects: 
                   6507:     $scan_data - may be updated
                   6508: 
                   6509: =cut
                   6510: 
1.82      albertel 6511: 
1.157     albertel 6512: sub scantron_fixup_scanline {
                   6513:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6514:     if ($field eq 'ID') {
                   6515: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6516: 	    return ($line,1,'New value too large');
1.157     albertel 6517: 	}
                   6518: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6519: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6520: 				     $args->{'newid'});
                   6521: 	}
                   6522: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6523: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6524: 	if ($args->{'newid'}=~/^\s*$/) {
                   6525: 	    &scan_data($scan_data,"$whichline.user",
                   6526: 		       $args->{'username'}.':'.$args->{'domain'});
                   6527: 	}
1.186     albertel 6528:     } elsif ($field eq 'CODE') {
1.192     albertel 6529: 	if ($args->{'CODE_ignore_dup'}) {
                   6530: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6531: 	}
                   6532: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6533: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6534: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6535: 		return ($line,1,'New CODE value too large');
                   6536: 	    }
                   6537: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6538: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6539: 	    }
                   6540: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6541: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6542: 	}
1.157     albertel 6543:     } elsif ($field eq 'answer') {
1.497     foxr     6544: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6545: 	my $off=$scantron_config->{'Qoff'};
                   6546: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6547: 	my $answer=${off}x$length;
                   6548: 	if ($args->{'response'} eq 'none') {
                   6549: 	    &scan_data($scan_data,
1.503     raeburn  6550: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6551: 	} else {
                   6552: 	    if ($on eq 'letter') {
                   6553: 		my @alphabet=('A'..'Z');
                   6554: 		$answer=$alphabet[$args->{'response'}];
                   6555: 	    } elsif ($on eq 'number') {
                   6556: 		$answer=$args->{'response'}+1;
                   6557: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6558: 	    } else {
1.497     foxr     6559: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6560: 	    }
1.497     foxr     6561: 	    &scan_data($scan_data,
1.503     raeburn  6562: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6563: 	}
1.497     foxr     6564: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6565: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6566:     }
                   6567:     return $line;
                   6568: }
1.423     albertel 6569: 
                   6570: =pod
                   6571: 
                   6572: =item scan_data
                   6573: 
                   6574:     Edit or look up  an item in the scan_data hash.
                   6575: 
                   6576:   Arguments:
                   6577:     $scan_data  - The hash (see scantron_getfile)
                   6578:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6579:                   scantronfilename_key).
1.423     albertel 6580:     $data        - New value of the hash entry.
                   6581:     $delete      - If true, the entry is removed from the hash.
                   6582: 
                   6583:   Returns:
                   6584:     The new value of the hash table field (undefined if deleted).
                   6585: 
                   6586: =cut
                   6587: 
                   6588: 
1.157     albertel 6589: sub scan_data {
                   6590:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6591:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6592:     if (defined($value)) {
                   6593: 	$scan_data->{$filename.'_'.$key} = $value;
                   6594:     }
                   6595:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6596:     return $scan_data->{$filename.'_'.$key};
                   6597: }
1.423     albertel 6598: 
1.495     albertel 6599: # ----- These first few routines are general use routines.----
                   6600: 
                   6601: # Return the number of occurences of a pattern in a string.
                   6602: 
                   6603: sub occurence_count {
                   6604:     my ($string, $pattern) = @_;
                   6605: 
                   6606:     my @matches = ($string =~ /$pattern/g);
                   6607: 
                   6608:     return scalar(@matches);
                   6609: }
                   6610: 
                   6611: 
                   6612: # Take a string known to have digits and convert all the
                   6613: # digits into letters in the range J,A..I.
                   6614: 
                   6615: sub digits_to_letters {
                   6616:     my ($input) = @_;
                   6617: 
                   6618:     my @alphabet = ('J', 'A'..'I');
                   6619: 
                   6620:     my @input    = split(//, $input);
                   6621:     my $output ='';
                   6622:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6623: 	if ($input[$i] =~ /\d/) {
                   6624: 	    $output .= $alphabet[$input[$i]];
                   6625: 	} else {
                   6626: 	    $output .= $input[$i];
                   6627: 	}
                   6628:     }
                   6629:     return $output;
                   6630: }
                   6631: 
1.423     albertel 6632: =pod 
                   6633: 
                   6634: =item scantron_parse_scanline
                   6635: 
                   6636:   Decodes a scanline from the selected scantron file
                   6637: 
                   6638:  Arguments:
                   6639:     line             - The text of the scantron file line to process
                   6640:     whichline        - Line number
                   6641:     scantron_config  - Hash describing the format of the scantron lines.
                   6642:     scan_data        - Hash of extra information about the scanline
                   6643:                        (see scantron_getfile for more information)
                   6644:     just_header      - True if should not process question answers but only
                   6645:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6646:3):     randomorder      - True if randomorder in use
                   6647:3):     randompick       - True if randompick in use
                   6648:3):     sequence         - Exam folder URL
                   6649:3):     master_seq       - Ref to array containing symbs in exam folder
                   6650:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6651:3):                        (corresponding values are resource objects)
                   6652:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6653:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6654:3):                        are refs to an array of resource objects, ordered
                   6655:3):                        according to order used for CODE, when randomorder
                   6656:3):                        and or randompick are in use.
                   6657:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6658:3):                        for current line to question number used for same question
                   6659:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6660:3):     startline        - Ref to hash where key is question number (0 is first)
                   6661:3):                        and value is number of first bubble line for current 
                   6662:3):                        student or code-based randompick and/or randomorder.
                   6663:3):     totalref         - Ref of scalar used to score total number of bubble
                   6664:3):                        lines needed for responses in a scan line (used when
                   6665:3):                        randompick in use. 
                   6666:3): 
1.423     albertel 6667:  Returns:
                   6668:    Hash containing the result of parsing the scanline
                   6669: 
                   6670:    Keys are all proceeded by the string 'scantron.'
                   6671: 
                   6672:        CODE    - the CODE in use for this scanline
                   6673:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6674:                  by the operator
                   6675:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6676:                             CODEs were selected, but the usage has been
                   6677:                             forced by the operator
1.556     weissno  6678:        ID  - student/employee ID
1.423     albertel 6679:        PaperID - if used, the ID number printed on the sheet when the 
                   6680:                  paper was scanned
                   6681:        FirstName - first name from the sheet
                   6682:        LastName  - last name from the sheet
                   6683: 
                   6684:      if just_header was not true these key may also exist
                   6685: 
1.447     foxr     6686:        missingerror - a list of bubble ranges that are considered to be answers
                   6687:                       to a single question that don't have any bubbles filled in.
                   6688:                       Of the form questionnumber:firstbubblenumber:count.
                   6689:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6690:                       to a single question that have more than one bubble filled in.
                   6691:                       Of the form questionnumber::firstbubblenumber:count
                   6692:    
                   6693:                 In the above, count is the number of bubble responses in the
                   6694:                 input line needed to represent the possible answers to the question.
                   6695:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6696:                 per line would have count = 2.
                   6697: 
1.423     albertel 6698:        maxquest     - the number of the last bubble line that was parsed
                   6699: 
                   6700:        (<number> starts at 1)
                   6701:        <number>.answer - zero or more letters representing the selected
                   6702:                          letters from the scanline for the bubble line 
                   6703:                          <number>.
                   6704:                          if blank there was either no bubble or there where
                   6705:                          multiple bubbles, (consult the keys missingerror and
                   6706:                          doubleerror if this is an error condition)
                   6707: 
                   6708: =cut
                   6709: 
1.82      albertel 6710: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6711:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6712:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6713:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6714: 
1.82      albertel 6715:     my %record;
1.596.2.12.2.  6(raebur 6716:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6717:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6718: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6719: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6720: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6721: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6722: 	    $record{'scantron.CODE'}=substr($data,
                   6723: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6724: 					    $$scantron_config{'CODElength'});
1.191     albertel 6725: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6726: 		$record{'scantron.useCODE'}=1;
                   6727: 	    }
1.192     albertel 6728: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6729: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6730: 	    }
1.82      albertel 6731: 	} else {
                   6732: 	    #FIXME interpret first N questions
                   6733: 	}
                   6734:     }
1.83      albertel 6735:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6736: 				  $$scantron_config{'IDlength'});
1.157     albertel 6737:     $record{'scantron.PaperID'}=
                   6738: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6739: 	       $$scantron_config{'PaperIDlength'});
                   6740:     $record{'scantron.FirstName'}=
                   6741: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6742: 	       $$scantron_config{'FirstNamelength'});
                   6743:     $record{'scantron.LastName'}=
                   6744: 	substr($data,$$scantron_config{'LastName'}-1,
                   6745: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6746:     if ($just_header) { return \%record; }
1.194     albertel 6747: 
1.82      albertel 6748:     my @alphabet=('A'..'Z');
                   6749:     my $questnum=0;
1.447     foxr     6750:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6751: 
1.596.2.12.2.  6(raebur 6752:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6753:3):     if ($randompick || $randomorder) {
                   6754:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6755:3):                                          $master_seq,$symb_to_resource,
                   6756:3):                                          $partids_by_symb,$orderedforcode,
                   6757:3):                                          $respnumlookup,$startline);
                   6758:3):         if ($total) {
                   6759:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6760:3):         }
                   6761:3):         if (ref($totalref)) {
                   6762:3):             $$totalref = $total;
                   6763:3):         }
                   6764:3):     }
                   6765:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6766:     chomp($questions);		# Get rid of any trailing \n.
                   6767:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6768:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6769:3):         my $answers_needed;
                   6770:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6771:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6772:3):         } else {
                   6773:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6774:3):         }
1.503     raeburn  6775:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6776:                              || 1;
                   6777:         $questnum++;
                   6778:         my $quest_id = $questnum;
                   6779:         my $currentquest = substr($questions,0,$answer_length);
                   6780:         $questions       = substr($questions,$answer_length);
                   6781:         if (length($currentquest) < $answer_length) { next; }
                   6782: 
1.596.2.12.2.  6(raebur 6783:3):         my $subdivided;
                   6784:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6785:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6786:3):         } else {
                   6787:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6788:3):         }
                   6789:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6790:             my $subquestnum = 1;
                   6791:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6792:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6793:             foreach my $subans (@subanswers_needed) {
                   6794:                 my $subans_length =
                   6795:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6796:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6797:                 $subquestions   = substr($subquestions,$subans_length);
                   6798:                 $quest_id = "$questnum.$subquestnum";
                   6799:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6800:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6801:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6802:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6803:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6804:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6805:                 } else {
                   6806:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6807:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6808:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6809:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6810:                 }
                   6811:                 $subquestnum ++;
                   6812:             }
                   6813:         } else {
                   6814:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6815:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6816:                 $ansnum = &scantron_validator_lettnum($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:             } else {
                   6821:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6822:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6823:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6824:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6825:             }
                   6826:         }
                   6827:     }
                   6828:     $record{'scantron.maxquest'}=$questnum;
                   6829:     return \%record;
                   6830: }
1.447     foxr     6831: 
1.596.2.12.2.  6(raebur 6832:3): sub get_master_seq {
          0(raebur 6833:2):     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
          6(raebur 6834:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6835:3):                    (ref($symb_to_resource) eq 'HASH'));
          0(raebur 6836:2):     if ($need_symb_in_map) {
                   6837:2):         return unless (ref($symb_for_examcode) eq 'HASH');
                   6838:2):     }
          6(raebur 6839:3):     my $resource_error;
                   6840:3):     foreach my $resource (@{$resources}) {
                   6841:3):         my $ressymb;
                   6842:3):         if (ref($resource)) {
                   6843:3):             $ressymb = $resource->symb();
                   6844:3):             push(@{$master_seq},$ressymb);
                   6845:3):             $symb_to_resource->{$ressymb} = $resource;
          0(raebur 6846:2):             if ($need_symb_in_map) {
                   6847:2):                 unless ($resource->is_map()) {
                   6848:2):                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6849:2):                     unless (exists($symb_for_examcode->{$map})) {
                   6850:2):                         $symb_for_examcode->{$map} = $ressymb;
                   6851:2):                     }
                   6852:2):                 }
                   6853:2):             }
          6(raebur 6854:3):         } else {
                   6855:3):             $resource_error = 1;
                   6856:3):             last;
                   6857:3):         }
                   6858:3):     }
                   6859:3):     return $resource_error;
                   6860:3): }
                   6861:3): 
                   6862:3): sub get_respnum_lookups {
                   6863:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6864:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6865:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6866:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6867:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6868:3):                    (ref($startline) eq 'HASH'));
                   6869:3):     my ($user,$scancode);
                   6870:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6871:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6872:3):         $scancode = $record->{'scantron.CODE'};
                   6873:3):     } else {
                   6874:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6875:3):     }
                   6876:3):     my @mapresources =
                   6877:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6878:3):                      $orderedforcode);
                   6879:3):     my $total = 0;
                   6880:3):     my $count = 0;
                   6881:3):     foreach my $resource (@mapresources) {
                   6882:3):         my $id = $resource->id();
                   6883:3):         my $symb = $resource->symb();
                   6884:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6885:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6886:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6887:3):                 if ($respnum ne '') {
                   6888:3):                     $respnumlookup->{$count} = $respnum;
                   6889:3):                     $startline->{$count} = $total;
                   6890:3):                     $total += $bubble_lines_per_response{$respnum};
                   6891:3):                     $count ++;
                   6892:3):                 }
                   6893:3):             }
                   6894:3):         }
                   6895:3):     }
                   6896:3):     return $total;
                   6897:3): }
                   6898:3): 
1.503     raeburn  6899: sub scantron_validator_lettnum {
                   6900:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6901:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6902:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6903: 
                   6904:     # Qon 'letter' implies for each slot in currquest we have:
                   6905:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6906:     #    about anything else (esp. a value of Qoff) for missing
                   6907:     #    bubbles.
                   6908:     #
                   6909:     # Qon 'number' implies each slot gives a digit that indexes the
                   6910:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6911:     #    and * or ? for double bubbles on a single line.
                   6912:     #
1.447     foxr     6913: 
1.503     raeburn  6914:     my $matchon;
                   6915:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6916:         $matchon = '[A-Z]';
                   6917:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6918:         $matchon = '\d';
                   6919:     }
                   6920:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6921:3):     my $responsenum = $questnum-1;
                   6922:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6923:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6924:3):     }
                   6925:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6926:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6927:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6928:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6929:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6930:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6931:         my @singlelines = split('',$currquest);
                   6932:         foreach my $entry (@singlelines) {
                   6933:             $occurrences = &occurence_count($entry,$matchon);
                   6934:             if ($occurrences > 1) {
                   6935:                 last;
                   6936:             }
1.596.2.12.2.  6(raebur 6937:3):         }
1.503     raeburn  6938:     } else {
                   6939:         $occurrences = &occurence_count($currquest,$matchon); 
                   6940:     }
                   6941:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6942:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6943:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6944:             my $bubble = substr($currquest,$ans,1);
                   6945:             if ($bubble =~ /$matchon/ ) {
                   6946:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6947:                     if ($bubble == 0) {
                   6948:                         $bubble = 10; 
                   6949:                     }
                   6950:                     $record->{"scantron.$ansnum.answer"} = 
                   6951:                         $alphabet->[$bubble-1];
                   6952:                 } else {
                   6953:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6954:                 }
                   6955:             } else {
                   6956:                 $record->{"scantron.$ansnum.answer"}='';
                   6957:             }
                   6958:             $ansnum++;
                   6959:         }
                   6960:     } elsif (!defined($currquest)
                   6961:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6962:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6963:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6964:             $record->{"scantron.$ansnum.answer"}='';
                   6965:             $ansnum++;
                   6966:         }
                   6967:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6968:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6969:         }
                   6970:     } else {
                   6971:         if ($$scantron_config{'Qon'} eq 'number') {
                   6972:             $currquest = &digits_to_letters($currquest);            
                   6973:         }
                   6974:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6975:             my $bubble = substr($currquest,$ans,1);
                   6976:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6977:             $ansnum++;
                   6978:         }
                   6979:     }
                   6980:     return $ansnum;
                   6981: }
1.447     foxr     6982: 
1.503     raeburn  6983: sub scantron_validator_positional {
                   6984:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6985:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6986:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6987: 
1.503     raeburn  6988:     # Otherwise there's a positional notation;
                   6989:     # each bubble line requires Qlength items, and there are filled in
                   6990:     # bubbles for each case where there 'Qon' characters.
                   6991:     #
1.447     foxr     6992: 
1.503     raeburn  6993:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6994: 
1.503     raeburn  6995:     # If the split only gives us one element.. the full length of the
                   6996:     # answer string, no bubbles are filled in:
1.447     foxr     6997: 
1.507     raeburn  6998:     if ($answers_needed eq '') {
                   6999:         return;
                   7000:     }
                   7001: 
1.503     raeburn  7002:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   7003:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   7004:             $record->{"scantron.$ansnum.answer"}='';
                   7005:             $ansnum++;
                   7006:         }
                   7007:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   7008:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   7009:         }
                   7010:     } elsif (scalar(@array) == 2) {
                   7011:         my $location = length($array[0]);
                   7012:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   7013:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   7014:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7015:             if ($ans eq $line_num) {
                   7016:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   7017:             } else {
                   7018:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   7019:             }
                   7020:             $ansnum++;
                   7021:          }
                   7022:     } else {
                   7023:         #  If there's more than one instance of a bubble character
                   7024:         #  That's a double bubble; with positional notation we can
                   7025:         #  record all the bubbles filled in as well as the
                   7026:         #  fact this response consists of multiple bubbles.
                   7027:         #
1.596.2.12.2.  6(raebur 7028:3):         my $responsenum = $questnum-1;
                   7029:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7030:3):             $responsenum = $respnumlookup->{$questnum-1}
                   7031:3):         }
                   7032:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7033:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7034:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7035:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7036:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7037:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  7038:             my $doubleerror = 0;
                   7039:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   7040:                    (!$doubleerror)) {
                   7041:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   7042:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   7043:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   7044:                if (length(@currarray) > 2) {
                   7045:                    $doubleerror = 1;
                   7046:                } 
                   7047:             }
                   7048:             if ($doubleerror) {
                   7049:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7050:             }
                   7051:         } else {
                   7052:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7053:         }
                   7054:         my $item = $ansnum;
                   7055:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7056:             $record->{"scantron.$item.answer"} = '';
                   7057:             $item ++;
                   7058:         }
1.447     foxr     7059: 
1.503     raeburn  7060:         my @ans=@array;
                   7061:         my $i=0;
                   7062:         my $increment = 0;
                   7063:         while ($#ans) {
                   7064:             $i+=length($ans[0]) + $increment;
                   7065:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   7066:             my $bubble = $i%$$scantron_config{'Qlength'};
                   7067:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   7068:             shift(@ans);
                   7069:             $increment = 1;
                   7070:         }
                   7071:         $ansnum += $answers_needed;
1.82      albertel 7072:     }
1.503     raeburn  7073:     return $ansnum;
1.82      albertel 7074: }
                   7075: 
1.423     albertel 7076: =pod
                   7077: 
                   7078: =item scantron_add_delay
                   7079: 
                   7080:    Adds an error message that occurred during the grading phase to a
                   7081:    queue of messages to be shown after grading pass is complete
                   7082: 
                   7083:  Arguments:
1.424     albertel 7084:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 7085:    $scanline    - the scanline that caused the error
                   7086:    $errormesage - the error message
                   7087:    $errorcode   - a numeric code for the error
                   7088: 
                   7089:  Side Effects:
1.424     albertel 7090:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 7091: 
                   7092: =cut
                   7093: 
1.82      albertel 7094: sub scantron_add_delay {
1.140     albertel 7095:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   7096:     push(@$delayqueue,
                   7097: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   7098: 	  'ecode' => $errorcode }
                   7099: 	 );
1.82      albertel 7100: }
                   7101: 
1.423     albertel 7102: =pod
                   7103: 
                   7104: =item scantron_find_student
                   7105: 
1.424     albertel 7106:    Finds the username for the current scanline
                   7107: 
                   7108:   Arguments:
                   7109:    $scantron_record - hash result from scantron_parse_scanline
                   7110:    $scan_data       - hash of correction information 
                   7111:                       (see &scantron_getfile() form more information)
                   7112:    $idmap           - hash from &username_to_idmap()
                   7113:    $line            - number of current scanline
                   7114:  
                   7115:   Returns:
                   7116:    Either 'username:domain' or undef if unknown
                   7117: 
1.423     albertel 7118: =cut
                   7119: 
1.82      albertel 7120: sub scantron_find_student {
1.157     albertel 7121:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7122:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7123:     if ($scanID =~ /^\s*$/) {
                   7124:  	return &scan_data($scan_data,"$line.user");
                   7125:     }
1.83      albertel 7126:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7127:  	if (lc($id) eq lc($scanID)) {
                   7128:  	    return $$idmap{$id};
                   7129:  	}
1.83      albertel 7130:     }
                   7131:     return undef;
                   7132: }
                   7133: 
1.423     albertel 7134: =pod
                   7135: 
                   7136: =item scantron_filter
                   7137: 
1.424     albertel 7138:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7139:    hidden resources was selected
                   7140: 
1.423     albertel 7141: =cut
                   7142: 
1.83      albertel 7143: sub scantron_filter {
                   7144:     my ($curres)=@_;
1.331     albertel 7145: 
                   7146:     if (ref($curres) && $curres->is_problem()) {
                   7147: 	# if the user has asked to not have either hidden
                   7148: 	# or 'randomout' controlled resources to be graded
                   7149: 	# don't include them
                   7150: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7151: 	    && $curres->randomout) {
                   7152: 	    return 0;
                   7153: 	}
1.83      albertel 7154: 	return 1;
                   7155:     }
                   7156:     return 0;
1.82      albertel 7157: }
                   7158: 
1.423     albertel 7159: =pod
                   7160: 
                   7161: =item scantron_process_corrections
                   7162: 
1.424     albertel 7163:    Gets correction information out of submitted form data and corrects
                   7164:    the scanline
                   7165: 
1.423     albertel 7166: =cut
                   7167: 
1.157     albertel 7168: sub scantron_process_corrections {
                   7169:     my ($r) = @_;
1.596.2.12.2.  9(raebur 7170:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7171:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7172:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7173:     my $which=$env{'form.scantron_line'};
1.200     albertel 7174:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7175:     my ($skip,$err,$errmsg);
1.257     albertel 7176:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7177: 	$skip=1;
1.257     albertel 7178:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7179: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7180: 	    $env{'form.scantron_domain'};
1.157     albertel 7181: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7182: 	($line,$err,$errmsg)=
                   7183: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7184: 				     'ID',{'newid'=>$newid,
1.257     albertel 7185: 				    'username'=>$env{'form.scantron_username'},
                   7186: 				    'domain'=>$env{'form.scantron_domain'}});
                   7187:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7188: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7189: 	my $newCODE;
1.192     albertel 7190: 	my %args;
1.190     albertel 7191: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7192: 	    $newCODE='use_unfound';
1.190     albertel 7193: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7194: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7195: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7196: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7197: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7198: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7199: 	}
1.257     albertel 7200: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7201: 	    $args{'CODE_ignore_dup'}=1;
                   7202: 	}
                   7203: 	$args{'CODE'}=$newCODE;
1.186     albertel 7204: 	($line,$err,$errmsg)=
                   7205: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7206: 				     'CODE',\%args);
1.257     albertel 7207:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7208: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7209: 	    ($line,$err,$errmsg)=
                   7210: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7211: 					 $which,'answer',
                   7212: 					 { 'question'=>$question,
1.503     raeburn  7213: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7214:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7215: 	    if ($err) { last; }
                   7216: 	}
                   7217:     }
                   7218:     if ($err) {
1.596.2.12.2.  0(raebur 7219:3): 	$r->print(
                   7220:3):             '<p class="LC_error">'
                   7221:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7222:3):                 $errmsg)
          1(raebur 7223:3):            .'</p>');
1.157     albertel 7224:     } else {
1.200     albertel 7225: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7226: 	&scantron_putfile($scanlines,$scan_data);
                   7227:     }
                   7228: }
                   7229: 
1.423     albertel 7230: =pod
                   7231: 
                   7232: =item reset_skipping_status
                   7233: 
1.424     albertel 7234:    Forgets the current set of remember skipped scanlines (and thus
                   7235:    reverts back to considering all lines in the
                   7236:    scantron_skipped_<filename> file)
                   7237: 
1.423     albertel 7238: =cut
                   7239: 
1.200     albertel 7240: sub reset_skipping_status {
                   7241:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7242:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7243:     &scantron_putfile(undef,$scan_data);
                   7244: }
                   7245: 
1.423     albertel 7246: =pod
                   7247: 
                   7248: =item start_skipping
                   7249: 
1.424     albertel 7250:    Marks a scanline to be skipped. 
                   7251: 
1.423     albertel 7252: =cut
                   7253: 
1.376     albertel 7254: sub start_skipping {
1.200     albertel 7255:     my ($scan_data,$i)=@_;
                   7256:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7257:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7258: 	$remembered{$i}=2;
                   7259:     } else {
                   7260: 	$remembered{$i}=1;
                   7261:     }
1.200     albertel 7262:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7263: }
                   7264: 
1.423     albertel 7265: =pod
                   7266: 
                   7267: =item should_be_skipped
                   7268: 
1.424     albertel 7269:    Checks whether a scanline should be skipped.
                   7270: 
1.423     albertel 7271: =cut
                   7272: 
1.200     albertel 7273: sub should_be_skipped {
1.376     albertel 7274:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7275:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7276: 	# not redoing old skips
1.376     albertel 7277: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7278: 	return 0;
                   7279:     }
                   7280:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7281: 
                   7282:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7283: 	return 0;
                   7284:     }
1.200     albertel 7285:     return 1;
                   7286: }
                   7287: 
1.423     albertel 7288: =pod
                   7289: 
                   7290: =item remember_current_skipped
                   7291: 
1.424     albertel 7292:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7293:    file and remembers them into scan_data for later use.
                   7294: 
1.423     albertel 7295: =cut
                   7296: 
1.200     albertel 7297: sub remember_current_skipped {
                   7298:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7299:     my %to_remember;
                   7300:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7301: 	if ($scanlines->{'skipped'}[$i]) {
                   7302: 	    $to_remember{$i}=1;
                   7303: 	}
                   7304:     }
1.376     albertel 7305: 
1.200     albertel 7306:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7307:     &scantron_putfile(undef,$scan_data);
                   7308: }
                   7309: 
1.423     albertel 7310: =pod
                   7311: 
                   7312: =item check_for_error
                   7313: 
1.424     albertel 7314:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7315:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7316:     something went wrong.
                   7317: 
1.423     albertel 7318: =cut
                   7319: 
1.200     albertel 7320: sub check_for_error {
                   7321:     my ($r,$result)=@_;
                   7322:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7323: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7324:     }
                   7325: }
1.157     albertel 7326: 
1.423     albertel 7327: =pod
                   7328: 
                   7329: =item scantron_warning_screen
                   7330: 
1.424     albertel 7331:    Interstitial screen to make sure the operator has selected the
                   7332:    correct options before we start the validation phase.
                   7333: 
1.423     albertel 7334: =cut
                   7335: 
1.203     albertel 7336: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7337:0):     my ($button_text,$symb)=@_;
1.257     albertel 7338:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7339:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7340:     my $CODElist;
1.284     albertel 7341:     if ($scantron_config{'CODElocation'} &&
                   7342: 	$scantron_config{'CODEstart'} &&
                   7343: 	$scantron_config{'CODElength'}) {
                   7344: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7345:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7346: 	$CODElist=
1.492     albertel 7347: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7348: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7349:     }
1.596.2.12.2.  (raeburn 7350:):     my $lastbubblepoints;
                   7351:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7352:):         $lastbubblepoints =
                   7353:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7354:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7355:):     }
1.492     albertel 7356:     return ('
1.203     albertel 7357: <p>
1.492     albertel 7358: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7359:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7360: </p>
                   7361: <table>
1.492     albertel 7362: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7363: <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 7364:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7365: </table>
1.596.2.12.2.  1(raebur 7366:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7367: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 7368: 
                   7369: <br />
1.492     albertel 7370: ');
1.203     albertel 7371: }
                   7372: 
1.423     albertel 7373: =pod
                   7374: 
                   7375: =item scantron_do_warning
                   7376: 
1.424     albertel 7377:    Check if the operator has picked something for all required
                   7378:    fields. Error out if something is missing.
                   7379: 
1.423     albertel 7380: =cut
                   7381: 
1.203     albertel 7382: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7383:0):     my ($r,$symb)=@_;
1.203     albertel 7384:     if (!$symb) {return '';}
1.324     albertel 7385:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7386:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7387:     if ( $env{'form.selectpage'} eq '' ||
                   7388: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7389: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7390: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7391: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7392: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7393: 	} 
1.257     albertel 7394: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7395: 	    $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 7396: 	} 
1.257     albertel 7397: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7398: 	    $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 7399: 	} 
                   7400:     } else {
1.596.2.12.2.  1(raebur 7401:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7402:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7403: 	$r->print('
1.596.2.12.2.  (raeburn 7404:): '.$warning.$bubbledbyhand.'
1.492     albertel 7405: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7406: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7407: ');
1.237     albertel 7408:     }
1.596.2.12.2.  1(raebur 7409:0):     $r->print("</form><br />");
1.203     albertel 7410:     return '';
                   7411: }
                   7412: 
1.423     albertel 7413: =pod
                   7414: 
                   7415: =item scantron_form_start
                   7416: 
1.424     albertel 7417:     html hidden input for remembering all selected grading options
                   7418: 
1.423     albertel 7419: =cut
                   7420: 
1.203     albertel 7421: sub scantron_form_start {
                   7422:     my ($max_bubble)=@_;
                   7423:     my $result= <<SCANTRONFORM;
                   7424: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7425:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7426:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7427:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7428:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7429:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7430:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7431:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7432:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7433:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7434: SCANTRONFORM
1.447     foxr     7435: 
                   7436:   my $line = 0;
                   7437:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7438:        my $chunk =
                   7439: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7440:        $chunk .=
                   7441: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7442:        $chunk .= 
                   7443:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7444:        $chunk .=
                   7445:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7446:3):        $chunk .=
                   7447:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7448:        $result .= $chunk;
                   7449:        $line++;
1.596.2.12.2.  6(raebur 7450:3):     }
1.203     albertel 7451:     return $result;
                   7452: }
                   7453: 
1.423     albertel 7454: =pod
                   7455: 
                   7456: =item scantron_validate_file
                   7457: 
1.596.2.6  raeburn  7458:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7459: 
                   7460:     Also processes any necessary information resets that need to
                   7461:     occur before validation begins (ignore previous corrections,
                   7462:     restarting the skipped records processing)
                   7463: 
1.423     albertel 7464: =cut
                   7465: 
1.157     albertel 7466: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7467:0):     my ($r,$symb) = @_;
1.157     albertel 7468:     if (!$symb) {return '';}
1.324     albertel 7469:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7470:     
1.596.2.12.2.  0(raebur 7471:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7472:     # them when doing the corrections reset
1.257     albertel 7473:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7474: 	&reset_skipping_status();
                   7475:     }
1.257     albertel 7476:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7477: 	&remember_current_skipped();
1.257     albertel 7478: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7479:     }
                   7480: 
1.257     albertel 7481:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7482: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7483: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7484: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7485: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7486:     }
1.200     albertel 7487: 
1.257     albertel 7488:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7489: 	&scantron_process_corrections($r);
                   7490:     }
1.503     raeburn  7491:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7492:     #get the student pick code ready
                   7493:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7494:     my $nav_error;
1.596.2.12.2.  9(raebur 7495:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7496:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7497:     if ($nav_error) {
                   7498:         $r->print(&navmap_errormsg());
                   7499:         return '';
                   7500:     }
1.203     albertel 7501:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7502:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7503:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7504:):     }
1.157     albertel 7505:     $r->print($result);
                   7506:     
1.334     albertel 7507:     my @validate_phases=( 'sequence',
                   7508: 			  'ID',
1.157     albertel 7509: 			  'CODE',
                   7510: 			  'doublebubble',
                   7511: 			  'missingbubbles');
1.257     albertel 7512:     if (!$env{'form.validatepass'}) {
                   7513: 	$env{'form.validatepass'} = 0;
1.157     albertel 7514:     }
1.257     albertel 7515:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7516: 
1.448     foxr     7517: 
1.157     albertel 7518:     my $stop=0;
                   7519:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7520: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7521: 	$r->rflush();
1.596.2.12.2.  6(raebur 7522:3): 
1.157     albertel 7523: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7524: 	{
                   7525: 	    no strict 'refs';
                   7526: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7527: 	}
                   7528:     }
                   7529:     if (!$stop) {
1.596.2.12.2.  1(raebur 7530:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7531: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7532:                   $warning.
                   7533:                   &mt('Perform verification for each student after storage of submissions?').
                   7534:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7535:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7536:                   ('&nbsp;'x3).'<label>'.
                   7537:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7538:                   '</label></span><br />'.
                   7539:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7540:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7541:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7542:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7543:     } else {
                   7544: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7545: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7546:     }
                   7547:     if ($stop) {
1.334     albertel 7548: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7549: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7550: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7551: 
1.596.2.12.2.  1(raebur 7552: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 7553: 	} else {
1.503     raeburn  7554:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7555: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7556:             } else {
1.539     riegler  7557:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7558:             }
1.492     albertel 7559: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7560: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7561: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7562: 	}
1.157     albertel 7563:     }
1.596.2.12.2.  1(raebur 7564:0):     $r->print(" </form><br />");
1.157     albertel 7565:     return '';
                   7566: }
                   7567: 
1.423     albertel 7568: 
                   7569: =pod
                   7570: 
                   7571: =item scantron_remove_file
                   7572: 
1.596.2.6  raeburn  7573:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7574:    scantron_original_<filename> is never removed
                   7575: 
                   7576: 
1.423     albertel 7577: =cut
                   7578: 
1.200     albertel 7579: sub scantron_remove_file {
1.192     albertel 7580:     my ($which)=@_;
1.257     albertel 7581:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7582:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7583:     my $file='scantron_';
1.200     albertel 7584:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7585: 	$file.=$which.'_';
1.192     albertel 7586:     } else {
                   7587: 	return 'refused';
                   7588:     }
1.257     albertel 7589:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7590:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7591: }
                   7592: 
1.423     albertel 7593: 
                   7594: =pod
                   7595: 
                   7596: =item scantron_remove_scan_data
                   7597: 
1.596.2.6  raeburn  7598:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7599:    data file.  (In the case that both the are doing skipped records we need
                   7600:    to remember the old skipped lines for the time being so that element
                   7601:    persists for a while.)
                   7602: 
1.423     albertel 7603: =cut
                   7604: 
1.200     albertel 7605: sub scantron_remove_scan_data {
1.257     albertel 7606:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7607:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7608:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7609:     my @todelete;
1.257     albertel 7610:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7611:     foreach my $key (@keys) {
                   7612: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7613: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7614: 		$key=~/remember_skipping/) {
                   7615: 		next;
                   7616: 	    }
1.192     albertel 7617: 	    push(@todelete,$key);
                   7618: 	}
                   7619:     }
1.200     albertel 7620:     my $result;
1.192     albertel 7621:     if (@todelete) {
1.491     albertel 7622: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7623: 				       \@todelete,$cdom,$cname);
                   7624:     } else {
                   7625: 	$result = 'ok';
1.192     albertel 7626:     }
                   7627:     return $result;
                   7628: }
                   7629: 
1.423     albertel 7630: 
                   7631: =pod
                   7632: 
                   7633: =item scantron_getfile
                   7634: 
1.596.2.6  raeburn  7635:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7636:     the scan_data hash
                   7637:   
                   7638:   Arguments:
                   7639:     None
                   7640: 
                   7641:   Returns:
                   7642:     2 hash references
                   7643: 
                   7644:      - first one has 
                   7645:          orig      -
                   7646:          corrected -
                   7647:          skipped   -  each of which points to an array ref of the specified
                   7648:                       file broken up into individual lines
                   7649:          count     - number of scanlines
                   7650:  
                   7651:      - second is the scan_data hash possible keys are
1.425     albertel 7652:        ($number refers to scanline numbered $number and thus the key affects
                   7653:         only that scanline
                   7654:         $bubline refers to the specific bubble line element and the aspects
                   7655:         refers to that specific bubble line element)
                   7656: 
                   7657:        $number.user - username:domain to use
                   7658:        $number.CODE_ignore_dup 
                   7659:                     - ignore the duplicate CODE error 
                   7660:        $number.useCODE
                   7661:                     - use the CODE in the scanline as is
                   7662:        $number.no_bubble.$bubline
                   7663:                     - it is valid that there is no bubbled in bubble
                   7664:                       at $number $bubline
                   7665:        remember_skipping
                   7666:                     - a frozen hash containing keys of $number and values
                   7667:                       of either 
                   7668:                         1 - we are on a 'do skipped records pass' and plan
                   7669:                             on processing this line
                   7670:                         2 - we are on a 'do skipped records pass' and this
                   7671:                             scanline has been marked to skip yet again
1.424     albertel 7672: 
1.423     albertel 7673: =cut
                   7674: 
1.157     albertel 7675: sub scantron_getfile {
1.200     albertel 7676:     #FIXME really would prefer a scantron directory
1.257     albertel 7677:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7678:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7679:     my $lines;
                   7680:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7681: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7682:     my %scanlines;
                   7683:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7684:     my $temp=$scanlines{'orig'};
                   7685:     $scanlines{'count'}=$#$temp;
                   7686: 
                   7687:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7688: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7689:     if ($lines eq '-1') {
                   7690: 	$scanlines{'corrected'}=[];
                   7691:     } else {
                   7692: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7693:     }
                   7694:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7695: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7696:     if ($lines eq '-1') {
                   7697: 	$scanlines{'skipped'}=[];
                   7698:     } else {
                   7699: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7700:     }
1.175     albertel 7701:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7702:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7703:     my %scan_data = @tmp;
                   7704:     return (\%scanlines,\%scan_data);
                   7705: }
                   7706: 
1.423     albertel 7707: =pod
                   7708: 
                   7709: =item lonnet_putfile
                   7710: 
1.424     albertel 7711:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7712: 
                   7713:  Arguments:
                   7714:    $contents - data to store
                   7715:    $filename - filename to store $contents into
                   7716: 
                   7717:  Returns:
                   7718:    result value from &Apache::lonnet::finishuserfileupload
                   7719: 
1.423     albertel 7720: =cut
                   7721: 
1.157     albertel 7722: sub lonnet_putfile {
                   7723:     my ($contents,$filename)=@_;
1.257     albertel 7724:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7725:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7726:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7727:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7728: 
                   7729: }
                   7730: 
1.423     albertel 7731: =pod
                   7732: 
                   7733: =item scantron_putfile
                   7734: 
1.596.2.6  raeburn  7735:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7736:     scan_data hash. (Does not modify the original version only the
                   7737:     corrected and skipped versions.
                   7738: 
                   7739:  Arguments:
                   7740:     $scanlines - hash ref that looks like the first return value from
                   7741:                  &scantron_getfile()
                   7742:     $scan_data - hash ref that looks like the second return value from
                   7743:                  &scantron_getfile()
                   7744: 
1.423     albertel 7745: =cut
                   7746: 
1.157     albertel 7747: sub scantron_putfile {
                   7748:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7749:     #FIXME really would prefer a scantron directory
1.257     albertel 7750:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7751:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7752:     if ($scanlines) {
                   7753: 	my $prefix='scantron_';
1.157     albertel 7754: # no need to update orig, shouldn't change
                   7755: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7756: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7757: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7758: 			$prefix.'corrected_'.
1.257     albertel 7759: 			$env{'form.scantron_selectfile'});
1.200     albertel 7760: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7761: 			$prefix.'skipped_'.
1.257     albertel 7762: 			$env{'form.scantron_selectfile'});
1.200     albertel 7763:     }
1.175     albertel 7764:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7765: }
                   7766: 
1.423     albertel 7767: =pod
                   7768: 
                   7769: =item scantron_get_line
                   7770: 
1.424     albertel 7771:    Returns the correct version of the scanline
                   7772: 
                   7773:  Arguments:
                   7774:     $scanlines - hash ref that looks like the first return value from
                   7775:                  &scantron_getfile()
                   7776:     $scan_data - hash ref that looks like the second return value from
                   7777:                  &scantron_getfile()
                   7778:     $i         - number of the requested line (starts at 0)
                   7779: 
                   7780:  Returns:
                   7781:    A scanline, (either the original or the corrected one if it
                   7782:    exists), or undef if the requested scanline should be
                   7783:    skipped. (Either because it's an skipped scanline, or it's an
                   7784:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7785:    pass.
                   7786: 
1.423     albertel 7787: =cut
                   7788: 
1.157     albertel 7789: sub scantron_get_line {
1.200     albertel 7790:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7791:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7792:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7793:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7794:     return $scanlines->{'orig'}[$i]; 
                   7795: }
                   7796: 
1.423     albertel 7797: =pod
                   7798: 
                   7799: =item scantron_todo_count
                   7800: 
1.424     albertel 7801:     Counts the number of scanlines that need processing.
                   7802: 
                   7803:  Arguments:
                   7804:     $scanlines - hash ref that looks like the first return value from
                   7805:                  &scantron_getfile()
                   7806:     $scan_data - hash ref that looks like the second return value from
                   7807:                  &scantron_getfile()
                   7808: 
                   7809:  Returns:
                   7810:     $count - number of scanlines to process
                   7811: 
1.423     albertel 7812: =cut
                   7813: 
1.200     albertel 7814: sub get_todo_count {
                   7815:     my ($scanlines,$scan_data)=@_;
                   7816:     my $count=0;
                   7817:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7818: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7819: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7820: 	$count++;
                   7821:     }
                   7822:     return $count;
                   7823: }
                   7824: 
1.423     albertel 7825: =pod
                   7826: 
                   7827: =item scantron_put_line
                   7828: 
1.596.2.6  raeburn  7829:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7830:     data file.
                   7831: 
                   7832:  Arguments:
                   7833:     $scanlines - hash ref that looks like the first return value from
                   7834:                  &scantron_getfile()
                   7835:     $scan_data - hash ref that looks like the second return value from
                   7836:                  &scantron_getfile()
                   7837:     $i         - line number to update
                   7838:     $newline   - contents of the updated scanline
                   7839:     $skip      - if true make the line for skipping and update the
                   7840:                  'skipped' file
                   7841: 
1.423     albertel 7842: =cut
                   7843: 
1.157     albertel 7844: sub scantron_put_line {
1.200     albertel 7845:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7846:     if ($skip) {
                   7847: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7848: 	&start_skipping($scan_data,$i);
1.157     albertel 7849: 	return;
                   7850:     }
                   7851:     $scanlines->{'corrected'}[$i]=$newline;
                   7852: }
                   7853: 
1.423     albertel 7854: =pod
                   7855: 
                   7856: =item scantron_clear_skip
                   7857: 
1.424     albertel 7858:    Remove a line from the 'skipped' file
                   7859: 
                   7860:  Arguments:
                   7861:     $scanlines - hash ref that looks like the first return value from
                   7862:                  &scantron_getfile()
                   7863:     $scan_data - hash ref that looks like the second return value from
                   7864:                  &scantron_getfile()
                   7865:     $i         - line number to update
                   7866: 
1.423     albertel 7867: =cut
                   7868: 
1.376     albertel 7869: sub scantron_clear_skip {
                   7870:     my ($scanlines,$scan_data,$i)=@_;
                   7871:     if (exists($scanlines->{'skipped'}[$i])) {
                   7872: 	undef($scanlines->{'skipped'}[$i]);
                   7873: 	return 1;
                   7874:     }
                   7875:     return 0;
                   7876: }
                   7877: 
1.423     albertel 7878: =pod
                   7879: 
                   7880: =item scantron_filter_not_exam
                   7881: 
1.424     albertel 7882:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7883:    filter out resources that are not marked as 'exam' mode
                   7884: 
1.423     albertel 7885: =cut
                   7886: 
1.334     albertel 7887: sub scantron_filter_not_exam {
                   7888:     my ($curres)=@_;
                   7889:     
                   7890:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7891: 	# if the user has asked to not have either hidden
                   7892: 	# or 'randomout' controlled resources to be graded
                   7893: 	# don't include them
                   7894: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7895: 	    && $curres->randomout) {
                   7896: 	    return 0;
                   7897: 	}
                   7898: 	return 1;
                   7899:     }
                   7900:     return 0;
                   7901: }
                   7902: 
1.423     albertel 7903: =pod
                   7904: 
                   7905: =item scantron_validate_sequence
                   7906: 
1.424     albertel 7907:     Validates the selected sequence, checking for resource that are
                   7908:     not set to exam mode.
                   7909: 
1.423     albertel 7910: =cut
                   7911: 
1.334     albertel 7912: sub scantron_validate_sequence {
                   7913:     my ($r,$currentphase) = @_;
                   7914: 
                   7915:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7916:     unless (ref($navmap)) {
                   7917:         $r->print(&navmap_errormsg());
                   7918:         return (1,$currentphase);
                   7919:     }
1.334     albertel 7920:     my (undef,undef,$sequence)=
                   7921: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7922: 
                   7923:     my $map=$navmap->getResourceByUrl($sequence);
                   7924: 
                   7925:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7926:                                     value="ignore" />');
                   7927:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7928: 	my @resources=
                   7929: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7930: 	if (@resources) {
1.596.2.12.2.  0(raebur 7931:2): 	    $r->print('<p class="LC_warning">'
                   7932:2):                .&mt('Some resources in the sequence currently are not set to'
                   7933:2):                    .' exam mode. Grading these resources currently may not'
                   7934:2):                    .' work correctly.')
                   7935:2):                .'</p>'
                   7936:2):             );
1.334     albertel 7937: 	    return (1,$currentphase);
                   7938: 	}
                   7939:     }
                   7940: 
                   7941:     return (0,$currentphase+1);
                   7942: }
                   7943: 
1.423     albertel 7944: 
                   7945: 
1.157     albertel 7946: sub scantron_validate_ID {
                   7947:     my ($r,$currentphase) = @_;
                   7948:     
                   7949:     #get student info
                   7950:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7951:     my %idmap=&username_to_idmap($classlist);
                   7952: 
                   7953:     #get scantron line setup
1.596.2.12.2.  9(raebur 7954:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7955:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7956: 
                   7957:     my $nav_error;
1.596.2.12.2.  (raeburn 7958:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7959:     if ($nav_error) {
                   7960:         $r->print(&navmap_errormsg());
                   7961:         return(1,$currentphase);
                   7962:     }
1.157     albertel 7963: 
                   7964:     my %found=('ids'=>{},'usernames'=>{});
                   7965:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7966: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7967: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7968: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7969: 						 $scan_data);
                   7970: 	my $id=$$scan_record{'scantron.ID'};
                   7971: 	my $found;
                   7972: 	foreach my $checkid (keys(%idmap)) {
                   7973: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7974: 	}
                   7975: 	if ($found) {
                   7976: 	    my $username=$idmap{$found};
                   7977: 	    if ($found{'ids'}{$found}) {
                   7978: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7979: 					 $line,'duplicateID',$found);
1.194     albertel 7980: 		return(1,$currentphase);
1.157     albertel 7981: 	    } elsif ($found{'usernames'}{$username}) {
                   7982: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7983: 					 $line,'duplicateID',$username);
1.194     albertel 7984: 		return(1,$currentphase);
1.157     albertel 7985: 	    }
1.186     albertel 7986: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7987: 	    $found{'ids'}{$found}++;
                   7988: 	    $found{'usernames'}{$username}++;
                   7989: 	} else {
                   7990: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7991: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7992: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7993: 		    &scantron_get_correction($r,$i,$scan_record,
                   7994: 					     \%scantron_config,
                   7995: 					     $line,'duplicateID',$username);
1.194     albertel 7996: 		    return(1,$currentphase);
1.157     albertel 7997: 		} elsif (!defined($username)) {
                   7998: 		    &scantron_get_correction($r,$i,$scan_record,
                   7999: 					     \%scantron_config,
                   8000: 					     $line,'incorrectID');
1.194     albertel 8001: 		    return(1,$currentphase);
1.157     albertel 8002: 		}
                   8003: 		$found{'usernames'}{$username}++;
                   8004: 	    } else {
                   8005: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   8006: 					 $line,'incorrectID');
1.194     albertel 8007: 		return(1,$currentphase);
1.157     albertel 8008: 	    }
                   8009: 	}
                   8010:     }
                   8011: 
                   8012:     return (0,$currentphase+1);
                   8013: }
                   8014: 
1.423     albertel 8015: 
1.157     albertel 8016: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 8017:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   8018:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 8019: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 8020: #to show both the current line and the previous one and allow skipping
                   8021: #the previous one or the current one
                   8022: 
1.333     albertel 8023:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  8024:         $r->print(
                   8025:             '<p class="LC_warning">'
                   8026:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8027:                 "<b>$error</b>",
                   8028:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8029:            ."</p> \n");
1.157     albertel 8030:     } else {
1.596.2.6  raeburn  8031:         $r->print(
                   8032:             '<p class="LC_warning">'
                   8033:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8034:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8035:            ."</p> \n");
                   8036:     }
                   8037:     my $message =
                   8038:         '<p>'
                   8039:        .&mt('The ID on the form is [_1]',
                   8040:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8041:        .'<br />'
1.596.2.12  raeburn  8042:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  8043:             $$scan_record{'scantron.LastName'},
                   8044:             $$scan_record{'scantron.FirstName'})
                   8045:        .'</p>';
1.242     albertel 8046: 
1.157     albertel 8047:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8048:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8049:                            # Array populated for doublebubble or
                   8050:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8051:                            # to validate radio button checking   
                   8052: 
1.157     albertel 8053:     if ($error =~ /ID$/) {
1.186     albertel 8054: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  8055: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8056: 		      "</p>\n");
1.157     albertel 8057: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  8058: 	    $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 8059: 	}
1.242     albertel 8060: 	$r->print($message);
1.492     albertel 8061: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8062: 	$r->print("\n<ul><li> ");
                   8063: 	#FIXME it would be nice if this sent back the user ID and
                   8064: 	#could do partial userID matches
                   8065: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8066: 				       'scantron_username','scantron_domain'));
                   8067: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 8068:3): 	$r->print("\n:\n".
1.257     albertel 8069: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8070: 
                   8071: 	$r->print('</li>');
1.186     albertel 8072:     } elsif ($error =~ /CODE$/) {
                   8073: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  8074: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8075: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  8076: 	    $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 8077: 	}
1.596.2.6  raeburn  8078:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   8079:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8080:                  ."</p>\n");
1.242     albertel 8081: 	$r->print($message);
1.596.2.6  raeburn  8082: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8083: 	$r->print("\n<br /> ");
1.194     albertel 8084: 	my $i=0;
1.273     albertel 8085: 	if ($error eq 'incorrectCODE' 
                   8086: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8087: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8088: 	    if ($closest > 0) {
                   8089: 		foreach my $testcode (@{$closest}) {
                   8090: 		    my $checked='';
1.569     bisitz   8091: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8092: 		    $r->print("
                   8093:    <label>
1.569     bisitz   8094:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8095:        ".&mt("Use the similar CODE [_1] instead.",
                   8096: 	    "<b><tt>".$testcode."</tt></b>")."
                   8097:     </label>
                   8098:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8099: 		    $r->print("\n<br />");
                   8100: 		    $i++;
                   8101: 		}
1.194     albertel 8102: 	    }
                   8103: 	}
1.273     albertel 8104: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8105: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8106: 	    $r->print("
                   8107:     <label>
1.569     bisitz   8108:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  8109:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8110: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8111:     </label>");
1.273     albertel 8112: 	    $r->print("\n<br />");
                   8113: 	}
1.194     albertel 8114: 
1.596.2.12.2.  1(raebur 8115:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8116: function change_radio(field) {
1.190     albertel 8117:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8118:     var i;
                   8119:     for (i=0;i<slct.length;i++) {
                   8120:         if (slct[i].value==field) { slct[i].checked=true; }
                   8121:     }
                   8122: }
                   8123: ENDSCRIPT
1.187     albertel 8124: 	my $href="/adm/pickcode?".
1.359     www      8125: 	   "form=".&escape("scantronupload").
                   8126: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8127: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8128: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8129: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8130: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8131: 	    $r->print("
                   8132:     <label>
                   8133:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8134:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8135: 	     "<a target='_blank' href='$href'>","</a>")."
                   8136:     </label> 
1.558     bisitz   8137:     ".&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 8138: 	    $r->print("\n<br />");
                   8139: 	}
1.492     albertel 8140: 	$r->print("
                   8141:     <label>
                   8142:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8143:        ".&mt("Use [_1] as the CODE.",
                   8144: 	     "</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 8145: 	$r->print("\n<br /><br />");
1.157     albertel 8146:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  8147: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8148: 
                   8149: 	# The form field scantron_questions is acutally a list of line numbers.
                   8150: 	# represented by this form so:
                   8151: 
1.596.2.12.2.  6(raebur 8152:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8153:3):                                                 $respnumlookup,$startline);
1.497     foxr     8154: 
1.157     albertel 8155: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8156: 		  $line_list.'" />');
1.242     albertel 8157: 	$r->print($message);
1.492     albertel 8158: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8159: 	foreach my $question (@{$arg}) {
1.503     raeburn  8160: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8161:3):                                                    $scan_record, $error,
                   8162:3):                                                    $randomorder,$randompick,
                   8163:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8164:             push(@lines_to_correct,@linenums);
1.157     albertel 8165: 	}
1.503     raeburn  8166:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8167:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  8168: 	$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 8169: 	$r->print($message);
1.492     albertel 8170: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8171: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8172: 
1.503     raeburn  8173: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8174: 	# a list of question numbers. Therefore:
                   8175: 	#
                   8176: 	
1.596.2.12.2.  6(raebur 8177:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8178:3):                                                 $respnumlookup,$startline);
1.497     foxr     8179: 
1.157     albertel 8180: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8181: 		  $line_list.'" />');
1.157     albertel 8182: 	foreach my $question (@{$arg}) {
1.503     raeburn  8183: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8184:3):                                                    $scan_record, $error,
                   8185:3):                                                    $randomorder,$randompick,
                   8186:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8187:             push(@lines_to_correct,@linenums);
1.157     albertel 8188: 	}
1.503     raeburn  8189:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8190:     } else {
                   8191: 	$r->print("\n<ul>");
                   8192:     }
                   8193:     $r->print("\n</li></ul>");
1.497     foxr     8194: }
                   8195: 
1.503     raeburn  8196: sub verify_bubbles_checked {
                   8197:     my (@ansnums) = @_;
                   8198:     my $ansnumstr = join('","',@ansnums);
                   8199:     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 8200:6):     &js_escape(\$warning);
          1(raebur 8201:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8202: function verify_bubble_radio(form) {
                   8203:     var ansnumArray = new Array ("$ansnumstr");
                   8204:     var need_bubble_count = 0;
                   8205:     for (var i=0; i<ansnumArray.length; i++) {
                   8206:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8207:             var bubble_picked = 0; 
                   8208:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8209:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8210:                     bubble_picked = 1;
                   8211:                 }
                   8212:             }
                   8213:             if (bubble_picked == 0) {
                   8214:                 need_bubble_count ++;
                   8215:             }
                   8216:         }
                   8217:     }
                   8218:     if (need_bubble_count) {
                   8219:         alert("$warning");
                   8220:         return;
                   8221:     }
                   8222:     form.submit(); 
                   8223: }
                   8224: ENDSCRIPT
                   8225:     return $output;
                   8226: }
                   8227: 
1.497     foxr     8228: =pod
                   8229: 
                   8230: =item  questions_to_line_list
1.157     albertel 8231: 
1.497     foxr     8232: Converts a list of questions into a string of comma separated
                   8233: line numbers in the answer sheet used by the questions.  This is
                   8234: used to fill in the scantron_questions form field.
                   8235: 
                   8236:   Arguments:
                   8237:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 8238:3):      randomorder  - True if randomorder in use.
                   8239:3):      randompick   - True if randompick in use.
                   8240:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8241:3):                      for current line to question number used for same question
                   8242:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   8243:3):      startline    - Reference to hash where key is question number (0 is first)
                   8244:3):                     and key is number of first bubble line for current student
                   8245:3):                     or code-based randompick and/or randomorder.
1.497     foxr     8246: 
                   8247: =cut
                   8248: 
                   8249: 
                   8250: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 8251:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8252:     my @lines;
                   8253: 
1.503     raeburn  8254:     foreach my $item (@{$questions}) {
                   8255:         my $question = $item;
                   8256:         my ($first,$count,$last);
                   8257:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8258:             $question = $1;
                   8259:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 8260:3):             my $responsenum = $question-1;
                   8261:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8262:3):                 $responsenum = $respnumlookup->{$question-1};
                   8263:3):                 if (ref($startline) eq 'HASH') {
                   8264:3):                     $first = $startline->{$question-1} + 1;
                   8265:3):                 }
                   8266:3):             } else {
                   8267:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8268:3):             }
          7(raebur 8269:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8270:             my $subcount = 1;
                   8271:             while ($subcount<$subquestion) {
                   8272:                 $first += $subans[$subcount-1];
                   8273:                 $subcount ++;
                   8274:             }
                   8275:             $count = $subans[$subquestion-1];
                   8276:         } else {
1.596.2.12.2.  7(raebur 8277:3):             my $responsenum = $question-1;
                   8278:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8279:3):                 $responsenum = $respnumlookup->{$question-1};
                   8280:3):                 if (ref($startline) eq 'HASH') {
                   8281:3):                     $first = $startline->{$question-1} + 1;
                   8282:3):                 }
                   8283:3):             } else {
                   8284:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8285:3):             }
                   8286:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8287:         }
1.506     raeburn  8288:         $last = $first+$count-1;
1.503     raeburn  8289:         push(@lines, ($first..$last));
1.497     foxr     8290:     }
                   8291:     return join(',', @lines);
                   8292: }
                   8293: 
                   8294: =pod 
                   8295: 
                   8296: =item prompt_for_corrections
                   8297: 
                   8298: Prompts for a potentially multiline correction to the
                   8299: user's bubbling (factors out common code from scantron_get_correction
                   8300: for multi and missing bubble cases).
                   8301: 
                   8302:  Arguments:
                   8303:    $r           - Apache request object.
                   8304:    $question    - The question number to prompt for.
                   8305:    $scan_config - The scantron file configuration hash.
                   8306:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8307:    $error       - Type of error
1.596.2.12.2.  7(raebur 8308:3):    $randomorder - True if randomorder in use.
                   8309:3):    $randompick  - True if randompick in use.
                   8310:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8311:3):                     for current line to question number used for same question
                   8312:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8313:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8314:3):                   and value is number of first bubble line for current student
                   8315:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8316: 
                   8317:  Implicit inputs:
                   8318:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8319:                                   Numbered from 0 (but question numbers are from
                   8320:                                   1.
                   8321:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8322:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8323:                                   type problems render as separate sub-questions, 
1.503     raeburn  8324:                                   in exam mode. This hash contains a 
                   8325:                                   comma-separated list of the lines per 
                   8326:                                   sub-question.
1.510     raeburn  8327:    %responsetype_per_response   - essayresponse, formularesponse,
                   8328:                                   stringresponse, imageresponse, reactionresponse,
                   8329:                                   and organicresponse type problem parts can have
1.503     raeburn  8330:                                   multiple lines per response if the weight
                   8331:                                   assigned exceeds 10.  In this case, only
                   8332:                                   one bubble per line is permitted, but more 
                   8333:                                   than one line might contain bubbles, e.g.
                   8334:                                   bubbling of: line 1 - J, line 2 - J, 
                   8335:                                   line 3 - B would assign 22 points.  
1.497     foxr     8336: 
                   8337: =cut
                   8338: 
                   8339: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8340:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8341:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8342:     my ($current_line,$lines);
                   8343:     my @linenums;
                   8344:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8345:3):     my ($first,$responsenum);
1.503     raeburn  8346:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8347:         $question = $1;
                   8348:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8349:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8350:3):             $responsenum = $respnumlookup->{$question-1};
                   8351:3):             if (ref($startline) eq 'HASH') {
                   8352:3):                 $first = $startline->{$question-1};
                   8353:3):             }
                   8354:3):         } else {
                   8355:3):             $responsenum = $question-1;
          7(raebur 8356:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8357:3):         }
                   8358:3):         $current_line = $first + 1 ;
                   8359:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8360:         my $subcount = 1;
                   8361:         while ($subcount<$subquestion) {
                   8362:             $current_line += $subans[$subcount-1];
                   8363:             $subcount ++;
                   8364:         }
                   8365:         $lines = $subans[$subquestion-1];
                   8366:     } else {
1.596.2.12.2.  6(raebur 8367:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8368:3):             $responsenum = $respnumlookup->{$question-1};
                   8369:3):             if (ref($startline) eq 'HASH') {
                   8370:3):                 $first = $startline->{$question-1};
                   8371:3):             }
                   8372:3):         } else {
                   8373:3):             $responsenum = $question-1;
                   8374:3):             $first = $first_bubble_line{$responsenum};
                   8375:3):         }
                   8376:3):         $current_line = $first + 1;
                   8377:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8378:     }
1.497     foxr     8379:     if ($lines > 1) {
1.503     raeburn  8380:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8381:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8382:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8383:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8384:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8385:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8386:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8387: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  8388:         } else {
                   8389:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8390:         }
1.497     foxr     8391:     }
                   8392:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8393:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8394:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8395: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8396:         push(@linenums,$current_line);
1.497     foxr     8397: 	$current_line++;
                   8398:     }
                   8399:     if ($lines > 1) {
                   8400: 	$r->print("<hr /><br />");
                   8401:     }
1.503     raeburn  8402:     return @linenums;
1.157     albertel 8403: }
1.423     albertel 8404: 
                   8405: =pod
                   8406: 
                   8407: =item scantron_bubble_selector
                   8408:   
                   8409:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8410:    possibly showing the existing the selected bubbles if known
1.423     albertel 8411: 
                   8412:  Arguments:
                   8413:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8414:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8415:     $line        - Number of the line being displayed.
1.503     raeburn  8416:     $questionnum - Question number (may include subquestion)
                   8417:     $error       - Type of error.
1.497     foxr     8418:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8419: 
                   8420: =cut
                   8421: 
1.157     albertel 8422: sub scantron_bubble_selector {
1.503     raeburn  8423:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8424:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8425: 
                   8426:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8427:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8428:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8429:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8430:):             $max=$$scan_config{'BubblesPerRow'};
                   8431:):             if (($scmode eq 'number') && ($max > 10)) {
                   8432:):                 $max = 10;
                   8433:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8434:):                 $max = 26;
                   8435:):             }
                   8436:):         } else {
                   8437:):             $max = 10;
                   8438:):         }
                   8439:):     }
1.274     albertel 8440: 
1.157     albertel 8441:     my @alphabet=('A'..'Z');
1.503     raeburn  8442:     $r->print(&Apache::loncommon::start_data_table().
                   8443:               &Apache::loncommon::start_data_table_row());
                   8444:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8445:     for (my $i=0;$i<$max+1;$i++) {
                   8446: 	$r->print("\n".'<td align="center">');
                   8447: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8448: 	else { $r->print('&nbsp;'); }
                   8449: 	$r->print('</td>');
                   8450:     }
1.503     raeburn  8451:     $r->print(&Apache::loncommon::end_data_table_row().
                   8452:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8453:     for (my $i=0;$i<$max;$i++) {
                   8454: 	$r->print("\n".
                   8455: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8456: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8457:     }
1.503     raeburn  8458:     my $nobub_checked = ' ';
                   8459:     if ($error eq 'missingbubble') {
                   8460:         $nobub_checked = ' checked = "checked" ';
                   8461:     }
                   8462:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8463: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8464:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8465:               $line.'" value="'.$questionnum.'" /></td>');
                   8466:     $r->print(&Apache::loncommon::end_data_table_row().
                   8467:               &Apache::loncommon::end_data_table());
1.157     albertel 8468: }
                   8469: 
1.423     albertel 8470: =pod
                   8471: 
                   8472: =item num_matches
                   8473: 
1.424     albertel 8474:    Counts the number of characters that are the same between the two arguments.
                   8475: 
                   8476:  Arguments:
                   8477:    $orig - CODE from the scanline
                   8478:    $code - CODE to match against
                   8479: 
                   8480:  Returns:
                   8481:    $count - integer count of the number of same characters between the
                   8482:             two arguments
                   8483: 
1.423     albertel 8484: =cut
                   8485: 
1.194     albertel 8486: sub num_matches {
                   8487:     my ($orig,$code) = @_;
                   8488:     my @code=split(//,$code);
                   8489:     my @orig=split(//,$orig);
                   8490:     my $same=0;
                   8491:     for (my $i=0;$i<scalar(@code);$i++) {
                   8492: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8493:     }
                   8494:     return $same;
                   8495: }
                   8496: 
1.423     albertel 8497: =pod
                   8498: 
                   8499: =item scantron_get_closely_matching_CODEs
                   8500: 
1.424     albertel 8501:    Cycles through all CODEs and finds the set that has the greatest
                   8502:    number of same characters as the provided CODE
                   8503: 
                   8504:  Arguments:
                   8505:    $allcodes - hash ref returned by &get_codes()
                   8506:    $CODE     - CODE from the current scanline
                   8507: 
                   8508:  Returns:
                   8509:    2 element list
                   8510:     - first elements is number of how closely matching the best fit is 
                   8511:       (5 means best set has 5 matching characters)
                   8512:     - second element is an arrary ref containing the set of valid CODEs
                   8513:       that best fit the passed in CODE
                   8514: 
1.423     albertel 8515: =cut
                   8516: 
1.194     albertel 8517: sub scantron_get_closely_matching_CODEs {
                   8518:     my ($allcodes,$CODE)=@_;
                   8519:     my @CODEs;
                   8520:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8521: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8522:     }
                   8523: 
                   8524:     return ($#CODEs,$CODEs[-1]);
                   8525: }
                   8526: 
1.423     albertel 8527: =pod
                   8528: 
                   8529: =item get_codes
                   8530: 
1.424     albertel 8531:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8532:    set of remembered CODEs.
                   8533: 
                   8534:  Arguments:
                   8535:   $old_name - name of the set of remembered CODEs
                   8536:   $cdom     - domain of the course
                   8537:   $cnum     - internal course name
                   8538: 
                   8539:  Returns:
                   8540:   %allcodes - keys are the valid CODEs, values are all 1
                   8541: 
1.423     albertel 8542: =cut
                   8543: 
1.194     albertel 8544: sub get_codes {
1.280     foxr     8545:     my ($old_name, $cdom, $cnum) = @_;
                   8546:     if (!$old_name) {
                   8547: 	$old_name=$env{'form.scantron_CODElist'};
                   8548:     }
                   8549:     if (!$cdom) {
                   8550: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8551:     }
                   8552:     if (!$cnum) {
                   8553: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8554:     }
1.278     albertel 8555:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8556: 				    $cdom,$cnum);
                   8557:     my %allcodes;
                   8558:     if ($result{"type\0$old_name"} eq 'number') {
                   8559: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8560:     } else {
                   8561: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8562:     }
1.194     albertel 8563:     return %allcodes;
                   8564: }
                   8565: 
1.423     albertel 8566: =pod
                   8567: 
                   8568: =item scantron_validate_CODE
                   8569: 
1.424     albertel 8570:    Validates all scanlines in the selected file to not have any
                   8571:    invalid or underspecified CODEs and that none of the codes are
                   8572:    duplicated if this was requested.
                   8573: 
1.423     albertel 8574: =cut
                   8575: 
1.157     albertel 8576: sub scantron_validate_CODE {
                   8577:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8578:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8579:     if ($scantron_config{'CODElocation'} &&
                   8580: 	$scantron_config{'CODEstart'} &&
                   8581: 	$scantron_config{'CODElength'}) {
1.257     albertel 8582: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8583: 	    &FIXME_blow_up()
                   8584: 	}
                   8585:     } else {
                   8586: 	return (0,$currentphase+1);
                   8587:     }
                   8588:     
                   8589:     my %usedCODEs;
                   8590: 
1.194     albertel 8591:     my %allcodes=&get_codes();
1.186     albertel 8592: 
1.582     raeburn  8593:     my $nav_error;
1.596.2.12.2.  (raeburn 8594:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8595:     if ($nav_error) {
                   8596:         $r->print(&navmap_errormsg());
                   8597:         return(1,$currentphase);
                   8598:     }
1.447     foxr     8599: 
1.186     albertel 8600:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8601:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8602: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8603: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8604: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8605: 						 $scan_data);
                   8606: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8607: 	my $error=0;
1.224     albertel 8608: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8609: 	    &scantron_get_correction($r,$i,$scan_record,
                   8610: 				     \%scantron_config,
                   8611: 				     $line,'incorrectCODE',\%allcodes);
                   8612: 	    return(1,$currentphase);
                   8613: 	}
1.221     albertel 8614: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8615: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8616: 	    &scantron_get_correction($r,$i,$scan_record,
                   8617: 				     \%scantron_config,
1.194     albertel 8618: 				     $line,'incorrectCODE',\%allcodes);
                   8619: 	    return(1,$currentphase);
1.186     albertel 8620: 	}
1.214     albertel 8621: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8622: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8623: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8624: 	    &scantron_get_correction($r,$i,$scan_record,
                   8625: 				     \%scantron_config,
1.194     albertel 8626: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8627: 	    return(1,$currentphase);
1.186     albertel 8628: 	}
1.524     raeburn  8629: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8630:     }
1.157     albertel 8631:     return (0,$currentphase+1);
                   8632: }
                   8633: 
1.423     albertel 8634: =pod
                   8635: 
                   8636: =item scantron_validate_doublebubble
                   8637: 
1.424     albertel 8638:    Validates all scanlines in the selected file to not have any
                   8639:    bubble lines with multiple bubbles marked.
                   8640: 
1.423     albertel 8641: =cut
                   8642: 
1.157     albertel 8643: sub scantron_validate_doublebubble {
                   8644:     my ($r,$currentphase) = @_;
                   8645:     #get student info
                   8646:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8647:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8648:3):     my (undef,undef,$sequence)=
                   8649:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8650: 
                   8651:     #get scantron line setup
1.596.2.12.2.  9(raebur 8652:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8653:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8654:3): 
                   8655:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8656:3):     unless (ref($navmap)) {
                   8657:3):         $r->print(&navmap_errormsg());
                   8658:3):         return(1,$currentphase);
                   8659:3):     }
                   8660:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8661:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8662:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8663:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8664:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8665:3): 
1.583     raeburn  8666:     my $nav_error;
1.596.2.12.2.  6(raebur 8667:3):     if (ref($map)) {
                   8668:3):         $randomorder = $map->randomorder();
                   8669:3):         $randompick = $map->randompick();
          0(raebur 8670:2):         unless ($randomorder || $randompick) {
                   8671:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8672:2):                 if ($res->randomorder()) {
                   8673:2):                     $randomorder = 1;
                   8674:2):                 }
                   8675:2):                 if ($res->randompick()) {
                   8676:2):                     $randompick = 1;
                   8677:2):                 }
                   8678:2):                 last if ($randomorder || $randompick);
                   8679:2):             }
                   8680:2):         }
          6(raebur 8681:3):         if ($randomorder || $randompick) {
                   8682:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8683:3):             if ($nav_error) {
                   8684:3):                 $r->print(&navmap_errormsg());
                   8685:3):                 return(1,$currentphase);
                   8686:3):             }
                   8687:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8688:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8689:3):         }
                   8690:3):     } else {
                   8691:3):         $r->print(&navmap_errormsg());
                   8692:3):         return(1,$currentphase);
                   8693:3):     }
                   8694:3): 
          (raeburn 8695:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8696:     if ($nav_error) {
                   8697:         $r->print(&navmap_errormsg());
                   8698:         return(1,$currentphase);
                   8699:     }
1.447     foxr     8700: 
1.157     albertel 8701:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8702: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8703: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8704: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8705:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8706:3):                                                  $randompick,$sequence,\@master_seq,
                   8707:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8708:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8709: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8710: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8711: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8712:3): 				 $$scan_record{'scantron.doubleerror'},
                   8713:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8714:     	return (1,$currentphase);
                   8715:     }
                   8716:     return (0,$currentphase+1);
                   8717: }
                   8718: 
1.423     albertel 8719: 
1.503     raeburn  8720: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8721:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8722:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8723: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8724: 	&restore_bubble_lines();
1.257     albertel 8725: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8726:     }
1.330     albertel 8727: 
1.447     foxr     8728:     my (undef, undef, $sequence) =
1.257     albertel 8729: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8730: 
1.447     foxr     8731:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8732:     unless (ref($navmap)) {
                   8733:         if (ref($nav_error)) {
                   8734:             $$nav_error = 1;
                   8735:         }
1.591     raeburn  8736:         return;
1.582     raeburn  8737:     }
1.191     albertel 8738:     my $map=$navmap->getResourceByUrl($sequence);
                   8739:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8740:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8741: 
                   8742:     &Apache::lonxml::clear_problem_counter();
                   8743: 
1.557     raeburn  8744:     my $uname       = $env{'user.name'};
                   8745:     my $udom        = $env{'user.domain'};
1.435     foxr     8746:     my $cid         = $env{'request.course.id'};
                   8747:     my $total_lines = 0;
                   8748:     %bubble_lines_per_response = ();
1.447     foxr     8749:     %first_bubble_line         = ();
1.503     raeburn  8750:     %subdivided_bubble_lines   = ();
                   8751:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8752:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8753: 
1.447     foxr     8754:     my $response_number = 0;
                   8755:     my $bubble_line     = 0;
1.191     albertel 8756:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8757:3):         my $resid = $resource->id();
          (raeburn 8758:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8759:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8760:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8761: 	    foreach my $part_id (@{$parts}) {
                   8762:                 my $lines;
                   8763: 
                   8764: 	        # TODO - make this a persistent hash not an array.
                   8765: 
                   8766:                 # optionresponse, matchresponse and rankresponse type items 
                   8767:                 # render as separate sub-questions in exam mode.
                   8768:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8769:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8770:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8771:                     my ($numbub,$numshown);
                   8772:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8773:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8774:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8775:                         }
                   8776:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8777:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8778:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8779:                         }
                   8780:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8781:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8782:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8783:                         }
                   8784:                     }
                   8785:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8786:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8787:                     }
1.596.2.12.2.  (raeburn 8788:):                     my $bubbles_per_row =
                   8789:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8790:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8791:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8792:                         $inner_bubble_lines++;
                   8793:                     }
                   8794:                     for (my $i=0; $i<$numshown; $i++) {
                   8795:                         $subdivided_bubble_lines{$response_number} .= 
                   8796:                             $inner_bubble_lines.',';
                   8797:                     }
                   8798:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8799:                     $lines = $numshown * $inner_bubble_lines;
                   8800:                 } else {
                   8801:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8802:):                 }
1.542     raeburn  8803: 
                   8804:                 $first_bubble_line{$response_number} = $bubble_line;
                   8805: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8806:                 $responsetype_per_response{$response_number} = 
                   8807:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8808:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8809: 	        $response_number++;
                   8810: 
                   8811: 	        $bubble_line +=  $lines;
                   8812: 	        $total_lines +=  $lines;
                   8813: 	    }
                   8814:         }
                   8815:     }
1.552     raeburn  8816:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8817: 
                   8818:     &save_bubble_lines();
                   8819:     $env{'form.scantron_maxbubble'} =
                   8820: 	$total_lines;
                   8821:     return $env{'form.scantron_maxbubble'};
                   8822: }
1.523     raeburn  8823: 
1.596.2.12.2.  (raeburn 8824:): sub bubblesheet_bubbles_per_row {
                   8825:):     my ($scantron_config) = @_;
                   8826:):     my $bubbles_per_row;
                   8827:):     if (ref($scantron_config) eq 'HASH') {
                   8828:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8829:):     }
                   8830:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8831:):         $bubbles_per_row = 10;
                   8832:):     }
                   8833:):     return $bubbles_per_row;
                   8834:): }
                   8835:): 
1.157     albertel 8836: sub scantron_validate_missingbubbles {
                   8837:     my ($r,$currentphase) = @_;
                   8838:     #get student info
                   8839:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8840:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8841:3):     my (undef,undef,$sequence)=
                   8842:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8843: 
                   8844:     #get scantron line setup
1.596.2.12.2.  9(raebur 8845:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8846:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8847:3): 
                   8848:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8849:3):     unless (ref($navmap)) {
                   8850:3):         $r->print(&navmap_errormsg());
                   8851:3):         return(1,$currentphase);
                   8852:3):     }
                   8853:3): 
                   8854:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8855:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8856:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8857:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8858:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8859:3): 
1.582     raeburn  8860:     my $nav_error;
1.596.2.12.2.  6(raebur 8861:3):     if (ref($map)) {
                   8862:3):         $randomorder = $map->randomorder();
                   8863:3):         $randompick = $map->randompick();
          0(raebur 8864:2):         unless ($randomorder || $randompick) {
                   8865:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8866:2):                 if ($res->randomorder()) {
                   8867:2):                     $randomorder = 1;
                   8868:2):                 }
                   8869:2):                 if ($res->randompick()) {
                   8870:2):                     $randompick = 1;
                   8871:2):                 }
                   8872:2):                 last if ($randomorder || $randompick);
                   8873:2):             }
                   8874:2):         }
          7(raebur 8875:3):         if ($randomorder || $randompick) {
                   8876:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8877:3):             if ($nav_error) {
                   8878:3):                 $r->print(&navmap_errormsg());
                   8879:3):                 return(1,$currentphase);
                   8880:3):             }
                   8881:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8882:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8883:3):         }
          6(raebur 8884:3):     } else {
                   8885:3):         $r->print(&navmap_errormsg());
          7(raebur 8886:3):         return(1,$currentphase);
          6(raebur 8887:3):     }
                   8888:3): 
                   8889:3): 
          (raeburn 8890:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8891:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8892:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8893:         return(1,$currentphase);
                   8894:     }
1.596.2.12.2.  6(raebur 8895:3): 
1.157     albertel 8896:     if (!$max_bubble) { $max_bubble=2**31; }
                   8897:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8898: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8899: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8900:3):         my $scan_record =
                   8901:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8902:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8903:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8904:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8905: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8906: 	my @to_correct;
1.470     foxr     8907: 	
                   8908: 	# Probably here's where the error is...
                   8909: 
1.157     albertel 8910: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8911:             my $lastbubble;
                   8912:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8913:3):                 my $question = $1;
                   8914:3):                 my $subquestion = $2;
                   8915:3):                 my ($first,$responsenum);
                   8916:3):                 if ($randomorder || $randompick) {
                   8917:3):                     $responsenum = $respnumlookup{$question-1};
                   8918:3):                     $first = $startline{$question-1};
                   8919:3):                 } else {
                   8920:3):                     $responsenum = $question-1;
                   8921:3):                     $first = $first_bubble_line{$responsenum};
                   8922:3):                 }
                   8923:3):                 if (!defined($first)) { next; }
          7(raebur 8924:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8925:3):                 my $subcount = 1;
                   8926:3):                 while ($subcount<$subquestion) {
                   8927:3):                     $first += $subans[$subcount-1];
                   8928:3):                     $subcount ++;
                   8929:3):                 }
                   8930:3):                 my $count = $subans[$subquestion-1];
                   8931:3):                 $lastbubble = $first + $count;
1.505     raeburn  8932:             } else {
1.596.2.12.2.  6(raebur 8933:3):                 my ($first,$responsenum);
                   8934:3):                 if ($randomorder || $randompick) {
                   8935:3):                     $responsenum = $respnumlookup{$missing-1};
                   8936:3):                     $first = $startline{$missing-1};
                   8937:3):                 } else {
                   8938:3):                     $responsenum = $missing-1;
                   8939:3):                     $first = $first_bubble_line{$responsenum};
                   8940:3):                 }
                   8941:3):                 if (!defined($first)) { next; }
                   8942:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8943:             }
                   8944:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8945: 	    push(@to_correct,$missing);
                   8946: 	}
                   8947: 	if (@to_correct) {
                   8948: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8949:3): 				     $line,'missingbubble',\@to_correct,
                   8950:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8951:3):                                      \%startline);
1.157     albertel 8952: 	    return (1,$currentphase);
                   8953: 	}
                   8954: 
                   8955:     }
                   8956:     return (0,$currentphase+1);
                   8957: }
                   8958: 
1.596.2.12.2.  (raeburn 8959:): sub hand_bubble_option {
                   8960:):     my (undef, undef, $sequence) =
                   8961:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8962:):     return if ($sequence eq '');
                   8963:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8964:):     unless (ref($navmap)) {
                   8965:):         return;
                   8966:):     }
                   8967:):     my $needs_hand_bubbles;
                   8968:):     my $map=$navmap->getResourceByUrl($sequence);
                   8969:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8970:):     foreach my $res (@resources) {
                   8971:):         if (ref($res)) {
                   8972:):             if ($res->is_problem()) {
                   8973:):                 my $partlist = $res->parts();
                   8974:):                 foreach my $part (@{ $partlist }) {
                   8975:):                     my @types = $res->responseType($part);
                   8976:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8977:):                         $needs_hand_bubbles = 1;
                   8978:):                         last;
                   8979:):                     }
                   8980:):                 }
                   8981:):             }
                   8982:):         }
                   8983:):     }
                   8984:):     if ($needs_hand_bubbles) {
          9(raebur 8985:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8986:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8987:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8988:):                &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 />').
                   8989:):                '<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 8990:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8991:):     }
                   8992:):     return;
                   8993:): }
1.423     albertel 8994: 
1.82      albertel 8995: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8996:0):     my ($r,$symb) = @_;
1.513     foxr     8997: 
1.257     albertel 8998:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8999:     if (!$symb) {
                   9000: 	return '';
                   9001:     }
1.324     albertel 9002:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 9003: 
1.596.2.12.2.  9(raebur 9004:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 9005:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 9006:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 9007:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9008:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 9009:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9010:     unless (ref($navmap)) {
                   9011:         $r->print(&navmap_errormsg());
                   9012:         return '';
1.596.2.12.2.  6(raebur 9013:3):     }
1.83      albertel 9014:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9015:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
          0(raebur 9016:2):         %grader_randomlists_by_symb,%symb_for_examcode);
          1(raebur 9017:2):     if (ref($map)) {
                   9018:2):         $randomorder = $map->randomorder();
          6(raebur 9019:3):         $randompick = $map->randompick();
          0(raebur 9020:2):         unless ($randomorder || $randompick) {
                   9021:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9022:2):                 if ($res->randomorder()) {
                   9023:2):                     $randomorder = 1;
                   9024:2):                 }
                   9025:2):                 if ($res->randompick()) {
                   9026:2):                     $randompick = 1;
                   9027:2):                 }
                   9028:2):                 last if ($randomorder || $randompick);
                   9029:2):             }
                   9030:2):         }
          6(raebur 9031:3):     } else {
                   9032:3):         $r->print(&navmap_errormsg());
                   9033:3):         return '';
          1(raebur 9034:2):     }
          6(raebur 9035:3):     my $nav_error;
1.83      albertel 9036:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9037:3):     if ($randomorder || $randompick) {
          0(raebur 9038:2):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
          6(raebur 9039:3):         if ($nav_error) {
                   9040:3):             $r->print(&navmap_errormsg());
                   9041:3):             return '';
1.586     raeburn  9042:         }
                   9043:     }
1.596.2.12.2.  6(raebur 9044:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9045:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9046: 
1.554     raeburn  9047:     my ($uname,$udom);
1.82      albertel 9048:     my $result= <<SCANTRONFORM;
1.81      albertel 9049: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9050:   <input type="hidden" name="command" value="scantron_configphase" />
                   9051:   $default_form_data
                   9052: SCANTRONFORM
1.82      albertel 9053:     $r->print($result);
                   9054: 
                   9055:     my @delayqueue;
1.542     raeburn  9056:     my (%completedstudents,%scandata);
1.140     albertel 9057:     
1.520     www      9058:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9059:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 9060:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 9061:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9062:     $r->print('<br />');
1.140     albertel 9063:     my $start=&Time::HiRes::time();
1.158     albertel 9064:     my $i=-1;
1.542     raeburn  9065:     my $started;
1.447     foxr     9066: 
1.596.2.12.2.  (raeburn 9067:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9068:     if ($nav_error) {
                   9069:         $r->print(&navmap_errormsg());
                   9070:         return '';
                   9071:     }
                   9072: 
1.513     foxr     9073:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9074:     # the user and return.
                   9075: 
                   9076:     if ($ssi_error) {
                   9077: 	$r->print("</form>");
                   9078: 	&ssi_print_error($r);
1.520     www      9079:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9080: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9081:     }
1.447     foxr     9082: 
1.596.2.12.2.  9(raebur 9083:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9084:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 9085:3):     my %orderedforcode;
1.542     raeburn  9086: 
1.157     albertel 9087:     while ($i<$scanlines->{'count'}) {
                   9088:  	($uname,$udom)=('','');
                   9089:  	$i++;
1.200     albertel 9090:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9091:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9092: 	if ($started) {
1.596.2.12.2.  1(raebur 9093:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9094: 	}
                   9095: 	$started=1;
1.596.2.12.2.  6(raebur 9096:3):         my %respnumlookup = ();
                   9097:3):         my %startline = ();
                   9098:3):         my $total;
1.157     albertel 9099:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 9100:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   9101:3):                                                  $randompick,$sequence,\@master_seq,
                   9102:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9103:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9104:3):                                                  \$total);
1.157     albertel 9105:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9106:  					      \%idmap,$i)) {
                   9107:   	    &scantron_add_delay(\@delayqueue,$line,
                   9108:  				'Unable to find a student that matches',1);
                   9109:  	    next;
                   9110:   	}
                   9111:  	if (exists $completedstudents{$uname}) {
                   9112:  	    &scantron_add_delay(\@delayqueue,$line,
                   9113:  				'Student '.$uname.' has multiple sheets',2);
                   9114:  	    next;
                   9115:  	}
1.596.2.12.2.  1(raebur 9116:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9117:2):         my $user = $uname.':'.$usec;
1.157     albertel 9118:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9119: 
1.596.2.12.2.  1(raebur 9120:2):         my $scancode;
                   9121:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9122:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9123:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9124:2):         } else {
                   9125:2):             $scancode = '';
                   9126:2):         }
                   9127:2): 
                   9128:2):         my @mapresources = @resources;
          6(raebur 9129:3):         if ($randomorder || $randompick) {
          1(raebur 9130:2):             @mapresources =
          6(raebur 9131:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9132:3):                              \%orderedforcode);
          1(raebur 9133:2):         }
1.586     raeburn  9134:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 9135:2):         foreach my $resource (@mapresources) {
1.586     raeburn  9136:             my $ressymb;
                   9137:             if (ref($resource)) {
                   9138:                 $ressymb = $resource->symb();
                   9139:             } else {
                   9140:                 $res_error = 1;
                   9141:                 last;
                   9142:             }
1.557     raeburn  9143:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9144:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9145:7):                 my $currcode;
                   9146:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9147:7):                     $currcode = $scancode;
                   9148:7):                 }
1.557     raeburn  9149:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 9150:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 9151:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   9152:7):                                               $currcode);
1.557     raeburn  9153:                 $partids_by_symb{$ressymb} = $parts;
                   9154:             } else {
                   9155:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9156:             }
1.554     raeburn  9157:         }
                   9158: 
1.586     raeburn  9159:         if ($res_error) {
                   9160:             &scantron_add_delay(\@delayqueue,$line,
                   9161:                                 'An error occurred while grading student '.$uname,2);
                   9162:             next;
                   9163:         }
                   9164: 
1.330     albertel 9165: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9166:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9167: 
                   9168: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9169: 	    &scantron_putfile($scanlines,$scan_data);
                   9170: 	}
1.161     albertel 9171: 	
1.542     raeburn  9172:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9173:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 9174:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   9175:3):                                    \%respnumlookup,\%startline) 
                   9176:3):             eq 'ssi_error') {
1.542     raeburn  9177:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9178:             $r->print("</form>");
                   9179:             &ssi_print_error($r);
                   9180:             &Apache::lonnet::remove_lock($lock);
                   9181:             return '';      # Why return ''?  Beats me.
                   9182:         }
1.513     foxr     9183: 
1.596.2.12.2.  6(raebur 9184:3):         if (($scancode) && ($randomorder || $randompick)) {
          0(raebur 9185:2):             foreach my $key (keys(%symb_for_examcode)) {
                   9186:2):                 my $symb_in_map = $symb_for_examcode{$key};
                   9187:2):                 if ($symb_in_map ne '') {
                   9188:2):                     my $parmresult =
                   9189:2):                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9190:2):                                                                '0_examcode',2,$scancode,
                   9191:2):                                                                'string_examcode',$uname,
                   9192:2):                                                                $udom);
                   9193:2):                 }
                   9194:2):             }
          6(raebur 9195:3):         }
1.140     albertel 9196: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9197:         if ($env{'form.verifyrecord'}) {
                   9198:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 9199:3):             if ($randompick) {
                   9200:3):                 if ($total) {
                   9201:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   9202:3):                 }
                   9203:3):             }
                   9204:3): 
1.542     raeburn  9205:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9206:             chomp($studentdata);
                   9207:             $studentdata =~ s/\r$//;
                   9208:             my $studentrecord = '';
                   9209:             my $counter = -1;
1.596.2.12.2.  1(raebur 9210:2):             foreach my $resource (@mapresources) {
1.554     raeburn  9211:                 my $ressymb = $resource->symb();
1.542     raeburn  9212:                 ($counter,my $recording) =
                   9213:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9214:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9215:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9216:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9217:                 $studentrecord .= $recording;
                   9218:             }
                   9219:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9220:                 &Apache::lonxml::clear_problem_counter();
                   9221:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9222:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 9223:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   9224:3):                                            \%respnumlookup,\%startline)
                   9225:3):                     eq 'ssi_error') {
1.554     raeburn  9226:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9227:                     $r->print("</form>");
                   9228:                     &ssi_print_error($r);
                   9229:                     &Apache::lonnet::remove_lock($lock);
                   9230:                     delete($completedstudents{$uname});
                   9231:                     return '';
                   9232:                 }
1.542     raeburn  9233:                 $counter = -1;
                   9234:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 9235:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  9236:                     my $ressymb = $resource->symb();
1.542     raeburn  9237:                     ($counter,my $recording) =
                   9238:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9239:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9240:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   9241:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   9242:3):                                                  \%startline);
1.542     raeburn  9243:                     $studentrecord .= $recording;
                   9244:                 }
                   9245:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  9246:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9247:                     if ($scancode eq '') {
1.596.2.6  raeburn  9248:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9249:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9250:                     } else {
1.596.2.6  raeburn  9251:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9252:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9253:                     }
                   9254:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9255:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9256:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9257:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9258:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9259:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 9260:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9261:                               &Apache::loncommon::end_data_table_row().
                   9262:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9263:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 9264:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9265:                               &Apache::loncommon::end_data_table_row().
                   9266:                               &Apache::loncommon::end_data_table().'</p>');
                   9267:                 } else {
                   9268:                     $r->print('<br /><span class="LC_warning">'.
                   9269:                              &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 />'.
                   9270:                              &mt("As a consequence, this user's submission history records two tries.").
                   9271:                                  '</span><br />');
                   9272:                 }
                   9273:             }
                   9274:         }
1.543     raeburn  9275:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9276:     } continue {
1.330     albertel 9277: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9278: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9279:     }
1.140     albertel 9280:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9281:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9282: #    my $lasttime = &Time::HiRes::time()-$start;
                   9283: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9284: 
1.200     albertel 9285:     $r->print("</form>");
1.157     albertel 9286:     return '';
1.75      albertel 9287: }
1.157     albertel 9288: 
1.557     raeburn  9289: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 9290:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9291:):         $bubbles_per_row) = @_;
1.557     raeburn  9292:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9293:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9294:         foreach my $resource (@{$resources}) {
                   9295:             my $ressymb = $resource->symb();
                   9296:             my ($analysis,$parts) =
                   9297:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 9298:):                                           $env{'user.name'},$env{'user.domain'},
                   9299:):                                           1,$bubbles_per_row);
1.557     raeburn  9300:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9301:             if (ref($analysis) eq 'HASH') {
                   9302:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9303:                     $grader_randomlists_by_symb->{$ressymb} =
                   9304:                         $analysis->{'parts_withrandomlist'};
                   9305:                 }
                   9306:             }
                   9307:         }
                   9308:     }
                   9309:     return;
                   9310: }
                   9311: 
1.596.2.12.2.  1(raebur 9312:2): =pod
                   9313:2): 
                   9314:2): =item users_order
                   9315:2): 
                   9316:2):   Returns array of resources in current map, ordered based on either CODE,
                   9317:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9318:2):   "NAMEd" exam.
                   9319:2): 
          6(raebur 9320:3):   Should be used when randomorder and/or randompick applied when the 
                   9321:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9322:3):   for the version of the exam the student received.
          1(raebur 9323:2): 
                   9324:2): =cut
                   9325:2): 
                   9326:2): sub users_order  {
          6(raebur 9327:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9328:2):     my @mapresources;
          6(raebur 9329:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9330:2):         return @mapresources;
                   9331:2):     }
          6(raebur 9332:3):     if ($scancode) {
                   9333:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9334:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9335:3):         } else {
                   9336:3):             $env{'form.CODE'} = $scancode;
                   9337:3):             my $actual_seq =
                   9338:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9339:3):                                                                $master_seq,
                   9340:3):                                                                $user,$scancode,1);
                   9341:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9342:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9343:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9344:3):                     if (@mapresources > 0) {
                   9345:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9346:3):                     }
                   9347:3):                 }
                   9348:3):             }
                   9349:3):             delete($env{'form.CODE'});
          1(raebur 9350:2):         }
                   9351:2):     } else {
                   9352:2):         my $actual_seq =
                   9353:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9354:2):                                                            $master_seq,
          5(raebur 9355:3):                                                            $user,undef,1);
          1(raebur 9356:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9357:2):             @mapresources =
                   9358:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9359:2):         }
          6(raebur 9360:3):     }
                   9361:3):     return @mapresources;
          1(raebur 9362:2): }
                   9363:2): 
1.542     raeburn  9364: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9365:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9366:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9367:3):     my $uselookup = 0;
                   9368:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9369:3):         (ref($startline) eq 'HASH')) {
                   9370:3):         $uselookup = 1;
                   9371:3):     }
                   9372:3): 
1.554     raeburn  9373:     if (ref($resources) eq 'ARRAY') {
                   9374:         my $count = 0;
                   9375:         foreach my $resource (@{$resources}) {
                   9376:             my $ressymb = $resource->symb();
                   9377:             my %form = ('submitted'      => 'scantron',
                   9378:                         'grade_target'   => 'grade',
                   9379:                         'grade_username' => $uname,
                   9380:                         'grade_domain'   => $udom,
                   9381:                         'grade_courseid' => $env{'request.course.id'},
                   9382:                         'grade_symb'     => $ressymb,
                   9383:                         'CODE'           => $scancode
                   9384:                        );
1.596.2.12.2.  (raeburn 9385:):             if ($bubbles_per_row ne '') {
                   9386:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9387:):             }
                   9388:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9389:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9390:):             }
1.554     raeburn  9391:             if (ref($parts) eq 'HASH') {
                   9392:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9393:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9394:3):                         if ($uselookup) {
                   9395:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9396:3):                         } else {
                   9397:3):                             $form{'scantron_questnum_start.'.$part} =
                   9398:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9399:3):                         }
1.554     raeburn  9400:                         $count++;
                   9401:                     }
                   9402:                 }
                   9403:             }
                   9404:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9405:             return 'ssi_error' if ($ssi_error);
                   9406:             last if (&Apache::loncommon::connection_aborted($r));
                   9407:         }
1.542     raeburn  9408:     }
                   9409:     return;
                   9410: }
                   9411: 
1.157     albertel 9412: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9413:0):     my ($r,$symb) = @_;
1.565     raeburn  9414:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9415:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9416:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9417:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9418:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9419: 							  'domainid',
1.565     raeburn  9420: 							  'coursename',$dom);
                   9421:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9422:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9423:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9424:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9425:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9426:     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 9427:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9428:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9429:     function checkUpload(formname) {
                   9430: 	if (formname.upfile.value == "") {
1.579     raeburn  9431: 	    alert("'.$nofile_alert.'");
1.157     albertel 9432: 	    return false;
                   9433: 	}
1.565     raeburn  9434:         if (formname.courseid.value == "") {
1.579     raeburn  9435:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9436:             return false;
                   9437:         }
1.157     albertel 9438: 	formname.submit();
                   9439:     }
1.565     raeburn  9440: 
                   9441:     function ToSyllabus() {
                   9442:         var cdom = '."'$dom'".';
                   9443:         var cnum = document.rules.courseid.value;
                   9444:         if (cdom == "" || cdom == null) {
                   9445:             return;
                   9446:         }
                   9447:         if (cnum == "" || cnum == null) {
                   9448:            return;
                   9449:         }
                   9450:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9451:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9452:         return;
                   9453:     }
                   9454: 
1.596.2.12.2.  9(raebur 9455:9):     '.$formatjs.'
                   9456:9): '));
                   9457:9):     $r->print('
1.596.2.4  raeburn  9458: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9459: 
1.492     albertel 9460: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9461: '.$default_form_data.
                   9462:   &Apache::lonhtmlcommon::start_pick_box().
                   9463:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9464:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9465:   &Apache::lonhtmlcommon::row_closure().
                   9466:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9467:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9468:   &Apache::lonhtmlcommon::row_closure().
                   9469:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9470:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9471:9):   &Apache::lonhtmlcommon::row_closure());
                   9472:9):     if ($formatoptions) {
                   9473:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9474:9):                   &Apache::lonhtmlcommon::row_closure());
                   9475:9):     }
                   9476:9):     $r->print(
1.565     raeburn  9477:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9478:   '<input type="file" name="upfile" size="50" />'.
                   9479:   &Apache::lonhtmlcommon::row_closure(1).
                   9480:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9481: 
1.492     albertel 9482: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9483: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9484: </form>
1.492     albertel 9485: ');
1.157     albertel 9486:     return '';
                   9487: }
                   9488: 
1.596.2.12.2.  9(raebur 9489:9): sub scantron_upload_dataformat {
                   9490:9):     my ($dom) = @_;
                   9491:9):     my ($formatoptions,$formattitle,$formatjs);
                   9492:9):     $formatjs = <<'END';
                   9493:9): function toggleScantab(form) {
                   9494:9):    return;
                   9495:9): }
                   9496:9): END
                   9497:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9498:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9499:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9500:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9501:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9502:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9503:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9504:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9505:9):                             my ($onclick,$formatextra,$singleline);
                   9506:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9507:9):                             my $count = 0;
                   9508:9):                             foreach my $line (@lines) {
          0.2.1(ra 9509:an-23):                                 next if (($line =~ /^\#/) || ($line eq ''));
          9(raebur 9510:9):                                 $singleline = $line;
                   9511:9):                                 $count ++;
                   9512:9):                             }
                   9513:9):                             if ($count > 1) {
                   9514:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9515:9):                                                '<span class="LC_nobreak">'.
          4(raebur 9516:0):                                                &mt('Bubblesheet type').':&nbsp;'.
          9(raebur 9517:9):                                                &scantron_scantab().'</span></div>';
                   9518:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9519:9):                                 $formatjs = <<"END";
                   9520:9): function toggleScantab(form) {
                   9521:9):     var divid = 'bubbletype';
                   9522:9):     if (document.getElementById(divid)) {
                   9523:9):         var radioname = 'fileformat';
                   9524:9):         var num = form.elements[radioname].length;
                   9525:9):         if (num) {
                   9526:9):             for (var i=0; i<num; i++) {
                   9527:9):                 if (form.elements[radioname][i].checked) {
                   9528:9):                     var chosen = form.elements[radioname][i].value;
                   9529:9):                     if (chosen == 'dat') {
                   9530:9):                         document.getElementById(divid).style.display = 'none';
                   9531:9):                     } else if (chosen == 'csv') {
                   9532:9):                         document.getElementById(divid).style.display = 'block';
                   9533:9):                     }
                   9534:9):                 }
                   9535:9):             }
                   9536:9):         }
                   9537:9):     }
                   9538:9):     return;
                   9539:9): }
                   9540:9): 
                   9541:9): END
                   9542:9):                             } elsif ($count == 1) {
                   9543:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9544:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9545:9):                             }
                   9546:9):                             $formattitle = &mt('File format');
                   9547:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9548:9):                                              &mt('Plain Text (no delimiters)').
                   9549:9):                                              '</label>'.('&nbsp;'x2).
                   9550:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9551:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9552:9):                         }
                   9553:9):                     }
                   9554:9):                 }
                   9555:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9556:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9557:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9558:9):                         $formattitle = &mt('Bubblesheet type');
                   9559:9):                         $formatoptions = &scantron_scantab();
                   9560:9):                     }
                   9561:9):                 }
                   9562:9):             }
                   9563:9):         }
                   9564:9):     }
                   9565:9):     return ($formatoptions,$formattitle,$formatjs);
                   9566:9): }
1.423     albertel 9567: 
1.157     albertel 9568: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9569:0):     my ($r,$symb) = @_;
1.182     albertel 9570:     my $doanotherupload=
                   9571: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9572: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9573: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9574: 	'</form>'."\n";
1.257     albertel 9575:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9576: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9577: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9578: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9579:0):         unless ($symb) {
1.182     albertel 9580: 	    $r->print($doanotherupload);
                   9581: 	}
1.162     albertel 9582: 	return '';
                   9583:     }
1.257     albertel 9584:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9585:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9586:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9587:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9588:3):         $r->print(
                   9589:3):             &Apache::lonhtmlcommon::confirm_success(
                   9590:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9591:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9592:     } else {
1.596.2.12.2.  9(raebur 9593:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9594:9):         my $parser;
                   9595:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9596:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9597:9):                 my $is_csv;
                   9598:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9599:9):                 if (@possibles > 1) {
                   9600:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9601:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9602:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9603:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9604:9):                                     $is_csv = 1;
                   9605:9):                                 }
                   9606:9):                             }
                   9607:9):                         }
                   9608:9):                     }
                   9609:9):                 } elsif (@possibles == 1) {
                   9610:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9611:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9612:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9613:9):                                 $is_csv = 1;
                   9614:9):                             }
                   9615:9):                         }
                   9616:9):                     }
                   9617:9):                 }
                   9618:9):                 if ($is_csv) {
                   9619:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9620:9):                 }
                   9621:9):             }
                   9622:9):         }
                   9623:9):         my $result =
                   9624:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9625:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9626: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9627:3):             $r->print(
                   9628:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9629:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9630:3):                         (length($env{'form.upfile'})-1),
                   9631:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9632:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9633:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9634:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9635: 	} else {
1.596.2.12.2.  5(raebur 9636:3):             $r->print(
                   9637:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9638:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9639:3):                           $result,
1.568     raeburn  9640: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9641: 	}
                   9642:     }
1.174     albertel 9643:     if ($symb) {
1.596.2.12.2.  1(raebur 9644:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9645:     } else {
1.182     albertel 9646: 	$r->print($doanotherupload);
1.174     albertel 9647:     }
1.157     albertel 9648:     return '';
                   9649: }
                   9650: 
1.567     raeburn  9651: sub validate_uploaded_scantron_file {
                   9652:     my ($cdom,$cname,$fname) = @_;
                   9653:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9654:     my @lines;
                   9655:     if ($scanlines ne '-1') {
                   9656:         @lines=split("\n",$scanlines,-1);
                   9657:     }
                   9658:     my $output;
                   9659:     if (@lines) {
                   9660:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9661:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9662:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9663:         my %idmap = &username_to_idmap($classlist);
                   9664:         foreach my $key (keys(%idmap)) {
                   9665:             my $lckey = lc($key);
                   9666:             $idmap{$lckey} = $idmap{$key};
                   9667:         }
                   9668:         my %unique_formats;
1.596.2.12.2.  9(raebur 9669:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9670:         foreach my $line (@formatlines) {
1.596.2.12.2.  0.2.1(ra 9671:an-23):             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  9672:             my @config = split(/:/,$line);
                   9673:             my $idstart = $config[5];
                   9674:             my $idlength = $config[6];
                   9675:             if (($idstart ne '') && ($idlength > 0)) {
                   9676:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9677:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9678:                 } else {
                   9679:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9680:                 }
                   9681:             }
                   9682:         }
                   9683:         foreach my $key (keys(%unique_formats)) {
                   9684:             my ($idstart,$idlength) = split(':',$key);
                   9685:             %{$counts{$key}} = (
                   9686:                                'found'   => 0,
                   9687:                                'total'   => 0,
                   9688:                               );
                   9689:             foreach my $line (@lines) {
                   9690:                 next if ($line =~ /^#/);
                   9691:                 next if ($line =~ /^[\s\cz]*$/);
                   9692:                 my $id = substr($line,$idstart-1,$idlength);
                   9693:                 $id = lc($id);
                   9694:                 if (exists($idmap{$id})) {
                   9695:                     $counts{$key}{'found'} ++;
                   9696:                 }
                   9697:                 $counts{$key}{'total'} ++;
                   9698:             }
                   9699:             if ($counts{$key}{'total'}) {
                   9700:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9701:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9702:                     $max_match_pct = $percent_match;
                   9703:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9704:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9705:                     $max_match_count = $counts{$key}{'total'};
                   9706:                 }
                   9707:             }
                   9708:         }
                   9709:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9710:             my $format_descs;
                   9711:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9712:             for (my $i=0; $i<$numwithformat; $i++) {
                   9713:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9714:                 if ($i<$numwithformat-2) {
                   9715:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9716:                 } elsif ($i==$numwithformat-2) {
                   9717:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9718:                 } elsif ($i==$numwithformat-1) {
                   9719:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9720:                 }
                   9721:             }
                   9722:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9723:3):             $output .= '<br />';
                   9724:3):             if ($found_match_count == $max_match_count) {
                   9725:3):                 # 100% matching entries
                   9726:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9727:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9728:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9729:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9730:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9731:3):                     ' in the file (for the format defined for [_3]).',
                   9732:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9733:3):             } else {
                   9734:3):                 # Not all entries matching? -> Show warning and additional info
                   9735:3):                 $output .=
                   9736:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9737:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9738:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9739:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9740:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9741:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9742:3):                         ' in the file (for the format defined for [_3]).',
                   9743:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9744:3):                     '<p class="LC_info">'.
                   9745:3):                     &mt('A low percentage of matches results from one of the following:').
                   9746:3):                     '</p><ul>'.
                   9747:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9748:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9749:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9750:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9751:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9752:3):                     '</ul>';
                   9753:3):             }
1.567     raeburn  9754:         }
                   9755:     } else {
1.596.2.12.2.  5(raebur 9756:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9757:     }
                   9758:     return $output;
                   9759: }
                   9760: 
1.202     albertel 9761: sub valid_file {
                   9762:     my ($requested_file)=@_;
                   9763:     foreach my $filename (sort(&scantron_filenames())) {
                   9764: 	if ($requested_file eq $filename) { return 1; }
                   9765:     }
                   9766:     return 0;
                   9767: }
                   9768: 
                   9769: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9770:0):     my ($r,$symb) = @_;
          (raeburn 9771:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9772:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9773:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9774:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9775:     if (! &valid_file($file)) {
1.492     albertel 9776: 	$r->print('
1.202     albertel 9777: 	<p>
1.596.2.12.2.  3(raebur 9778:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9779:         </p>
1.492     albertel 9780: ');
1.202     albertel 9781: 	return;
                   9782:     }
                   9783:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9784:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9785:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9786:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9787:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9788:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9789:     $r->print('
1.202     albertel 9790:     <p>
1.596.2.12.2.  1(raebur 9791:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9792: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9793:     </p>
                   9794:     <p>
1.492     albertel 9795: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9796: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9797:     </p>
                   9798:     <p>
1.492     albertel 9799: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9800: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9801:     </p>
1.492     albertel 9802: ');
1.202     albertel 9803:     return '';
                   9804: }
1.157     albertel 9805: 
1.523     raeburn  9806: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9807:0):     my ($r,$symb) = @_;
1.523     raeburn  9808:     if (!$symb) {return '';}
                   9809:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9810:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9811:     my $numletts = scalar(keys(%lettdig));
                   9812:     my $cnum = $env{'course.'.$cid.'.num'};
                   9813:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9814:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9815:     my %record;
                   9816:     my %scantron_config =
1.596.2.12.2.  9(raebur 9817:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9818:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9819:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9820:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9821:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9822:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9823:     unless (ref($navmap)) {
                   9824:         $r->print(&navmap_errormsg());
                   9825:         return '';
                   9826:     }
1.523     raeburn  9827:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9828:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9829:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9830:2):     if (ref($map)) {
                   9831:2):         $randomorder=$map->randomorder();
          7(raebur 9832:3):         $randompick=$map->randompick();
          0(raebur 9833:2):         unless ($randomorder || $randompick) {
                   9834:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9835:2):                 if ($res->randomorder()) {
                   9836:2):                     $randomorder = 1;
                   9837:2):                 }
                   9838:2):                 if ($res->randompick()) {
                   9839:2):                     $randompick = 1;
                   9840:2):                 }
                   9841:2):                 last if ($randomorder || $randompick);
                   9842:2):             }
                   9843:2):         }
          1(raebur 9844:2):     }
1.557     raeburn  9845:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9846:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9847:3):     if ($nav_error) {
                   9848:3):         $r->print(&navmap_errormsg());
                   9849:3):         return '';
          1(raebur 9850:2):     }
          (raeburn 9851:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9852:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9853:     my ($uname,$udom);
1.523     raeburn  9854:     my (%scandata,%lastname,%bylast);
                   9855:     $r->print('
                   9856: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9857: 
                   9858:     my @delayqueue;
                   9859:     my %completedstudents;
                   9860: 
1.596.2.12.2.  6(raebur 9861:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9862:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9863:3):     my ($username,$domain,$started);
          (raeburn 9864:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9865:     if ($nav_error) {
                   9866:         $r->print(&navmap_errormsg());
                   9867:         return '';
                   9868:     }
1.523     raeburn  9869: 
                   9870:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9871:                                           'Processing first student');
                   9872:     my $start=&Time::HiRes::time();
                   9873:     my $i=-1;
                   9874: 
                   9875:     while ($i<$scanlines->{'count'}) {
                   9876:         ($username,$domain,$uname)=('','','');
                   9877:         $i++;
                   9878:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9879:         if ($line=~/^[\s\cz]*$/) { next; }
                   9880:         if ($started) {
                   9881:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9882:                                                      'last student');
                   9883:         }
                   9884:         $started=1;
                   9885:         my $scan_record=
                   9886:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9887:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9888:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9889:3):                                               \%idmap,$i)) {
1.523     raeburn  9890:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9891:                                 'Unable to find a student that matches',1);
                   9892:             next;
                   9893:         }
                   9894:         if (exists $completedstudents{$uname}) {
                   9895:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9896:                                 'Student '.$uname.' has multiple sheets',2);
                   9897:             next;
                   9898:         }
                   9899:         my $pid = $scan_record->{'scantron.ID'};
                   9900:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9901:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9902:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9903:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9904:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9905:2): 
                   9906:2):         my $scancode;
                   9907:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9908:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9909:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9910:2):         } else {
                   9911:2):             $scancode = '';
                   9912:2):         }
                   9913:2): 
                   9914:2):         my @mapresources = @resources;
          6(raebur 9915:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9916:3):         my %respnumlookup=();
                   9917:3):         my %startline=();
                   9918:3):         if ($randomorder || $randompick) {
          1(raebur 9919:2):             @mapresources =
          6(raebur 9920:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9921:3):                              \%orderedforcode);
                   9922:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9923:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9924:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9925:3):                                              \%respnumlookup,\%startline);
                   9926:3):             if ($randompick && $total) {
                   9927:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9928:3):             }
          1(raebur 9929:2):         }
          6(raebur 9930:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9931:3):         chomp($scandata{$pid});
                   9932:3):         $scandata{$pid} =~ s/\r$//;
                   9933:3): 
1.523     raeburn  9934:         my $counter = -1;
1.596.2.12.2.  1(raebur 9935:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9936:             my $parts;
1.554     raeburn  9937:             my $ressymb = $resource->symb();
1.557     raeburn  9938:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9939:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9940:7):                 my $currcode;
                   9941:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9942:7):                     $currcode = $scancode;
                   9943:7):                 }
1.557     raeburn  9944:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9945:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9946:):                                               $username,$domain,undef,
          1(raebur 9947:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9948:             } else {
                   9949:                 $parts = $grader_partids_by_symb{$ressymb};
                   9950:             }
1.542     raeburn  9951:             ($counter,my $recording) =
                   9952:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9953:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9954:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9955:3):                                          $randomorder,$randompick,
                   9956:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9957:             $record{$pid} .= $recording;
1.523     raeburn  9958:         }
                   9959:     }
                   9960:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9961:     $r->print('<br />');
                   9962:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9963:     $passed = 0;
                   9964:     $failed = 0;
                   9965:     $numstudents = 0;
                   9966:     foreach my $last (sort(keys(%bylast))) {
                   9967:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9968:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9969:                 my $showscandata = $scandata{$pid};
                   9970:                 my $showrecord = $record{$pid};
                   9971:                 $showscandata =~ s/\s/&nbsp;/g;
                   9972:                 $showrecord =~ s/\s/&nbsp;/g;
                   9973:                 if ($scandata{$pid} eq $record{$pid}) {
                   9974:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9975:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9976: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9977: '</tr>'."\n".
                   9978: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9979:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9980:                     $passed ++;
                   9981:                 } else {
                   9982:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9983:                     $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  9984: '</tr>'."\n".
                   9985: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9986:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9987: '</tr>'."\n";
                   9988:                     $failed ++;
                   9989:                 }
                   9990:                 $numstudents ++;
                   9991:             }
                   9992:         }
                   9993:     }
1.596.2.4  raeburn  9994:     $r->print('<p>'.
1.596.2.8  raeburn  9995:               &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  9996:                   '<b>',
                   9997:                   $numstudents,
                   9998:                   '</b>',
                   9999:                   $env{'form.scantron_maxbubble'}).
                   10000:               '</p>'
                   10001:     );
1.596.2.12.2.  2(raebur 10002:2):     $r->print('<p>'
                   10003:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   10004:2):              .'<br />'
                   10005:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10006:2):              .'</p>');
1.523     raeburn  10007:     if ($passed) {
1.572     www      10008:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10009:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10010:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10011:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10012:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10013:                  $okstudents."\n".
                   10014:                  &Apache::loncommon::end_data_table().'<br />');
                   10015:     }
                   10016:     if ($failed) {
1.572     www      10017:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10018:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10019:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10020:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10021:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10022:                  $badstudents."\n".
                   10023:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10024:                  &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  10025:     }
1.596.2.12.2.  1(raebur 10026:0):     $r->print('</form><br />');
1.523     raeburn  10027:     return;
                   10028: }
                   10029: 
1.542     raeburn  10030: sub verify_scantron_grading {
1.554     raeburn  10031:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 10032:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10033:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  10034:     my ($record,%expected,%startpos);
                   10035:     return ($counter,$record) if (!ref($resource));
                   10036:     return ($counter,$record) if (!$resource->is_problem());
                   10037:     my $symb = $resource->symb();
1.554     raeburn  10038:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10039:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10040:         $counter ++;
                   10041:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 10042:3):         my $respnum = $counter;
                   10043:3):         if ($randomorder || $randompick) {
                   10044:3):             $respnum = $respnumlookup->{$counter};
                   10045:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   10046:3):         } else {
                   10047:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10048:3):         }
                   10049:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10050:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10051:             foreach my $item (@sub_lines) {
                   10052:                 $expected{$part_id} += $item;
                   10053:             }
                   10054:         } else {
1.596.2.12.2.  6(raebur 10055:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10056:         }
                   10057:     }
                   10058:     if ($symb) {
                   10059:         my %recorded;
                   10060:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10061:         if ($returnhash{'version'}) {
                   10062:             my %lasthash=();
                   10063:             my $version;
                   10064:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10065:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10066:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10067:                 }
                   10068:             }
                   10069:             foreach my $key (keys(%lasthash)) {
                   10070:                 if ($key =~ /\.scantron$/) {
                   10071:                     my $value = &unescape($lasthash{$key});
                   10072:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10073:                     if ($value eq '') {
                   10074:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10075:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10076:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10077:                             }
                   10078:                         }
                   10079:                     } else {
                   10080:                         my @tocheck;
                   10081:                         my @items = split(//,$value);
                   10082:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10083:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10084:                             if (@items < $expected{$part_id}) {
                   10085:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10086:                                 my @singles = split(//,$fragment);
                   10087:                                 foreach my $pos (@singles) {
                   10088:                                     if ($pos eq ' ') {
                   10089:                                         push(@tocheck,$pos);
                   10090:                                     } else {
                   10091:                                         my $next = shift(@items);
                   10092:                                         push(@tocheck,$next);
                   10093:                                     }
                   10094:                                 }
                   10095:                             } else {
                   10096:                                 @tocheck = @items;
                   10097:                             }
                   10098:                             foreach my $letter (@tocheck) {
                   10099:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10100:                                     if ($letter !~ /^[A-J]$/) {
                   10101:                                         $letter = $scantron_config->{'Qoff'};
                   10102:                                     }
                   10103:                                     $recorded{$part_id} .= $letter;
                   10104:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10105:                                     my $digit;
                   10106:                                     if ($letter !~ /^[A-J]$/) {
                   10107:                                         $digit = $scantron_config->{'Qoff'};
                   10108:                                     } else {
                   10109:                                         $digit = $lettdig->{$letter};
                   10110:                                     }
                   10111:                                     $recorded{$part_id} .= $digit;
                   10112:                                 }
                   10113:                             }
                   10114:                         } else {
                   10115:                             @tocheck = @items;
                   10116:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10117:                                 my $curr_sub = shift(@tocheck);
                   10118:                                 my $digit;
                   10119:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10120:                                     $digit = $lettdig->{$curr_sub}-1;
                   10121:                                 }
                   10122:                                 if ($curr_sub eq 'J') {
                   10123:                                     $digit += scalar($numletts);
                   10124:                                 }
                   10125:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10126:                                     if ($j == $digit) {
                   10127:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10128:                                     } else {
                   10129:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10130:                                     }
                   10131:                                 }
                   10132:                             }
                   10133:                         }
                   10134:                     }
                   10135:                 }
                   10136:             }
                   10137:         }
1.554     raeburn  10138:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10139:             if ($recorded{$part_id} eq '') {
                   10140:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10141:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10142:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10143:                     }
                   10144:                 }
                   10145:             }
                   10146:             $record .= $recorded{$part_id};
                   10147:         }
                   10148:     }
                   10149:     return ($counter,$record);
                   10150: }
                   10151: 
1.75      albertel 10152: #-------- end of section for handling grading scantron forms -------
                   10153: #
                   10154: #-------------------------------------------------------------------
                   10155: 
1.72      ng       10156: #-------------------------- Menu interface -------------------------
                   10157: #
1.596.2.12.2.  (raeburn 10158:): #--- Href with symb and command ---
                   10159:): 
                   10160:): sub href_symb_cmd {
                   10161:):     my ($symb,$cmd)=@_;
                   10162:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   10163:): }
                   10164:): 
1.443     banghart 10165: sub grading_menu {
1.596.2.12.2.  1(raebur 10166:0):     my ($request,$symb) = @_;
1.443     banghart 10167:     if (!$symb) {return '';}
                   10168: 
                   10169:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 10170:0):                   'command'=>'individual');
                   10171:0): 
                   10172:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10173:0): 
                   10174:0):     $fields{'command'}='ungraded';
                   10175:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10176:0): 
                   10177:0):     $fields{'command'}='table';
                   10178:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10179:0): 
                   10180:0):     $fields{'command'}='all_for_one';
                   10181:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10182:0): 
                   10183:0):     $fields{'command'}='downloadfilesselect';
                   10184:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10185:     
1.443     banghart 10186:     $fields{'command'} = 'csvform';
1.538     schulted 10187:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10188:     
1.443     banghart 10189:     $fields{'command'} = 'processclicker';
1.538     schulted 10190:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10191:     
1.443     banghart 10192:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10193:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 10194:0): 
                   10195:0):     $fields{'command'} = 'initialverifyreceipt';
                   10196:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
          6(raebur 10197:1): 
                   10198:1):     my %permissions;
                   10199:1):     if ($perm{'mgr'}) {
                   10200:1):         $permissions{'either'} = 'F';
                   10201:1):         $permissions{'mgr'} = 'F';
                   10202:1):     }
                   10203:1):     if ($perm{'vgr'}) {
                   10204:1):         $permissions{'either'} = 'F';
                   10205:1):         $permissions{'vgr'} = 'F';
                   10206:1):     }
                   10207:1): 
          1(raebur 10208:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10209:             items =>[
1.596.2.12.2.  1(raebur 10210:0):                         {       linktext => 'Select individual students to grade',
                   10211:0):                                 url => $url1a,
          6(raebur 10212:1):                                 permission => $permissions{'either'},
          1(raebur 10213:0):                                 icon => 'grade_students.png',
                   10214:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   10215:0):                         },
                   10216:0):                         {       linktext => 'Grade ungraded submissions',
                   10217:0):                                 url => $url1b,
          6(raebur 10218:1):                                 permission => $permissions{'either'},
          1(raebur 10219:0):                                 icon => 'ungrade_sub.png',
                   10220:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   10221:0):                         },
                   10222:0): 
                   10223:0):                         {       linktext => 'Grading table',
                   10224:0):                                 url => $url1c,
          6(raebur 10225:1):                                 permission => $permissions{'either'},
          1(raebur 10226:0):                                 icon => 'grading_table.png',
                   10227:0):                                 linktitle => 'Grade current resource for all students.'
                   10228:0):                         },
                   10229:0):                         {       linktext => 'Grade page/folder for one student',
                   10230:0):                                 url => $url1d,
          6(raebur 10231:1):                                 permission => $permissions{'either'},
          1(raebur 10232:0):                                 icon => 'grade_PageFolder.png',
                   10233:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 10234:                         },
1.596.2.12.2.  3(raebur 10235:0):                         {       linktext => 'Download submitted files',
          1(raebur 10236:0):                                 url => $url1e,
          6(raebur 10237:1):                                 permission => $permissions{'either'},
          1(raebur 10238:0):                                 icon => 'download_sub.png',
          3(raebur 10239:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 10240:0):                         }]},
                   10241:0):                          { categorytitle=>'Automated Grading',
                   10242:0):                items =>[
                   10243:0): 
1.538     schulted 10244:                 	    {	linktext => 'Upload Scores',
                   10245:                     		url => $url2,
1.596.2.12.2.  6(raebur 10246:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10247:                     		icon => 'uploadscores.png',
                   10248:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10249:                 	    },
                   10250:                 	    {	linktext => 'Process Clicker',
                   10251:                     		url => $url3,
1.596.2.12.2.  6(raebur 10252:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10253:                     		icon => 'addClickerInfoFile.png',
                   10254:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10255:                 	    },
1.587     raeburn  10256:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10257:                     		url => $url4,
1.596.2.12.2.  6(raebur 10258:1):                     		permission => $permissions{'mgr'},
          1(raebur 10259:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  10260:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 10261:0):                 	    },
                   10262:0):                             {   linktext => 'Verify Receipt Number',
                   10263:0):                                 url => $url5,
          6(raebur 10264:1):                                 permission => $permissions{'either'},
          1(raebur 10265:0):                                 icon => 'receipt_number.png',
                   10266:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10267:0):                             }
                   10268:0): 
1.538     schulted 10269:                     ]
                   10270:             });
                   10271: 
1.443     banghart 10272:     # Create the menu
                   10273:     my $Str;
1.445     banghart 10274:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10275:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 10276:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 10277: 
1.596.2.12.2.  1(raebur 10278:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10279:     return $Str;    
                   10280: }
                   10281: 
1.596.2.12.2.  1(raebur 10282:0): sub ungraded {
                   10283:0):     my ($request)=@_;
                   10284:0):     &submit_options($request);
                   10285:0): }
1.443     banghart 10286: 
1.596.2.12.2.  1(raebur 10287:0): sub submit_options_sequence {
                   10288:0):     my ($request,$symb) = @_;
1.72      ng       10289:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 10290:0):     &commonJSfunctions($request);
                   10291:0):     my $result;
1.72      ng       10292: 
1.596.2.12.2.  1(raebur 10293:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10294:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10295:0):     $result.=&selectfield(0).
                   10296:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   10297:0):             <div>
                   10298:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10299:0):             </div>
                   10300:0):         </div>
                   10301:0):   </form>';
                   10302:0):     return $result;
                   10303:0): }
                   10304:0): 
                   10305:0): sub submit_options_table {
                   10306:0):     my ($request,$symb) = @_;
                   10307:0):     if (!$symb) {return '';}
1.118     ng       10308:     &commonJSfunctions($request);
1.596.2.12.2.  0.2.4(ra 10309:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
1.473     albertel 10310:     my $result;
1.596.2.12.2.  1(raebur 10311:0): 
                   10312:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10313:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10314:0): 
          0.2.4(ra 10315:ul-23):     $result.=&selectfield(1,$is_tool).
          1(raebur 10316:0):             '<input type="hidden" name="command" value="viewgrades" />
                   10317:0):             <div>
                   10318:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10319:0):             </div>
                   10320:0):         </div>
                   10321:0):   </form>';
                   10322:0):     return $result;
                   10323:0): }
                   10324:0): 
                   10325:0): sub submit_options_download {
                   10326:0):     my ($request,$symb) = @_;
                   10327:0):     if (!$symb) {return '';}
                   10328:0): 
                   10329:0):     my $res_error;
                   10330:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10331:0):         &response_type($symb,\$res_error);
                   10332:0):     if ($res_error) {
                   10333:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10334:0):         return;
                   10335:0):     }
                   10336:0):     unless ($numessay) {
                   10337:0):         $request->print(&mt('No essayresponse items found'));
                   10338:0):         return;
                   10339:0):     }
                   10340:0):     my $table;
                   10341:0):     if (ref($partlist) eq 'ARRAY') {
                   10342:0):         if (scalar(@$partlist) > 1 ) {
                   10343:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10344:         }
                   10345:     }
                   10346: 
1.596.2.12.2.  0.2.4(ra 10347:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          1(raebur 10348:0):     &commonJSfunctions($request);
1.72      ng       10349: 
1.596.2.12.2.  1(raebur 10350:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10351:0):         $table."\n".
                   10352:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10353:     $result.='
1.533     bisitz   10354: <h2>
1.596.2.12.2.  3(raebur 10355:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          0.2.4(ra 10356:ul-23): </h2>'.&selectfield(1,$is_tool).'
          1(raebur 10357:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10358:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10359:0):             </div>
                   10360:0):           </div>
                   10361:0): 
                   10362:0): 
                   10363:0):   </form>';
                   10364:0):     return $result;
                   10365:0): }
                   10366:0): 
                   10367:0): #--- Displays the submissions first page -------
                   10368:0): sub submit_options {
                   10369:0):     my ($request,$symb) = @_;
                   10370:0):     if (!$symb) {return '';}
                   10371:0): 
          0.2.4(ra 10372:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          1(raebur 10373:0):     &commonJSfunctions($request);
                   10374:0):     my $result;
                   10375:0): 
                   10376:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10377:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
          0.2.4(ra 10378:ul-23):     $result.=&selectfield(1,$is_tool).'
          1(raebur 10379:0):                 <input type="hidden" name="command" value="submission" />
                   10380:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10381:0):             </div>
                   10382:0):           </div>
                   10383:0):   </form>';
                   10384:0):     return $result;
                   10385:0): }
                   10386:0): 
                   10387:0): sub selectfield {
          0.2.4(ra 10388:ul-23):    my ($full,$is_tool)=@_;
                   10389:ul-23):    my %options;
                   10390:ul-23):    if ($is_tool) {
                   10391:ul-23):        %options =
                   10392:ul-23):            (&transtatus_options,
                   10393:ul-23):             'select_form_order' => ['yes','incorrect','all']);
                   10394:ul-23):    } else {
                   10395:ul-23):        %options =
                   10396:ul-23):            (&substatus_options,
                   10397:ul-23):             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10398:ul-23):    }
          7(raebur 10399:1): 
                   10400:1):   #
                   10401:1):   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10402:1):   # for a different course from the @Sections global in lonstatistics.pm,
                   10403:1):   # populated by an earlier request.
                   10404:1):   #
                   10405:1):    &Apache::lonstatistics::PrepareClasslist();
                   10406:1): 
          1(raebur 10407:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10408: 
                   10409:     <fieldset>
                   10410:       <legend>
                   10411:        '.&mt('Sections').'
                   10412:       </legend>
1.596.2.12.2.  1(raebur 10413:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10414:     </fieldset>
1.596.2.12.2.  1(raebur 10415:0): 
1.533     bisitz   10416:     <fieldset>
                   10417:       <legend>
                   10418:         '.&mt('Groups').'
                   10419:       </legend>
                   10420:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10421:     </fieldset>
1.596.2.12.2.  1(raebur 10422:0):  
1.533     bisitz   10423:     <fieldset>
                   10424:       <legend>
                   10425:         '.&mt('Access Status').'
                   10426:       </legend>
1.596.2.12.2.  1(raebur 10427:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10428:0):     </fieldset>';
                   10429:0):     if ($full) {
          0.2.4(ra 10430:ul-23):         my $heading = &mt('Submission Status');
                   10431:ul-23):         if ($is_tool) {
                   10432:ul-23):             $heading = &mt('Transaction Status');
                   10433:ul-23):         }
          1(raebur 10434:0):         $result.='
1.533     bisitz   10435:     <fieldset>
                   10436:       <legend>
1.596.2.12.2.  0.2.4(ra 10437:ul-23):         '.$heading.'
          1(raebur 10438:0):       </legend>'.
                   10439:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10440:0):    '</fieldset>';
                   10441:0):     }
                   10442:0):     $result.='</div><br />';
1.44      ng       10443:     return $result;
1.2       albertel 10444: }
                   10445: 
1.596.2.12.2.  7(raebur 10446:6): sub substatus_options {
                   10447:6):     return &Apache::lonlocal::texthash(
                   10448:6):                                       'yes'       => 'with submissions',
                   10449:6):                                       'queued'    => 'in grading queue',
                   10450:6):                                       'graded'    => 'with ungraded submissions',
                   10451:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10452:7):                                       'all'       => 'with any status',
                   10453:7):                                       );
          7(raebur 10454:6): }
                   10455:6): 
          1(raebur 10456:0): sub transtatus_options {
                   10457:0):     return &Apache::lonlocal::texthash(
                   10458:0):                                        'yes'       => 'with score transactions',
                   10459:0):                                        'incorrect' => 'with less than full credit',
                   10460:0):                                        'all'       => 'with any status',
                   10461:0):                                       );
                   10462:0): }
                   10463:0): 
1.285     albertel 10464: sub reset_perm {
                   10465:     undef(%perm);
                   10466: }
                   10467: 
                   10468: sub init_perm {
                   10469:     &reset_perm();
1.300     albertel 10470:     foreach my $test_perm ('vgr','mgr','opa') {
                   10471: 
                   10472: 	my $scope = $env{'request.course.id'};
                   10473: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10474: 
                   10475: 	    $scope .= '/'.$env{'request.course.sec'};
                   10476: 	    if ( $perm{$test_perm}=
                   10477: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10478: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10479: 	    } else {
                   10480: 		delete($perm{$test_perm});
                   10481: 	    }
1.285     albertel 10482: 	}
                   10483:     }
                   10484: }
                   10485: 
1.596.2.12.2.  (raeburn 10486:): sub init_old_essays {
                   10487:):     my ($symb,$apath,$adom,$aname) = @_;
                   10488:):     if ($symb ne '') {
                   10489:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10490:):         if (keys(%essays) > 0) {
                   10491:):             $old_essays{$symb} = \%essays;
                   10492:):         }
                   10493:):     }
                   10494:):     return;
                   10495:): }
                   10496:): 
                   10497:): sub reset_old_essays {
                   10498:):     undef(%old_essays);
                   10499:): }
                   10500:): 
1.400     www      10501: sub gather_clicker_ids {
1.408     albertel 10502:     my %clicker_ids;
1.400     www      10503: 
                   10504:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10505: 
                   10506:     # Set up a couple variables.
1.407     albertel 10507:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10508:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10509:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10510: 
1.407     albertel 10511:     foreach my $student (keys(%$classlist)) {
1.438     www      10512:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10513:         my $username = $classlist->{$student}->[$username_idx];
                   10514:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10515:         my $clickers =
1.408     albertel 10516: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10517:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10518:             $id=~s/^[\#0]+//;
1.421     www      10519:             $id=~s/[\-\:]//g;
1.407     albertel 10520:             if (exists($clicker_ids{$id})) {
1.408     albertel 10521: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10522:             } else {
1.408     albertel 10523: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10524:             }
                   10525:         }
                   10526:     }
1.407     albertel 10527:     return %clicker_ids;
1.400     www      10528: }
                   10529: 
1.402     www      10530: sub gather_adv_clicker_ids {
1.408     albertel 10531:     my %clicker_ids;
1.402     www      10532:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10533:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10534:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10535:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10536:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10537:             my ($puname,$pudom)=split(/\:/,$person);
                   10538:             my $clickers =
1.408     albertel 10539: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10540:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10541: 		$id=~s/^[\#0]+//;
1.421     www      10542:                 $id=~s/[\-\:]//g;
1.408     albertel 10543: 		if (exists($clicker_ids{$id})) {
                   10544: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10545: 		} else {
                   10546: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10547: 		}
1.405     www      10548:             }
1.402     www      10549:         }
                   10550:     }
1.407     albertel 10551:     return %clicker_ids;
1.402     www      10552: }
                   10553: 
1.413     www      10554: sub clicker_grading_parameters {
                   10555:     return ('gradingmechanism' => 'scalar',
                   10556:             'upfiletype' => 'scalar',
                   10557:             'specificid' => 'scalar',
                   10558:             'pcorrect' => 'scalar',
                   10559:             'pincorrect' => 'scalar');
                   10560: }
                   10561: 
1.400     www      10562: sub process_clicker {
1.596.2.12.2.  1(raebur 10563:0):     my ($r,$symb)=@_;
1.400     www      10564:     if (!$symb) {return '';}
                   10565:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10566:0):     $result.=&Apache::loncommon::start_data_table().
                   10567:0):              &Apache::loncommon::start_data_table_header_row().
                   10568:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10569:0):              &Apache::loncommon::end_data_table_header_row().
                   10570:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10571: # Attempt to restore parameters from last session, set defaults if not present
                   10572:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10573:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10574:                                                  \%Saveable_Parameters);
                   10575:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10576:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10577:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10578:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10579: 
                   10580:     my %checked;
1.521     www      10581:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10582:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10583:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10584:        }
                   10585:     }
                   10586: 
1.596.2.12.2.  1(raebur 10587:0):     my $upload=&mt("Evaluate File");
1.400     www      10588:     my $type=&mt("Type");
1.402     www      10589:     my $attendance=&mt("Award points just for participation");
                   10590:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10591:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10592:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10593:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10594:     my $pcorrect=&mt("Percentage points for correct solution");
                   10595:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10596:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10597:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10598:):                                                     'interwrite' => 'interwrite PRS',
                   10599:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10600:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10601:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10602: function sanitycheck() {
                   10603: // Accept only integer percentages
                   10604:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10605:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10606: // Find out grading choice
                   10607:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10608:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10609:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10610:       }
                   10611:    }
                   10612: // By default, new choice equals user selection
                   10613:    newgradingchoice=gradingchoice;
                   10614: // Not good to give more points for false answers than correct ones
                   10615:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10616:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10617:    }
                   10618: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10619:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10620:       document.forms.gradesupload.pcorrect.value=100;
                   10621:       document.forms.gradesupload.pincorrect.value=100;
                   10622:    }
                   10623: // If the values are different, cannot be attendance only
                   10624:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10625:        (gradingchoice=='attendance')) {
                   10626:        newgradingchoice='personnel';
                   10627:    }
                   10628: // Change grading choice to new one
                   10629:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10630:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10631:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10632:       } else {
                   10633:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10634:       }
                   10635:    }
                   10636: // Remember the old state
                   10637:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10638: }
1.596.2.12.2.  1(raebur 10639:0): ENDUPFORM
                   10640:0):     $result.= <<ENDUPFORM;
1.400     www      10641: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10642: <input type="hidden" name="symb" value="$symb" />
                   10643: <input type="hidden" name="command" value="processclickerfile" />
                   10644: <input type="file" name="upfile" size="50" />
                   10645: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10646:0): ENDUPFORM
                   10647:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10648:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10649:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10650: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10651: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10652: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10653: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10654: <br />&nbsp;&nbsp;&nbsp;
                   10655: <input type="text" name="givenanswer" size="50" />
1.413     www      10656: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10657:0): ENDGRADINGFORM
                   10658:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10659:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10660:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10661: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10662: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10663: </form>
1.596.2.12.2.  1(raebur 10664:0): ENDPERCFORM
                   10665:0):     $result.='</td>'.
                   10666:0):              &Apache::loncommon::end_data_table_row().
                   10667:0):              &Apache::loncommon::end_data_table();
1.400     www      10668:     return $result;
                   10669: }
                   10670: 
                   10671: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10672:0):     my ($r,$symb) = @_;
1.400     www      10673:     if (!$symb) {return '';}
1.413     www      10674: 
                   10675:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10676:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10677:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10678:0):     my $result='';
1.404     www      10679:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10680: 	$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 10681:0): 	return $result;
1.404     www      10682:     }
1.522     www      10683:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10684:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10685:0):         return $result;
1.521     www      10686:     }
1.522     www      10687:     my $foundgiven=0;
1.521     www      10688:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10689:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10690:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10691:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10692:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10693:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10694:         $foundgiven=$#answers+1;
1.521     www      10695:     }
1.407     albertel 10696:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10697:     my %correct_ids;
1.404     www      10698:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10699: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10700:     }
                   10701:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10702: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10703: 	   $correct_id=~tr/a-z/A-Z/;
                   10704: 	   $correct_id=~s/\s//gs;
                   10705: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10706:            $correct_id=~s/[\-\:]//g;
1.414     www      10707:            if ($correct_id) {
                   10708: 	      $correct_ids{$correct_id}='specified';
                   10709:            }
                   10710:         }
1.400     www      10711:     }
1.404     www      10712:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10713: 	$result.=&mt('Score based on attendance only');
1.521     www      10714:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10715:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10716:     } else {
1.408     albertel 10717: 	my $number=0;
1.411     www      10718: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10719: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10720: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10721: 	    if ($correct_ids{$id} eq 'specified') {
                   10722: 		$result.=&mt('specified');
                   10723: 	    } else {
                   10724: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10725: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10726: 	    }
                   10727: 	    $number++;
                   10728: 	}
1.411     www      10729:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10730:3):         if ($number==0) {
                   10731:3):             $result .=
                   10732:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10733:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10734:0):             return $result;
          5(raebur 10735:3):         }
1.404     www      10736:     }
1.405     www      10737:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10738:3):         $result .=
                   10739:3):             &Apache::lonhtmlcommon::confirm_success(
                   10740:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10741:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10742:0):         return $result;
1.405     www      10743:     }
1.596.2.12.2.  7(raebur 10744:9):     my $mimetype;
                   10745:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10746:9):         my $mm = new File::MMagic;
                   10747:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10748:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10749:9):             $result.= '<p>'.
                   10750:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10751:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10752:0):             return $result;
          7(raebur 10753:9):         }
                   10754:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10755:9):         $result .= '<p>'.
                   10756:9):             &Apache::lonhtmlcommon::confirm_success(
                   10757:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10758:0):         return $result;
          7(raebur 10759:9):     }
1.410     www      10760: 
                   10761: # Were able to get all the info needed, now analyze the file
                   10762: 
1.411     www      10763:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10764:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10765:0):     $result.=&Apache::loncommon::start_data_table().
                   10766:0):              &Apache::loncommon::start_data_table_header_row().
                   10767:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10768:0):              &Apache::loncommon::end_data_table_header_row().
                   10769:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10770:0): <td>
1.410     www      10771: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10772: <input type="hidden" name="symb" value="$symb" />
                   10773: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10774: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10775: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10776: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10777: ENDHEADER
1.522     www      10778:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10779:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10780:     } 
1.408     albertel 10781:     my %responses;
                   10782:     my @questiontitles;
1.405     www      10783:     my $errormsg='';
                   10784:     my $number=0;
                   10785:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10786:9):         if ($mimetype eq 'text/plain') {
                   10787:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10788:9):         } elsif ($mimetype eq 'text/html') {
                   10789:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10790:9):         }
                   10791:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10792:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10793:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10794:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10795:):     }
1.411     www      10796:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10797:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10798:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10799:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10800:              '<br />';
1.522     www      10801:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10802:        $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 10803:0):        return $result;
1.522     www      10804:     } 
1.414     www      10805: # Remember Question Titles
                   10806: # FIXME: Possibly need delimiter other than ":"
                   10807:     for (my $i=0;$i<$number;$i++) {
                   10808:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10809:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10810:     }
1.411     www      10811:     my $correct_count=0;
                   10812:     my $student_count=0;
                   10813:     my $unknown_count=0;
1.414     www      10814: # Match answers with usernames
                   10815: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10816:     foreach my $id (keys(%responses)) {
1.410     www      10817:        if ($correct_ids{$id}) {
1.414     www      10818:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10819:           $correct_count++;
1.410     www      10820:        } elsif ($clicker_ids{$id}) {
1.437     www      10821:           if ($clicker_ids{$id}=~/\,/) {
                   10822: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10823:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10824:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10825:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10826:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10827:                            "<select name='multi".$id."'>";
                   10828:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10829:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10830:              }
                   10831:              $result.='</select>';
                   10832:              $unknown_count++;
                   10833:           } else {
                   10834: # Good: found one and only one user with the right clicker
                   10835:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10836:              $student_count++;
                   10837:           }
1.410     www      10838:        } else {
1.596.2.12.2.  1(raebur 10839:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10840:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10841:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10842:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10843:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10844:                    "\n".&mt("Domain").": ".
                   10845:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10846:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10847:           $unknown_count++;
1.410     www      10848:        }
1.405     www      10849:     }
1.412     www      10850:     $result.='<hr />'.
                   10851:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10852:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10853:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10854:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10855:        } elsif ($correct_count>1) {
1.414     www      10856:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10857:        }
                   10858:     }
1.428     www      10859:     if ($number<1) {
                   10860:        $errormsg.="Found no questions.";
                   10861:     }
1.412     www      10862:     if ($errormsg) {
                   10863:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10864:     } else {
                   10865:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10866:     }
1.596.2.12.2.  1(raebur 10867:0):     $result.='</form></td>'.
                   10868:0):              &Apache::loncommon::end_data_table_row().
                   10869:0):              &Apache::loncommon::end_data_table();
                   10870:0):     return $result;
1.400     www      10871: }
                   10872: 
1.405     www      10873: sub iclicker_eval {
1.406     www      10874:     my ($questiontitles,$responses)=@_;
1.405     www      10875:     my $number=0;
                   10876:     my $errormsg='';
                   10877:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10878:         my %components=&Apache::loncommon::record_sep($line);
                   10879:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10880: 	if ($entries[0] eq 'Question') {
                   10881: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10882: 		$$questiontitles[$number]=$entries[$i];
                   10883: 		$number++;
                   10884: 	    }
                   10885: 	}
                   10886: 	if ($entries[0]=~/^\#/) {
                   10887: 	    my $id=$entries[0];
                   10888: 	    my @idresponses;
                   10889: 	    $id=~s/^[\#0]+//;
                   10890: 	    for (my $i=0;$i<$number;$i++) {
                   10891: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10892:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10893: 		push(@idresponses,$entries[$idx]);
                   10894: 	    }
                   10895: 	    $$responses{$id}=join(',',@idresponses);
                   10896: 	}
1.405     www      10897:     }
                   10898:     return ($errormsg,$number);
                   10899: }
                   10900: 
1.596.2.12.2.  7(raebur 10901:9): sub iclickerxml_eval {
                   10902:9):     my ($questiontitles,$responses)=@_;
                   10903:9):     my $number=0;
                   10904:9):     my $errormsg='';
                   10905:9):     my @state;
                   10906:9):     my %respbyid;
                   10907:9):     my $p = HTML::Parser->new
                   10908:9):     (
                   10909:9):         xml_mode => 1,
                   10910:9):         start_h =>
                   10911:9):             [sub {
                   10912:9):                  my ($tagname,$attr) = @_;
                   10913:9):                  push(@state,$tagname);
                   10914:9):                  if ("@state" eq "ssn p") {
                   10915:9):                      my $title = $attr->{qn};
                   10916:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10917:9):                      $questiontitles->[$number]=$title;
                   10918:9):                  } elsif ("@state" eq "ssn p v") {
                   10919:9):                      my $id = $attr->{id};
                   10920:9):                      my $entry = $attr->{ans};
                   10921:9):                      $id=~s/^[\#0]+//;
                   10922:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10923:9):                      $respbyid{$id}[$number] = $entry;
                   10924:9):                  }
                   10925:9):             }, "tagname, attr"],
                   10926:9):          end_h =>
                   10927:9):                [sub {
                   10928:9):                    my ($tagname) = @_;
                   10929:9):                    if ("@state" eq "ssn p") {
                   10930:9):                        $number++;
                   10931:9):                    }
                   10932:9):                    pop(@state);
                   10933:9):                 }, "tagname"],
                   10934:9):     );
                   10935:9): 
                   10936:9):     $p->parse($env{'form.upfile'});
                   10937:9):     $p->eof;
                   10938:9):     foreach my $id (keys(%respbyid)) {
                   10939:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10940:9):     }
                   10941:9):     return ($errormsg,$number);
                   10942:9): }
                   10943:9): 
1.419     www      10944: sub interwrite_eval {
                   10945:     my ($questiontitles,$responses)=@_;
                   10946:     my $number=0;
                   10947:     my $errormsg='';
1.420     www      10948:     my $skipline=1;
                   10949:     my $questionnumber=0;
                   10950:     my %idresponses=();
1.419     www      10951:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10952:         my %components=&Apache::loncommon::record_sep($line);
                   10953:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10954:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10955:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10956:         next if $skipline;
                   10957:         if ($entries[0]!=$questionnumber) {
                   10958:            $questionnumber=$entries[0];
                   10959:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10960:            $number++;
1.419     www      10961:         }
1.420     www      10962:         my $id=$entries[4];
                   10963:         $id=~s/^[\#0]+//;
1.421     www      10964:         $id=~s/^v\d*\://i;
                   10965:         $id=~s/[\-\:]//g;
1.420     www      10966:         $idresponses{$id}[$number]=$entries[6];
                   10967:     }
1.524     raeburn  10968:     foreach my $id (keys(%idresponses)) {
1.420     www      10969:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10970:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10971:     }
                   10972:     return ($errormsg,$number);
                   10973: }
                   10974: 
1.596.2.12.2.  (raeburn 10975:): sub turning_eval {
                   10976:):     my ($questiontitles,$responses)=@_;
                   10977:):     my $number=0;
                   10978:):     my $errormsg='';
                   10979:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10980:):         my %components=&Apache::loncommon::record_sep($line);
                   10981:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10982:):         if ($#entries>$number) { $number=$#entries; }
                   10983:):         my $id=$entries[0];
                   10984:):         my @idresponses;
                   10985:):         $id=~s/^[\#0]+//;
                   10986:):         unless ($id) { next; }
                   10987:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10988:):             $entries[$idx]=~s/\,/\;/g;
                   10989:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10990:):             push(@idresponses,$entries[$idx]);
                   10991:):         }
                   10992:):         $$responses{$id}=join(',',@idresponses);
                   10993:):     }
                   10994:):     for (my $i=1; $i<=$number; $i++) {
                   10995:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10996:):     }
                   10997:):     return ($errormsg,$number);
                   10998:): }
                   10999:): 
1.414     www      11000: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 11001:0):     my ($r,$symb) = @_;
1.414     www      11002:     if (!$symb) {return '';}
1.416     www      11003: # See which part we are saving to
1.582     raeburn  11004:     my $res_error;
                   11005:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11006:     if ($res_error) {
                   11007:         return &navmap_errormsg();
                   11008:     }
1.416     www      11009: # FIXME: This should probably look for the first handgradeable part
                   11010:     my $part=$$partlist[0];
                   11011: # Start screen output
1.596.2.12.2.  1(raebur 11012:0):     my $result = &Apache::loncommon::start_data_table(). 
                   11013:0):                  &Apache::loncommon::start_data_table_header_row().
                   11014:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11015:0):                  &Apache::loncommon::end_data_table_header_row().
                   11016:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11017: # Get correct result
                   11018: # FIXME: Possibly need delimiter other than ":"
                   11019:     my @correct=();
1.415     www      11020:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11021:     my $number=$env{'form.number'};
                   11022:     if ($gradingmechanism ne 'attendance') {
1.414     www      11023:        foreach my $key (keys(%env)) {
                   11024:           if ($key=~/^form\.correct\:/) {
                   11025:              my @input=split(/\,/,$env{$key});
                   11026:              for (my $i=0;$i<=$#input;$i++) {
                   11027:                  if (($correct[$i]) && ($input[$i]) &&
                   11028:                      ($correct[$i] ne $input[$i])) {
                   11029:                     $result.='<br /><span class="LC_warning">'.
                   11030:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11031:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  11032:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11033:                     $correct[$i]=$input[$i];
                   11034:                  }
                   11035:              }
                   11036:           }
                   11037:        }
1.415     www      11038:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  11039:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11040:              $result.='<br /><span class="LC_error">'.
                   11041:                       &mt('No correct result given for question "[_1]"!',
                   11042:                           $env{'form.question:'.$i}).'</span>';
                   11043:           }
                   11044:        }
1.596.2.4  raeburn  11045:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11046:     }
                   11047: # Start grading
1.415     www      11048:     my $pcorrect=$env{'form.pcorrect'};
                   11049:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11050:     my $storecount=0;
1.596.2.4  raeburn  11051:     my %users=();
1.415     www      11052:     foreach my $key (keys(%env)) {
1.420     www      11053:        my $user='';
1.415     www      11054:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11055:           $user=$1;
                   11056:        }
                   11057:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11058:           my $id=$1;
                   11059:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11060:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11061:           } elsif ($env{'form.multi'.$id}) {
                   11062:              $user=$env{'form.multi'.$id};
1.420     www      11063:           }
                   11064:        }
1.596.2.4  raeburn  11065:        if ($user) {
                   11066:           if ($users{$user}) {
                   11067:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 11068:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  11069:                       '</span><br />';
                   11070:           }
                   11071:           $users{$user}=1;
1.415     www      11072:           my @answer=split(/\,/,$env{$key});
                   11073:           my $sum=0;
1.522     www      11074:           my $realnumber=$number;
1.415     www      11075:           for (my $i=0;$i<$number;$i++) {
1.576     www      11076:              if  ($correct[$i] eq '-') {
                   11077:                 $realnumber--;
1.596.2.12.2.  1(raebur 11078:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11079:                 if ($gradingmechanism eq 'attendance') {
                   11080:                    $sum+=$pcorrect;
1.576     www      11081:                 } elsif ($correct[$i] eq '*') {
1.522     www      11082:                    $sum+=$pcorrect;
1.415     www      11083:                 } else {
1.596.2.4  raeburn  11084: # We actually grade if correct or not
                   11085:                    my $increment=$pincorrect;
                   11086: # Special case: numerical answer "0"
                   11087:                    if ($correct[$i] eq '0') {
                   11088:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11089:                          $increment=$pcorrect;
                   11090:                       }
                   11091: # General numerical answer, both evaluate to something non-zero
                   11092:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11093:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11094:                          $increment=$pcorrect;
                   11095:                       }
                   11096: # Must be just alphanumeric
                   11097:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11098:                       $increment=$pcorrect;
1.415     www      11099:                    }
1.596.2.4  raeburn  11100:                    $sum+=$increment;
1.415     www      11101:                 }
                   11102:              }
                   11103:           }
1.522     www      11104:           my $ave=$sum/(100*$realnumber);
1.416     www      11105: # Store
                   11106:           my ($username,$domain)=split(/\:/,$user);
                   11107:           my %grades=();
                   11108:           $grades{"resource.$part.solved"}='correct_by_override';
                   11109:           $grades{"resource.$part.awarded"}=$ave;
                   11110:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11111:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11112:                                                  $env{'request.course.id'},
                   11113:                                                  $domain,$username);
                   11114:           if ($returncode ne 'ok') {
                   11115:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11116:           } else {
                   11117:              $storecount++;
                   11118:           }
1.415     www      11119:        }
                   11120:     }
                   11121: # We are done
1.549     hauer    11122:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  11123:              '</td>'.
                   11124:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 11125:0):              &Apache::loncommon::end_data_table();
                   11126:0):     return $result;
1.414     www      11127: }
                   11128: 
1.582     raeburn  11129: sub navmap_errormsg {
                   11130:     return '<div class="LC_error">'.
                   11131:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11132:            &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  11133:            '</div>';
                   11134: }
                   11135: 
1.596.2.12.2.  (raeburn 11136:): sub startpage {
          5(raebur 11137:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
          9(raebur 11138:9):     my %args;
                   11139:9):     if ($onload) {
                   11140:9):          my %loaditems = (
                   11141:9):                         'onload' => $onload,
                   11142:9):                       );
                   11143:9):          $args{'add_entries'} = \%loaditems;
                   11144:9):     }
          (raeburn 11145:):     if ($nomenu) {
          9(raebur 11146:9):         $args{'only_body'} = 1;
          5(raebur 11147:0):         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
          (raeburn 11148:):     } else {
          8(raebur 11149:1):         if ($env{'request.course.id'}) {
                   11150:1):             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11151:1):         }
          9(raebur 11152:9):         $args{'bread_crumbs'} = $crumbs;
          5(raebur 11153:0):         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
          (raeburn 11154:):     }
                   11155:):     unless ($nodisplayflag) {
          1(raebur 11156:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 11157:):     }
                   11158:): }
                   11159:): 
          1(raebur 11160:0): sub select_problem {
                   11161:0):     my ($r)=@_;
                   11162:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   11163:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   11164:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11165:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11166:0): }
                   11167:0): 
          0.2.5(ra 11168:ep-23): #----- display problem, answer, and submissions for a single student (no grading)
                   11169:ep-23): 
                   11170:ep-23): sub view_as_user {
                   11171:ep-23):     my ($symb,$vuname,$vudom,$hasperm) = @_;
                   11172:ep-23):     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
                   11173:ep-23):     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
                   11174:ep-23):     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
                   11175:ep-23):                                                       $env{'request.course.id'},
                   11176:ep-23):                                                       undef,{'disable_submit' => 1}).
                   11177:ep-23):                  "\n\n".
                   11178:ep-23):                  '<div class="LC_grade_show_user">'.
                   11179:ep-23):                  '<h2>'.$displayname.'</h2>'.
                   11180:ep-23):                  "\n".
                   11181:ep-23):                  &Apache::loncommon::track_student_link('View recent activity',
                   11182:ep-23):                                                         $vuname,$vudom,'check').' '.
                   11183:ep-23):                  "\n";
                   11184:ep-23):     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
                   11185:ep-23):         (($env{'request.course.sec'} ne '') &&
                   11186:ep-23):          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
                   11187:ep-23):         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   11188:ep-23):                                                $vuname,$vudom,$symb,'check');
                   11189:ep-23):     }
                   11190:ep-23):     $output .= "\n";
                   11191:ep-23):     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
                   11192:ep-23):                                                              $env{'request.course.id'});
                   11193:ep-23):     $companswer=~s|<form(.*?)>||g;
                   11194:ep-23):     $companswer=~s|</form>||g;
                   11195:ep-23):     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
                   11196:ep-23):     $output .= '<div class="LC_Box">'.
                   11197:ep-23):                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
                   11198:ep-23):                $companswer.
                   11199:ep-23):                '</div>'."\n";
                   11200:ep-23):     my $is_tool = ($symb =~ /ext\.tool$/);
                   11201:ep-23):     my ($essayurl,%coursedesc_by_cid);
                   11202:ep-23):     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   11203:ep-23):     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
                   11204:ep-23):     my $res_error;
                   11205:ep-23):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   11206:ep-23):         &response_type($symb,\$res_error);
                   11207:ep-23):     my $fullname;
                   11208:ep-23):     my $collabinfo;
                   11209:ep-23):     if ($numessay) {
                   11210:ep-23):         unless ($hasperm) {
                   11211:ep-23):             &init_perm();
                   11212:ep-23):         }
                   11213:ep-23):         ($collabinfo,$fullname)=
                   11214:ep-23):             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
                   11215:ep-23):         unless ($hasperm) {
                   11216:ep-23):             &reset_perm();
                   11217:ep-23):         }
                   11218:ep-23):     }
                   11219:ep-23):     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   11220:ep-23):                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
                   11221:ep-23):                     '/check.gif" height="16" border="0" />';
                   11222:ep-23):     my ($lastsubonly,$partinfo) =
                   11223:ep-23):         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
                   11224:ep-23):                               '',$fullname,\%record,\%coursedesc_by_cid);
                   11225:ep-23):     $output .= '<div class="LC_Box">'.
                   11226:ep-23):                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
                   11227:ep-23):     if (($numresp > $numessay) & !$is_tool) {
                   11228:ep-23):         $output .='<p class="LC_info">'.
                   11229:ep-23):                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
                   11230:ep-23):                   "</p>\n";
                   11231:ep-23):     }
                   11232:ep-23):     $output .= $partinfo;
                   11233:ep-23):     $output .= $lastsubonly;
                   11234:ep-23):     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
                   11235:ep-23):     $output .= '</div></div>'."\n";
                   11236:ep-23):     return $output;
                   11237:ep-23): }
                   11238:ep-23): 
1.1       albertel 11239: sub handler {
1.41      ng       11240:     my $request=$_[0];
1.434     albertel 11241:     &reset_caches();
1.596.2.4  raeburn  11242:     if ($request->header_only) {
                   11243:         &Apache::loncommon::content_type($request,'text/html');
                   11244:         $request->send_http_header;
                   11245:         return OK;
1.41      ng       11246:     }
                   11247:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  11248: 
1.596.2.12.2.  1(raebur 11249:0): # see what command we need to execute
                   11250:0):  
1.160     albertel 11251:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11252:     my $command=$commands[0];
1.447     foxr     11253: 
1.596.2.12.2.  1(raebur 11254:0):     &init_perm();
                   11255:0):     if (!$env{'request.course.id'}) {
                   11256:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11257:0):                 ($command =~ /^scantronupload/)) {
                   11258:0):             # Not in a course.
                   11259:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11260:0):             return HTTP_NOT_ACCEPTABLE;
                   11261:0):         }
                   11262:0):     } elsif (!%perm) {
                   11263:0):         $request->internal_redirect('/adm/quickgrades');
                   11264:0):         return OK;
                   11265:0):     }
                   11266:0):     &Apache::loncommon::content_type($request,'text/html');
                   11267:0):     $request->send_http_header;
                   11268:0): 
1.160     albertel 11269:     if ($#commands > 0) {
                   11270: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11271:     }
1.447     foxr     11272: 
1.596.2.12.2.  1(raebur 11273:0): # see what the symb is
                   11274:0): 
                   11275:0):     my $symb=$env{'form.symb'};
                   11276:0):     unless ($symb) {
                   11277:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11278:0):        $symb=&Apache::lonnet::symbread($url);
                   11279:0):     }
                   11280:0):     &Apache::lonenc::check_decrypt(\$symb);
                   11281:0): 
1.513     foxr     11282:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 11283:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   11284:0): #
                   11285:0): # Not called from a resource, but inside a course
                   11286:0): #
                   11287:0):         &startpage($request,undef,[],1,1);
                   11288:0):         &select_problem($request);
1.41      ng       11289:     } else {
1.596.2.12.2.  1(raebur 11290:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   11291:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 11292:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11293:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11294:):                     &choose_task_version_form($symb,$env{'form.student'},
                   11295:):                                               $env{'form.userdom'});
                   11296:):             }
          1(raebur 11297:0):             my $divforres;
                   11298:0):             if ($env{'form.student'} eq '') {
                   11299:0):                 $js .= &part_selector_js();
                   11300:0):                 $onload = "toggleParts('gradesub');";
                   11301:0):             } else {
                   11302:0):                 $divforres = 1;
                   11303:0):             }
          5(raebur 11304:0):             my $head_extra = $js;
                   11305:0):             unless ($env{'form.vProb'} eq 'no') {
                   11306:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11307:0):                 if ($csslinks) {
                   11308:0):                     $head_extra .= "\n$csslinks";
                   11309:0):                 }
                   11310:0):             }
                   11311:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11312:0):                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
          (raeburn 11313:):             if ($versionform) {
          2(raebur 11314:0):                 if ($divforres) {
                   11315:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11316:0):                 }
          (raeburn 11317:):                 $request->print($versionform);
                   11318:):             }
          1(raebur 11319:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 11320:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11321:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11322:):                 &choose_task_version_form($symb,$env{'form.student'},
                   11323:):                                           $env{'form.userdom'},
                   11324:):                                           $env{'form.inhibitmenu'});
          5(raebur 11325:0):             my $head_extra = $js;
                   11326:0):             unless ($env{'form.vProb'} eq 'no') {
                   11327:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11328:0):                 if ($csslinks) {
                   11329:0):                     $head_extra .= "\n$csslinks";
                   11330:0):                 }
                   11331:0):             }
                   11332:0):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11333:0):                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
          (raeburn 11334:):             if ($versionform) {
                   11335:):                 $request->print($versionform);
                   11336:):             }
                   11337:):             $request->print('<br clear="all" />');
                   11338:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 11339:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   11340:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11341:0):                                        {href=>'',text=>'Select student'}],1,1);
                   11342:0):             &pickStudentPage($request,$symb);
                   11343:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
          5(raebur 11344:0):             my $csslinks;
                   11345:0):             unless ($env{'form.vProb'} eq 'no') {
                   11346:0):                 $csslinks = &Apache::loncommon::css_links($symb,'map');
                   11347:0):             }
          1(raebur 11348:0):             &startpage($request,$symb,
                   11349:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11350:0):                                        {href=>'',text=>'Select student'},
          5(raebur 11351:0):                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
          1(raebur 11352:0):             &displayPage($request,$symb);
                   11353:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   11354:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11355:0):                                        {href=>'',text=>'Select student'},
                   11356:0):                                        {href=>'',text=>'Grade student'},
                   11357:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   11358:0):             &updateGradeByPage($request,$symb);
                   11359:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
          5(raebur 11360:0):             my $csslinks;
                   11361:0):             unless ($env{'form.vProb'} eq 'no') {
                   11362:0):                 $csslinks = &Apache::loncommon::css_links($symb);
                   11363:0):             }
          1(raebur 11364:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
          5(raebur 11365:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
          1(raebur 11366:0):             &processGroup($request,$symb);
                   11367:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   11368:0):             &startpage($request,$symb);
                   11369:0):             $request->print(&grading_menu($request,$symb));
                   11370:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   11371:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   11372:0):             $request->print(&submit_options($request,$symb));
                   11373:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   11374:0):             my $js = &part_selector_js();
                   11375:0):             my $onload = "toggleParts('gradesub');";
                   11376:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11377:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11378:0):             $request->print(&listStudents($request,$symb,'graded'));
                   11379:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   11380:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   11381:0):             $request->print(&submit_options_table($request,$symb));
                   11382:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   11383:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   11384:0):             $request->print(&submit_options_sequence($request,$symb));
                   11385:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   11386:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   11387:0):             $request->print(&viewgrades($request,$symb));
                   11388:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   11389:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11390:0):                                        {href=>'',text=>'Store grades'}]);
                   11391:0):             $request->print(&processHandGrade($request,$symb));
                   11392:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   11393:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11394:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11395:0):                                                                              text=>"Modify grades"},
                   11396:0):                                        {href=>'', text=>"Store grades"}]);
                   11397:0):             $request->print(&editgrades($request,$symb));
                   11398:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   11399:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   11400:0):             $request->print(&initialverifyreceipt($request,$symb));
                   11401:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   11402:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11403:0):                                        {href=>'',text=>'Verification Result'}]);
                   11404:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      11405:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11406:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   11407:0):             $request->print(&process_clicker($request,$symb));
1.400     www      11408:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11409:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11410:0):                                        {href=>'', text=>'Process clicker file'}]);
                   11411:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      11412:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11413:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11414:0):                                        {href=>'', text=>'Process clicker file'},
                   11415:0):                                        {href=>'', text=>'Store grades'}]);
                   11416:0):             $request->print(&assign_clicker_grades($request,$symb));
                   11417:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   11418:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11419:0):             $request->print(&upcsvScores_form($request,$symb));
                   11420:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   11421:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11422:0):             $request->print(&csvupload($request,$symb));
                   11423:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   11424:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11425:0):             $request->print(&csvuploadmap($request,$symb));
                   11426:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   11427:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   11428:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11429:0):                 $request->print(&csvuploadoptions($request,$symb));
                   11430:0):             } else {
                   11431:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11432:0):                     $env{'form.upfile_associate'} = 'reverse';
                   11433:0):                 } else {
                   11434:0):                     $env{'form.upfile_associate'} = 'forward';
                   11435:0):                 }
                   11436:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11437:0):                 $request->print(&csvuploadmap($request,$symb));
                   11438:0):             }
                   11439:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   11440:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11441:0):             $request->print(&csvuploadassign($request,$symb));
                   11442:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   11443:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11444:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11445:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   11446:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   11447:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11448:0):             $request->print(&scantron_do_warning($request,$symb));
                   11449:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11450:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11451:0):             $request->print(&scantron_validate_file($request,$symb));
                   11452:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11453:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11454:0):             $request->print(&scantron_process_students($request,$symb));
                   11455:0):         } elsif ($command eq 'scantronupload' &&
                   11456:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11457:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11458:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11459:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11460:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11461:0):         } elsif ($command eq 'scantronupload_save' &&
                   11462:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11463:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11464:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11465:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11466:0):         } elsif ($command eq 'scantron_download' &&
                   11467:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11468:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11469:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11470:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11471:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11472:0):             $request->print(&checkscantron_results($request,$symb));
                   11473:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11474:0):             my $js = &part_selector_js();
                   11475:0):             my $onload = "toggleParts('gradingMenu');";
                   11476:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11477:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11478:0):             $request->print(&submit_options_download($request,$symb));
                   11479:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11480:0):             &startpage($request,$symb,
                   11481:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11482:0):     {href=>'', text=>'Download submitted files'}],
                   11483:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11484:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11485:0):             &submit_download_link($request,$symb);
                   11486:0):         } elsif ($command) {
                   11487:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11488:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11489:0):         }
1.2       albertel 11490:     }
1.513     foxr     11491:     if ($ssi_error) {
                   11492: 	&ssi_print_error($request);
                   11493:     }
1.353     albertel 11494:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11495:     &reset_caches();
1.596.2.4  raeburn  11496:     return OK;
1.44      ng       11497: }
                   11498: 
1.1       albertel 11499: 1;
                   11500: 
1.13      albertel 11501: __END__;
1.531     jms      11502: 
                   11503: 
                   11504: =head1 NAME
                   11505: 
                   11506: Apache::grades
                   11507: 
                   11508: =head1 SYNOPSIS
                   11509: 
                   11510: Handles the viewing of grades.
                   11511: 
                   11512: This is part of the LearningOnline Network with CAPA project
                   11513: described at http://www.lon-capa.org.
                   11514: 
                   11515: =head1 OVERVIEW
                   11516: 
                   11517: Do an ssi with retries:
                   11518: While I'd love to factor out this with the vesrion in lonprintout,
                   11519: 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
                   11520: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11521: 
                   11522: At least the logic that drives this has been pulled out into loncommon.
                   11523: 
                   11524: 
                   11525: 
                   11526: ssi_with_retries - Does the server side include of a resource.
                   11527:                      if the ssi call returns an error we'll retry it up to
                   11528:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11529:4):                      If we still have a problem, no text is appended to the
1.531     jms      11530:                      output and we set some global variables.
                   11531:                      to indicate to the caller an SSI error occurred.  
                   11532:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11533:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11534:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11535:                      by informing the user that this happened.
                   11536: 
                   11537: Parameters:
                   11538:   resource   - The resource to include.  This is passed directly, without
                   11539:                interpretation to lonnet::ssi.
                   11540:   form       - The form hash parameters that guide the interpretation of the resource
                   11541:                
                   11542:   retries    - Number of retries allowed before giving up completely.
                   11543: Returns:
                   11544:   On success, returns the rendered resource identified by the resource parameter.
                   11545: Side Effects:
                   11546:   The following global variables can be set:
                   11547:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11548:                               It is up to the caller to initialize this to false
                   11549:                               if desired.
                   11550:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11551:                               of the resource that could not be rendered by the ssi
                   11552:                               call.
                   11553:    ssi_error_message   - The error string fetched from the ssi response
                   11554:                               in the event of an error.
                   11555: 
                   11556: 
                   11557: =head1 HANDLER SUBROUTINE
                   11558: 
                   11559: ssi_with_retries()
                   11560: 
                   11561: =head1 SUBROUTINES
                   11562: 
                   11563: =over
                   11564: 
                   11565: =item scantron_get_correction() : 
                   11566: 
                   11567:    Builds the interface screen to interact with the operator to fix a
                   11568:    specific error condition in a specific scanline
                   11569: 
                   11570:  Arguments:
                   11571:     $r           - Apache request object
                   11572:     $i           - number of the current scanline
                   11573:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11574:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11575:     $line        - full contents of the current scanline
                   11576:     $error       - error condition, valid values are
                   11577:                    'incorrectCODE', 'duplicateCODE',
                   11578:                    'doublebubble', 'missingbubble',
                   11579:                    'duplicateID', 'incorrectID'
                   11580:     $arg         - extra information needed
                   11581:        For errors:
                   11582:          - duplicateID   - paper number that this studentID was seen before on
                   11583:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11584:                            seen on before
                   11585:          - incorrectCODE - current incorrect CODE 
                   11586:          - doublebubble  - array ref of the bubble lines that have double
                   11587:                            bubble errors
                   11588:          - missingbubble - array ref of the bubble lines that have missing
                   11589:                            bubble errors
                   11590: 
1.596.2.12.2.  0(raebur 11591:2):    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   11592:2):    $randompick  - True if exam folder (or a sub-folder) has randompick set
          6(raebur 11593:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11594:3):                      for current line to question number used for same question
                   11595:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11596:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11597:3):                   and value is number of first bubble line for current student
                   11598:3):                   or code-based randompick and/or randomorder.
                   11599:3): 
                   11600:3): 
1.531     jms      11601: =item  scantron_get_maxbubble() : 
                   11602: 
1.582     raeburn  11603:    Arguments:
                   11604:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11605:                       failure to retrieve a navmap object.
                   11606:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11607:        calling routine should trap the error condition and display the warning
                   11608:        found in &navmap_errormsg().
                   11609: 
1.596.2.12.2.  (raeburn 11610:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11611:): 
1.531     jms      11612:    Returns the maximum number of bubble lines that are expected to
                   11613:    occur. Does this by walking the selected sequence rendering the
                   11614:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11615:    for what the current value of the problem counter is.
                   11616: 
                   11617:    Caches the results to $env{'form.scantron_maxbubble'},
                   11618:    $env{'form.scantron.bubble_lines.n'}, 
                   11619:    $env{'form.scantron.first_bubble_line.n'} and
                   11620:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11621:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11622:    lines for response n and number of the first bubble line for response n,
                   11623:    and a comma separated list of numbers of bubble lines for sub-questions
                   11624:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11625: 
                   11626: 
                   11627: =item  scantron_validate_missingbubbles() : 
                   11628: 
                   11629:    Validates all scanlines in the selected file to not have any
                   11630:     answers that don't have bubbles that have not been verified
                   11631:     to be bubble free.
                   11632: 
                   11633: =item  scantron_process_students() : 
                   11634: 
1.596.2.6  raeburn  11635:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11636: 
                   11637:    The parsed scanline hash is added to %env 
                   11638: 
                   11639:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11640:    foreach resource , with the form data of
                   11641: 
                   11642: 	'submitted'     =>'scantron' 
                   11643: 	'grade_target'  =>'grade',
                   11644: 	'grade_username'=> username of student
                   11645: 	'grade_domain'  => domain of student
                   11646: 	'grade_courseid'=> of course
                   11647: 	'grade_symb'    => symb of resource to grade
                   11648: 
                   11649:     This triggers a grading pass. The problem grading code takes care
                   11650:     of converting the bubbled letter information (now in %env) into a
                   11651:     valid submission.
                   11652: 
                   11653: =item  scantron_upload_scantron_data() :
                   11654: 
1.596.2.6  raeburn  11655:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11656: 
                   11657: =item  scantron_upload_scantron_data_save() : 
                   11658: 
                   11659:    Adds a provided bubble information data file to the course if user
                   11660:    has the correct privileges to do so. 
                   11661: 
                   11662: =item  valid_file() :
                   11663: 
                   11664:    Validates that the requested bubble data file exists in the course.
                   11665: 
                   11666: =item  scantron_download_scantron_data() : 
                   11667: 
                   11668:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11669:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11670:    course.
                   11671: 
                   11672: =item  scantron_validate_ID() : 
                   11673: 
                   11674:    Validates all scanlines in the selected file to not have any
1.556     weissno  11675:    invalid or underspecified student/employee IDs
1.531     jms      11676: 
1.582     raeburn  11677: =item navmap_errormsg() :
                   11678: 
                   11679:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11680:    Should be called whenever the request to instantiate a navmap object fails.  
                   11681: 
1.531     jms      11682: =back
                   11683: 
                   11684: =cut

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