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

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.4(ra    4:ul-23): # $Id: grades.pm,v 1.596.2.12.2.60.2.3 2023/03/10 23:36:22 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.4(ra 2560:ul-23):     my ($string,$timestamp,$lastgradetime,$lastsubmittime) = &get_last_submission(\%record,$is_tool);
          1(raebur 2561:0): 
                   2562:0):     my $lastsubonly;
                   2563:0): 
          0.2.2(ra 2564:ar-23):     if ($timestamp eq '') {
                   2565:ar-23):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>'; 
          1(raebur 2566:0):     } else {
          0.2.2(ra 2567:ar-23):         my ($shownsubmdate,$showngradedate);
                   2568:ar-23):         if ($lastsubmittime && $lastgradetime) {
                   2569:ar-23):             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   2570:ar-23):             if ($lastgradetime > $lastsubmittime) {
                   2571:ar-23):                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   2572:ar-23):              }
                   2573:ar-23):         } else {
                   2574:ar-23):             $shownsubmdate = $timestamp;
                   2575:ar-23):         }
          1(raebur 2576:0):         $lastsubonly =
                   2577:0):             '<div class="LC_grade_submissions_body">'
          0.2.2(ra 2578:ar-23):            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   2579:ar-23):         if ($showngradedate) {
                   2580:ar-23):             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   2581:ar-23):         }
          1(raebur 2582:0): 
                   2583:0): 	my %seenparts;
                   2584:0): 	my @part_response_id = &flatten_responseType($responseType);
                   2585:0): 	foreach my $part (@part_response_id) {
                   2586:0): 	    my ($partid,$respid) = @{ $part };
                   2587:0): 	    my $display_part=&get_display_part($partid,$symb);
                   2588:0): 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2589:0): 		if (exists($seenparts{$partid})) { next; }
                   2590:0): 		$seenparts{$partid}=1;
                   2591:0):                 $request->print(
                   2592:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2593:0):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2594:0):                                '<a href="javascript:viewSubmitter(\''.
                   2595:0):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2596:0):                                '\');" target="_self">'.
                   2597:0):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2598:0):                     '<br />');
                   2599:0): 		next;
                   2600:0): 	    }
                   2601:0): 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2602:0): 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2603:0):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2604:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2605:0):                     ' <span class="LC_internal_info">'.
                   2606:0):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2607:0):                     '</span>&nbsp; &nbsp;'.
                   2608:0): 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2609:0): 		next;
                   2610:0): 	    }
                   2611:0): 	    foreach my $submission (@$string) {
                   2612:0): 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2613:0): 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2614:0): 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2615:0): 		# Similarity check
                   2616:0):                 my $similar='';
                   2617:0):                 my ($type,$trial,$rndseed);
                   2618:0):                 if ($hide eq 'rand') {
                   2619:0):                     $type = 'randomizetry';
                   2620:0):                     $trial = $record{"resource.$partid.tries"};
                   2621:0):                     $rndseed = $record{"resource.$partid.rndseed"};
                   2622:0):                 }
                   2623:0): 		if ($env{'form.checkPlag'}) {
                   2624:0): 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2625:0): 		        &most_similar($uname,$udom,$symb,$subval);
                   2626:0): 		    if ($osim) {
                   2627:0): 		        $osim=int($osim*100.0);
                   2628:0):                         if ($hide eq 'anon') {
                   2629:0):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2630:0):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2631:0):                         } else {
                   2632:0): 			    $similar='<hr />';
                   2633:0):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2634:0):                                 $similar .= '<h3><span class="LC_warning">'.
                   2635:0):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2636:0):                                                 $osim,
                   2637:0):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2638:0):                                             '</span></h3>';
                   2639:0):                             } elsif ($ocrsid ne '') {
                   2640:0):                                 my %old_course_desc;
                   2641:0):                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2642:0):                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
          5(raebur 2643:9):                                 } else {
          1(raebur 2644:0):                                     my $args;
                   2645:0):                                     if ($ocrsid ne $env{'request.course.id'}) {
                   2646:0):                                         $args = {'one_time' => 1};
                   2647:0):                                     }
                   2648:0):                                     %old_course_desc =
                   2649:0):                                         &Apache::lonnet::coursedescription($ocrsid,$args);
                   2650:0):                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
          5(raebur 2651:9):                                 }
          1(raebur 2652:0):                                 $similar .=
                   2653:0):                                     '<h3><span class="LC_warning">'.
                   2654:0): 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2655:0): 				        $osim,
                   2656:0): 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2657:0): 				        $old_course_desc{'description'},
                   2658:0): 				        $old_course_desc{'num'},
                   2659:0): 				        $old_course_desc{'domain'}).
                   2660:0): 				    '</span></h3>';
1.596     raeburn  2661:                             } else {
1.596.2.12.2.  1(raebur 2662:0):                                 $similar .=
                   2663:0):                                     '<h3><span class="LC_warning">'.
                   2664:0):                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2665:0):                                         $osim,
                   2666:0):                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2667:0):                                     '</span></h3>';
1.596     raeburn  2668:                             }
1.596.2.12.2.  1(raebur 2669:0):                             $similar .= '<blockquote><i>'.
                   2670:0):                                         &keywords_highlight($oessay).
                   2671:0):                                         '</i></blockquote><hr />';
                   2672:0): 		        }
                   2673:0):                     }
                   2674:0):                 }
                   2675:0): 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2676:0):                                      undef,$type,$trial,$rndseed);
                   2677:0):                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2678:0):                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2679:0):                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
                   2680:0): 		    my $display_part=&get_display_part($partid,$symb);
                   2681:0):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2682:0):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2683:0):                         ' <span class="LC_internal_info">'.
                   2684:0):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2685:0):                         '</span>&nbsp; &nbsp;';
                   2686:0): 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2687:0): 		    if (@$files) {
1.596.2.2  raeburn  2688:                         if ($hide eq 'anon') {
1.596.2.12.2.  1(raebur 2689:0):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
1.596     raeburn  2690:                         } else {
1.596.2.12.2.  1(raebur 2691:0):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2692:0):                                          .'<br /><span class="LC_warning">';
                   2693:0):                             if(@$files == 1) {
                   2694:0):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2695:0):                             } else {
                   2696:0):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
          0(raebur 2697:4):                             }
          1(raebur 2698:0):                             $lastsubonly .= '</span>';
                   2699:0):                             foreach my $file (@$files) {
                   2700:0):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2701:0):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
          0(raebur 2702:4):                             }
1.596     raeburn  2703:                         }
1.596.2.12.2.  1(raebur 2704:0): 			$lastsubonly.='<br />';
1.41      ng       2705: 		    }
1.596.2.12.2.  1(raebur 2706:0):                     if ($hide eq 'anon') {
                   2707:0):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2708:0):                     } else {
                   2709:0):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2710:0):                         if ($draft) {
                   2711:0):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2712:0):                         }
                   2713:0):                         $subval =
                   2714:0): 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2715:0): 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2716:0):                         if ($responsetype eq 'essay') {
                   2717:0):                             $subval =~ s{\n}{<br />}g;
                   2718:0):                         }
                   2719:0):                         $lastsubonly.=$subval."\n";
                   2720:0):                     }
                   2721:0):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2722:0): 		    $lastsubonly.='</div>';
1.41      ng       2723: 		}
                   2724: 	    }
1.151     albertel 2725: 	}
1.596.2.12.2.  1(raebur 2726:0): 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2727:0):     }
                   2728:0):     $request->print($lastsubonly);
                   2729:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2730:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2731: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2732:3):     }
                   2733:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2734:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2735: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2736: 								 $env{'request.course.id'},
1.44      ng       2737: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2738:5): 								 'Apache::grades::keywords_highlight',
                   2739:5):                                                                  $usec,$identifier));
1.41      ng       2740:     }
1.121     ng       2741:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2742: 	.$udom.'" />'."\n");
1.44      ng       2743:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2744:0):     if (!&canmodify($usec)) {
                   2745:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2746:0):         return;
1.180     albertel 2747:     } else {
1.468     albertel 2748: 	$request->print('</div>'."\n");
1.41      ng       2749:     }
1.33      ng       2750: 
1.596.2.12.2.  1(raebur 2751:0):     # grading message center
                   2752:0): 
                   2753:0):     if ($env{'form.compmsg'}) {
                   2754:0):         my $result='<div class="LC_Box">'.
                   2755:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2756:0):                    '<div class="LC_grade_message_center_body">';
                   2757:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2758:0):         my $msgfor = $givenn.' '.$lastname;
                   2759:0):         if (scalar(@$col_fullnames) > 0) {
                   2760:0):             my $lastone = pop(@$col_fullnames);
                   2761:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2762:0):         }
                   2763:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2764:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2765:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2766:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2767:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2768:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2769:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2770:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2771:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2772:0):                  '<br />&nbsp;('.
                   2773:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2774:0): 	         '</div></div>';
                   2775:0):         $request->print($result);
1.118     ng       2776:     }
1.41      ng       2777: 
                   2778:     my %seen = ();
                   2779:     my @partlist;
1.129     ng       2780:     my @gradePartRespid;
1.596.2.12.2.  0.2.4(ra 2781:ul-23):     my @part_response_id;
                   2782:ul-23):     if ($is_tool) {
                   2783:ul-23):         @part_response_id = ([0,'']);
                   2784:ul-23):     } else {
                   2785:ul-23):         @part_response_id = &flatten_responseType($responseType);
                   2786:ul-23):     }
1.585     bisitz   2787:     $request->print(
1.588     bisitz   2788:         '<div class="LC_Box">'
                   2789:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2790:     );
1.592     bisitz   2791:     $request->print(&gradeBox_start());
1.375     albertel 2792:     foreach my $part_response_id (@part_response_id) {
                   2793:     	my ($partid,$respid) = @{ $part_response_id };
                   2794: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2795: 	next if ($seen{$partid} > 0);
1.41      ng       2796: 	$seen{$partid}++;
1.524     raeburn  2797: 	push(@partlist,$partid);
                   2798: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2799: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2800:     }
1.585     bisitz   2801:     $request->print(&gradeBox_end()); # </div>
                   2802:     $request->print('</div>');
1.468     albertel 2803: 
                   2804:     $request->print('<div class="LC_grade_info_links">');
                   2805:     $request->print('</div>');
                   2806: 
1.45      ng       2807:     $result='<input type="hidden" name="partlist'.$counter.
                   2808: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2809:     $result.='<input type="hidden" name="gradePartRespid'.
                   2810: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2811:     my $ctr = 0;
                   2812:     while ($ctr < scalar(@partlist)) {
                   2813: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2814: 	    $partlist[$ctr].'" />'."\n";
                   2815: 	$ctr++;
                   2816:     }
1.468     albertel 2817:     $request->print($result.''."\n");
1.41      ng       2818: 
1.441     www      2819: # Done with printing info for one student
                   2820: 
1.468     albertel 2821:     $request->print('</div>');#LC_grade_show_user
1.441     www      2822: 
                   2823: 
1.41      ng       2824:     # print end of form
                   2825:     if ($counter == $total) {
1.592     bisitz   2826:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2827: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2828: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2829: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2830: 	my $ntstu ='<select name="NTSTU">'.
                   2831: 	    '<option>1</option><option>2</option>'.
                   2832: 	    '<option>3</option><option>5</option>'.
                   2833: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2834: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2835: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2836:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2837: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2838: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2839: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2840: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2841:         $endform.='<span class="LC_warning">'.
                   2842:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2843:                   '</span>'."\n" ;
1.349     albertel 2844:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2845:             "' name='increment' />";
1.485     albertel 2846: 	$endform.='</td></tr></table></form>';
1.41      ng       2847: 	$request->print($endform);
                   2848:     }
                   2849:     return '';
1.38      ng       2850: }
                   2851: 
1.464     albertel 2852: sub check_collaborators {
                   2853:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2854:     my ($result,@col_fullnames);
                   2855:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2856:     foreach my $part (keys(%$handgrade)) {
                   2857: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2858: 					'.maxcollaborators',
                   2859: 					$symb,$udom,$uname);
                   2860: 	next if ($ncol <= 0);
                   2861: 	$part =~ s/\_/\./g;
                   2862: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2863: 	my (@good_collaborators, @bad_collaborators);
                   2864: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2865: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2866: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2867: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2868: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2869: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2870: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2871: 	    # Doing this grep allows 'fuzzy' specification
                   2872: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2873: 			       keys(%$classlist));
                   2874: 	    if (! scalar(@matches)) {
                   2875: 		push(@bad_collaborators, $possible_collaborator);
                   2876: 	    } else {
                   2877: 		push(@good_collaborators, @matches);
                   2878: 	    }
                   2879: 	}
                   2880: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2881: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2882: 	    foreach my $name (@good_collaborators) {
                   2883: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2884: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2885: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2886: 	    }
1.596.2.4  raeburn  2887: 	    $result.='</ol><br />'."\n";
1.466     albertel 2888: 	    my ($part)=split(/\./,$part);
1.464     albertel 2889: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2890: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2891: 		"\n";
                   2892: 	}
                   2893: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2894: 	    $result.='<div class="LC_warning">';
1.464     albertel 2895: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2896: 	    $result .= '</div>';
                   2897: 	}         
                   2898: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2899: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2900: 	    $result .= &mt('This student has submitted too many '.
                   2901: 		'collaborators.  Maximum is [_1].',$ncol);
                   2902: 	    $result .= '</div>';
                   2903: 	}
                   2904:     }
                   2905:     return ($result,$fullname,\@col_fullnames);
                   2906: }
                   2907: 
1.44      ng       2908: #--- Retrieve the last submission for all the parts
1.38      ng       2909: sub get_last_submission {
1.596.2.12.2.  0.2.4(ra 2910:ul-23):     my ($returnhash,$is_tool)=@_;
          0.2.2(ra 2911:ar-23):     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       2912:     if ($$returnhash{'version'}) {
1.46      ng       2913: 	my %lasthash=();
1.596.2.12.2.  0.2.2(ra 2914:ar-23):         my %prevsolved=();
                   2915:ar-23):         my %solved=();
                   2916:ar-23): 	my $version;
1.119     ng       2917: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.596.2.12.2.  0.2.2(ra 2918:ar-23):             my %handgraded = ();
1.397     albertel 2919: 	    foreach my $key (sort(split(/\:/,
                   2920: 					$$returnhash{$version.':keys'}))) {
                   2921: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.596.2.12.2.  0.2.2(ra 2922:ar-23):                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   2923:ar-23):                     $handgraded{$1} = 1;
                   2924:ar-23):                 } elsif ($key =~ /\.portfiles$/) {
                   2925:ar-23):                     if (($$returnhash{$version.':'.$key} ne '') &&
                   2926:ar-23):                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   2927:ar-23):                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2928:ar-23):                     }
                   2929:ar-23):                 } elsif ($key =~ /\.submission$/) {
                   2930:ar-23):                     if ($$returnhash{$version.':'.$key} ne '') {
                   2931:ar-23):                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2932:ar-23):                     }
                   2933:ar-23):                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   2934:ar-23):                     $prevsolved{$1} = $solved{$1};
                   2935:ar-23):                     $solved{$1} = $lasthash{$key};
                   2936:ar-23):                 }
          0.2.3(ra 2937:ar-23):             }
          0.2.2(ra 2938:ar-23):             foreach my $partid (keys(%handgraded)) {
                   2939:ar-23):                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   2940:ar-23):                     (($solved{$partid} eq 'incorrect_by_override') ||
                   2941:ar-23):                      ($solved{$partid} eq 'correct_by_override'))) {
                   2942:ar-23):                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   2943:ar-23):                 }
                   2944:ar-23):                 if ($solved{$partid} ne '') {
                   2945:ar-23):                     $prevsolved{$partid} = $solved{$partid};
                   2946:ar-23):                 }
                   2947:ar-23):             }
                   2948:ar-23): 	    $timestamp = 
                   2949:ar-23): 		&Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2950: 	}
1.596.2.2  raeburn  2951:         my (%typeparts,%randombytry);
1.596     raeburn  2952:         my $showsurv = 
                   2953:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2954:         foreach my $key (sort(keys(%lasthash))) {
                   2955:             if ($key =~ /\.type$/) {
                   2956:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2957:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2958:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2959:                     my ($ign,@parts) = split(/\./,$key);
                   2960:                     pop(@parts);
1.596.2.3  raeburn  2961:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2962:                     if ($lasthash{$key} eq 'randomizetry') {
                   2963:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2964:                     } else {
                   2965:                         unless ($showsurv) {
                   2966:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2967:                         }
1.596     raeburn  2968:                     }
                   2969:                     delete($lasthash{$key});
                   2970:                 }
                   2971:             }
                   2972:         }
                   2973:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2974:         my @randomize = keys(%randombytry);
1.397     albertel 2975: 	foreach my $key (keys(%lasthash)) {
                   2976: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2977:             my $hide;
                   2978:             if (@hidden) {
                   2979:                 foreach my $id (@hidden) {
                   2980:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2981:                         $hide = 'anon';
1.596     raeburn  2982:                         last;
                   2983:                     }
                   2984:                 }
                   2985:             }
1.596.2.2  raeburn  2986:             unless ($hide) {
                   2987:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2988:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2989:                         if ($key =~ /^\Q$id\E/) {
                   2990:                             $hide = 'rand';
                   2991:                             last;
                   2992:                         }
                   2993:                     }
                   2994:                 }
                   2995:             }
1.397     albertel 2996: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 2997:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 2998:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2999:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   3000:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       3001: 	}
                   3002:     }
1.397     albertel 3003:     if (!@string) {
1.596.2.12.2.  0.2.4(ra 3004:ul-23):         my $msg;
                   3005:ul-23):         if ($is_tool) {
                   3006:ul-23):             $msg = &mt('No grade passed back.');
                   3007:ul-23):         } else {
                   3008:ul-23):             $msg = &mt('Nothing submitted - no attempts.');
                   3009:ul-23):         }
1.397     albertel 3010: 	$string[0] =
1.596.2.12.2.  0.2.4(ra 3011:ul-23): 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 3012:     }
1.596.2.12.2.  0.2.2(ra 3013:ar-23):     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       3014: }
1.35      ng       3015: 
1.44      ng       3016: #--- High light keywords, with style choosen by user.
1.38      ng       3017: sub keywords_highlight {
1.44      ng       3018:     my $string    = shift;
1.257     albertel 3019:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   3020:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       3021:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 3022:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 3023:     foreach my $keyword (@keylist) {
                   3024: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       3025:     }
                   3026:     return $string;
1.38      ng       3027: }
1.36      ng       3028: 
1.596.2.12.2.  (raeburn 3029:): # For Tasks provide a mechanism to display previous version for one specific student
                   3030:): 
                   3031:): sub show_previous_task_version {
                   3032:):     my ($request,$symb) = @_;
                   3033:):     if ($symb eq '') {
          8(raebur 3034:4):         $request->print(
                   3035:4):             '<span class="LC_error">'.
                   3036:4):             &mt('Unable to handle ambiguous references.').
                   3037:4):             '</span>');
          (raeburn 3038:):         return '';
                   3039:):     }
                   3040:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   3041:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   3042:):     if (!&canview($usec)) {
          8(raebur 3043:4):         $request->print('<span class="LC_warning">'.
                   3044:4):                         &mt('Unable to view previous version for requested student.').
                   3045:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 3046:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 3047:4):                         '</span>');
          (raeburn 3048:):         return;
                   3049:):     }
                   3050:):     my $mode = 'both';
                   3051:):     my $isTask = ($symb =~/\.task$/);
                   3052:):     if ($isTask) {
                   3053:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3054:):             if ($env{'form.fullname'} eq '') {
                   3055:):                 $env{'form.fullname'} =
                   3056:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3057:):             }
                   3058:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3059:):             $request->print("\n\n".
                   3060:):                             '<div class="LC_grade_show_user">'.
                   3061:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3062:):                             '</h2>'."\n");
                   3063:):             &Apache::lonxml::clear_problem_counter();
                   3064:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3065:):                             {'previousversion' => $env{'form.previousversion'} }));
                   3066:):             $request->print("\n</div>");
                   3067:):         }
                   3068:):     }
                   3069:):     return;
                   3070:): }
                   3071:): 
                   3072:): sub choose_task_version_form {
                   3073:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   3074:):     my $isTask = ($symb =~/\.task$/);
                   3075:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3076:):     if ($isTask) {
                   3077:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3078:):                                               $udom,$uname);
                   3079:):         if (($record{'resource.0.version'} eq '') ||
                   3080:):             ($record{'resource.0.version'} < 2)) {
                   3081:):             return ($record{'resource.0.version'},
                   3082:):                     $record{'resource.0.version'},$result,$js);
                   3083:):         } else {
                   3084:):             $current = $record{'resource.0.version'};
                   3085:):         }
                   3086:):         if ($env{'form.previousversion'}) {
                   3087:):             $displayed = $env{'form.previousversion'};
                   3088:):             $rowtitle = &mt('Choose another version:')
                   3089:):         } else {
                   3090:):             $displayed = $current;
                   3091:):             $rowtitle = &mt('Show earlier version:');
                   3092:):         }
                   3093:):         $result = '<div class="LC_left_float">';
                   3094:):         my $list;
                   3095:):         my $numversions = 0;
                   3096:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3097:):             if ($i == $current) {
                   3098:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   3099:):                     next;
                   3100:):                 } else {
                   3101:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3102:):                     $numversions ++;
                   3103:):                 }
                   3104:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3105:):                 unless ($i == $env{'form.previousversion'}) {
                   3106:):                     $numversions ++;
                   3107:):                 }
                   3108:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3109:):             }
                   3110:):         }
                   3111:):         if ($numversions) {
                   3112:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3113:):             $result .=
                   3114:):                 '<form name="getprev" method="post" action=""'.
                   3115:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3116:):                 &Apache::loncommon::start_data_table().
                   3117:):                 &Apache::loncommon::start_data_table_row().
                   3118:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3119:):                 '<td><select name="version">'.
                   3120:):                 '<option>'.&mt('Select').'</option>'.
                   3121:):                 $list.
                   3122:):                 '</select></td>'.
                   3123:):                 &Apache::loncommon::end_data_table_row();
                   3124:):             unless ($nomenu) {
                   3125:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3126:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3127:):                 '<td><span class="LC_nobreak">'.
                   3128:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3129:):                 &mt('Yes').'</label>'.
                   3130:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3131:):                 '</span></td>'.
                   3132:):                 &Apache::loncommon::end_data_table_row();
                   3133:):             }
                   3134:):             $result .=
                   3135:):                 &Apache::loncommon::start_data_table_row().
                   3136:):                 '<th align="left">&nbsp;</th>'.
                   3137:):                 '<td>'.
                   3138:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3139:):                 '</td>'.
                   3140:):                 &Apache::loncommon::end_data_table_row().
                   3141:):                 &Apache::loncommon::end_data_table().
                   3142:):                 '</form>';
                   3143:):             $js = &previous_display_javascript($nomenu,$current);
                   3144:):         } elsif ($displayed && $nomenu) {
                   3145:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3146:):         } else {
                   3147:):             $result .= &mt('No previous versions to show for this student');
                   3148:):         }
                   3149:):         $result .= '</div>';
                   3150:):     }
                   3151:):     return ($current,$displayed,$result,$js);
                   3152:): }
                   3153:): 
                   3154:): sub previous_display_javascript {
                   3155:):     my ($nomenu,$current) = @_;
                   3156:):     my $js = <<"JSONE";
                   3157:): <script type="text/javascript">
                   3158:): // <![CDATA[
                   3159:): function previousVersion(uname,udom,symb) {
                   3160:):     var current = '$current';
                   3161:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3162:):     var prevstr = new RegExp("^\\\\d+\$");
                   3163:):     if (!prevstr.test(version)) {
                   3164:):         return false;
                   3165:):     }
                   3166:):     var url = '';
                   3167:):     if (version == current) {
                   3168:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3169:):     } else {
                   3170:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3171:):     }
                   3172:): JSONE
                   3173:):     if ($nomenu) {
                   3174:):         $js .= <<"JSTWO";
                   3175:):     document.location.href = url;
                   3176:): JSTWO
                   3177:):     } else {
                   3178:):         $js .= <<"JSTHREE";
                   3179:):     var newwin = 0;
                   3180:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3181:):         if (document.getprev.prevwin[i].checked == true) {
                   3182:):             newwin = document.getprev.prevwin[i].value;
                   3183:):         }
                   3184:):     }
                   3185:):     if (newwin == 1) {
                   3186:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3187:):         url = url+'&inhibitmenu=yes';
                   3188:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3189:):             previousWin = window.open(url,'',options,1);
                   3190:):         } else {
                   3191:):             previousWin.location.href = url;
                   3192:):         }
                   3193:):         previousWin.focus();
                   3194:):         return false;
                   3195:):     } else {
                   3196:):         document.location.href = url;
                   3197:):         return false;
                   3198:):     }
                   3199:): JSTHREE
                   3200:):     }
                   3201:):     $js .= <<"ENDJS";
                   3202:):     return false;
                   3203:): }
                   3204:): // ]]>
                   3205:): </script>
                   3206:): ENDJS
                   3207:): 
                   3208:): }
                   3209:): 
1.44      ng       3210: #--- Called from submission routine
1.38      ng       3211: sub processHandGrade {
1.596.2.12.2.  1(raebur 3212:0):     my ($request,$symb) = @_;
1.324     albertel 3213:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3214:     my $button = $env{'form.gradeOpt'};
                   3215:     my $ngrade = $env{'form.NCT'};
                   3216:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3217:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3218:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  8(raebur 3219:1):     my ($res_error,%queueable);
                   3220:1):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3221:1):     if ($res_error) {
                   3222:1):         $request->print(&navmap_errormsg());
                   3223:1):         return;
                   3224:1):     } else {
                   3225:1):         foreach my $part (@{$partlist}) {
                   3226:1):             if (ref($responseType->{$part}) eq 'HASH') {
                   3227:1):                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3228:1):                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3229:1):                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3230:1):                         $queueable{$part} = 1;
                   3231:1):                         last;
                   3232:1):                     }
                   3233:1):                 }
                   3234:1):             }
                   3235:1):         }
                   3236:1):     }
1.301     albertel 3237: 
1.44      ng       3238:     if ($button eq 'Save & Next') {
                   3239: 	my $ctr = 0;
                   3240: 	while ($ctr < $ngrade) {
1.257     albertel 3241: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3242:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
          8(raebur 3243:1):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3244: 	    if ($errorflag eq 'no_score') {
                   3245: 		$ctr++;
                   3246: 		next;
                   3247: 	    }
1.104     albertel 3248: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3249:4):                 $request->print(
                   3250:4):                     '<span class="LC_error">'
                   3251:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3252:4):                    .'</span>');
1.104     albertel 3253: 		$ctr++;
                   3254: 		next;
                   3255: 	    }
1.596.2.12.2.  1(raebur 3256:5):             if ($numhidden) {
                   3257:5):                 $request->print(
                   3258:5):                     '<span class="LC_info">'
                   3259:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3260:5):                    .'</span><br />');
                   3261:5):             }
1.257     albertel 3262: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3263: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3264: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3265:             my ($feedurl,$showsymb) =
                   3266: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3267: 	    my $messagetail;
1.62      albertel 3268: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3269: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3270: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3271: 		$subject.=' ['.$restitle.']';
1.44      ng       3272: 		my (@msgnum) = split(/,/,$includemsg);
                   3273: 		foreach (@msgnum) {
1.257     albertel 3274: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3275: 		}
1.80      ng       3276: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3277: 		if ($env{'form.withgrades'.$ctr}) {
                   3278: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3279: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3280:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3281: 		}
                   3282: 		$msgstatus = 
                   3283:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3284: 						     $message.$messagetail,
1.418     albertel 3285:                                                      undef,$feedurl,undef,
1.386     raeburn  3286:                                                      undef,undef,$showsymb,
                   3287:                                                      $restitle);
1.574     bisitz   3288: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3289: 				$msgstatus.'<br />');
1.44      ng       3290: 	    }
1.257     albertel 3291: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3292: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3293: 		foreach my $collabstr (@collabstrs) {
                   3294: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3295: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3296: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3297: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.596.2.12.2.  8(raebur 3298:1): 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3299: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3300: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3301: 			    next;
1.418     albertel 3302: 			} elsif ($message ne '') {
                   3303: 			    my ($baseurl,$showsymb) = 
                   3304: 				&get_feedurl_and_symb($symb,$collaborator,
                   3305: 						      $udom);
                   3306: 			    if ($env{'form.withgrades'.$ctr}) {
                   3307: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3308:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3309: 			    }
1.418     albertel 3310: 			    $msgstatus = 
                   3311: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3312: 			}
1.44      ng       3313: 		    }
                   3314: 		}
                   3315: 	    }
                   3316: 	    $ctr++;
                   3317: 	}
                   3318:     }
                   3319: 
1.596.2.12.2.  1(raebur 3320:0):     my %keyhash = ();
                   3321:0):     if ($numessay) {
1.119     ng       3322: 	# Keywords sorted in alphabatical order
1.257     albertel 3323: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3324: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3325:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3326: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3327: 	$env{'form.keywords'} = join(' ',@keywords);
                   3328: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3329: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3330: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3331: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3332: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3333:0):     }
1.119     ng       3334: 
1.596.2.12.2.  1(raebur 3335:0):     if ($env{'form.compmsg'}) {
1.119     ng       3336: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3337: 	# New messages are saved in env for the next student.
1.119     ng       3338: 	# All messages are saved in nohist_handgrade.db
                   3339: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3340: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3341: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3342: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3343: 		$idx++;
                   3344: 	    }
                   3345: 	    $ctr++;
1.41      ng       3346: 	}
1.119     ng       3347: 	$ctr = 0;
                   3348: 	while ($ctr < $ngrade) {
1.257     albertel 3349: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3350: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3351: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3352: 		$idx++;
                   3353: 	    }
                   3354: 	    $ctr++;
1.41      ng       3355: 	}
1.257     albertel 3356: 	$env{'form.savemsgN'} = --$idx;
                   3357: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3358:0):     }
                   3359:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3360: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3361: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3362:     }
1.596.2.12.2.  1(raebur 3363:0): 
1.44      ng       3364:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3365:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3366:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3367: 	my ($ctr,$total) = (0,0);
                   3368: 	while ($ctr < $ngrade) {
1.257     albertel 3369: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3370: 	    $ctr++;
                   3371: 	}
1.257     albertel 3372: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3373: 	$ctr = 0;
                   3374: 	while ($ctr < $total) {
1.257     albertel 3375: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3376: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3377: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3378:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3379: 	    $ctr++;
                   3380: 	}
                   3381: 	return '';
                   3382:     }
1.36      ng       3383: 
1.44      ng       3384:     # Get the next/previous one or group of students
1.257     albertel 3385:     my $firststu = $env{'form.unamedom0'};
                   3386:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3387:     my $ctr = 2;
1.41      ng       3388:     while ($laststu eq '') {
1.257     albertel 3389: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3390: 	$ctr++;
                   3391: 	$laststu = $firststu if ($ctr > $ngrade);
                   3392:     }
1.44      ng       3393: 
1.41      ng       3394:     my (@parsedlist,@nextlist);
                   3395:     my ($nextflg) = 0;
1.524     raeburn  3396:     foreach my $item (sort 
1.294     albertel 3397: 	     {
                   3398: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3399: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3400: 		 }
                   3401: 		 return $a cmp $b;
                   3402: 	     } (keys(%$fullname))) {
1.41      ng       3403: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3404: 	    push(@parsedlist,$item);
1.41      ng       3405: 	}
1.524     raeburn  3406: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3407: 	if ($button eq 'Previous') {
1.524     raeburn  3408: 	    last if ($item eq $firststu);
                   3409: 	    push(@parsedlist,$item);
1.41      ng       3410: 	}
                   3411:     }
                   3412:     $ctr = 0;
                   3413:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3414:     foreach my $student (@parsedlist) {
1.257     albertel 3415: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3416: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3417: 	
                   3418: 	if ($submitonly eq 'queued') {
                   3419: 	    my %queue_status = 
                   3420: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3421: 							$udom,$uname);
                   3422: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3423: 	}
                   3424: 
1.156     albertel 3425: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3426: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3427: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3428: 	    my $submitted = 0;
1.248     albertel 3429: 	    my $ungraded = 0;
                   3430: 	    my $incorrect = 0;
1.524     raeburn  3431: 	    foreach my $item (keys(%status)) {
                   3432: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3433: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3434: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3435: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3436: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3437: 		    $submitted = 0;
                   3438: 		}
1.41      ng       3439: 	    }
1.156     albertel 3440: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3441: 				     $submitonly eq 'incorrect' ||
                   3442: 				     $submitonly eq 'graded'));
1.248     albertel 3443: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3444: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3445: 	}
1.524     raeburn  3446: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3447: 	last if ($ctr == $ntstu);
1.41      ng       3448: 	$ctr++;
                   3449:     }
1.36      ng       3450: 
1.41      ng       3451:     $ctr = 0;
                   3452:     my $total = scalar(@nextlist)-1;
1.39      ng       3453: 
1.524     raeburn  3454:     foreach (sort(@nextlist)) {
1.41      ng       3455: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3456: 	$env{'form.student'}  = $uname;
                   3457: 	$env{'form.userdom'}  = $udom;
                   3458: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3459:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3460: 	$ctr++;
                   3461:     }
                   3462:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3463:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3464: 	$request->print($the_end);
                   3465:     }
                   3466:     return '';
1.38      ng       3467: }
1.36      ng       3468: 
1.44      ng       3469: #---- Save the score and award for each student, if changed
1.38      ng       3470: sub saveHandGrade {
1.596.2.12.2.  8(raebur 3471:1):     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3472:     my @version_parts;
1.104     albertel 3473:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3474: 					   $env{'request.course.id'});
1.104     albertel 3475:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3476:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3477:     my @parts_graded;
1.77      ng       3478:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3479:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3480:     my %aggregate = ();
                   3481:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3482:5):     if ($env{'form.HIDE'.$newflg}) {
                   3483:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3484:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3485:5):         $totchg += $numchgs;
                   3486:5):     }
1.301     albertel 3487:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3488:     foreach my $new_part (@parts) {
1.337     banghart 3489: 	#collaborator ($submi may vary for different parts
1.259     banghart 3490: 	if ($submitter && $new_part ne $part) { next; }
                   3491: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3492: 	if ($dropMenu eq 'excused') {
1.259     banghart 3493: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3494: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3495: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3496: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3497: 		}
1.364     banghart 3498: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3499: 	    }
1.125     ng       3500: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3501: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3502: 	    foreach my $key (keys(%record)) {
1.259     banghart 3503: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3504: 	    }
1.259     banghart 3505: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3506: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3507:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3508: 
                   3509:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3510: 					       [$new_part]);
                   3511:             my $aggtries =$totaltries;
1.269     raeburn  3512:             if ($last_resets{$new_part}) {
1.270     albertel 3513:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3514: 					   $new_part);
1.269     raeburn  3515:             }
1.270     albertel 3516: 
                   3517:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3518:             if ($aggtries > 0) {
1.327     albertel 3519:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3520:                 $aggregateflag = 1;
                   3521:             }
1.125     ng       3522: 	} elsif ($dropMenu eq '') {
1.259     banghart 3523: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3524: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3525: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3526: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3527: 		next;
                   3528: 	    }
1.259     banghart 3529: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3530: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3531: 	    my $partial= $pts/$wgt;
1.259     banghart 3532: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3533: 		#do not update score for part if not changed.
1.346     banghart 3534:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3535: 		next;
1.251     banghart 3536: 	    } else {
1.524     raeburn  3537: 	        push(@parts_graded,$new_part);
1.153     albertel 3538: 	    }
1.259     banghart 3539: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3540: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3541: 	    }
1.259     banghart 3542: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3543: 	    if ($partial == 0) {
1.153     albertel 3544: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3545: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3546: 		}
1.41      ng       3547: 	    } else {
1.153     albertel 3548: 		if ($record{$reckey} ne 'correct_by_override') {
                   3549: 		    $newrecord{$reckey} = 'correct_by_override';
                   3550: 		}
                   3551: 	    }	    
                   3552: 	    if ($submitter && 
1.259     banghart 3553: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3554: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3555: 	    }
1.259     banghart 3556: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3557: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3558: 	}
1.259     banghart 3559: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3560: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3561: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3562: 	        $dropMenu eq 'reset status')
                   3563: 	   {
1.524     raeburn  3564: 	    push(@version_parts,$new_part);
1.259     banghart 3565: 	}
1.41      ng       3566:     }
1.301     albertel 3567:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3568:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3569: 
1.344     albertel 3570:     if (%newrecord) {
                   3571:         if (@version_parts) {
1.364     banghart 3572:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3573:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3574: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3575: 	    foreach my $new_part (@version_parts) {
                   3576: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3577: 				$new_part,\%newrecord);
                   3578: 	    }
1.259     banghart 3579:         }
1.44      ng       3580: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3581: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3582: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.596.2.12.2.  8(raebur 3583:1): 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3584:     }
1.269     raeburn  3585:     if ($aggregateflag) {
                   3586:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3587: 			      $cdom,$cnum);
1.269     raeburn  3588:     }
1.596.2.12.2.  1(raebur 3589:5):     return ('',$pts,$wgt,$totchg);
                   3590:5): }
                   3591:5): 
                   3592:5): sub makehidden {
                   3593:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3594:5):     return unless (ref($record) eq 'HASH');
                   3595:5):     my %modified;
                   3596:5):     my $numchanged = 0;
                   3597:5):     if (exists($record->{$version.':keys'})) {
                   3598:5):         my $partsregexp = $parts;
                   3599:5):         $partsregexp =~ s/,/|/g;
                   3600:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3601:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3602:5):                  my $item = $1;
                   3603:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3604:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3605:5):                  }
                   3606:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3607:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3608:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3609:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3610:5):             }
                   3611:5):         }
                   3612:5):         if (keys(%modified)) {
                   3613:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3614:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3615:5):                 $numchanged ++;
                   3616:5):             }
                   3617:5):         }
                   3618:5):     }
                   3619:5):     return $numchanged;
1.36      ng       3620: }
1.322     albertel 3621: 
1.380     albertel 3622: sub check_and_remove_from_queue {
1.596.2.12.2.  8(raebur 3623:1):     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3624:     my @ungraded_parts;
                   3625:     foreach my $part (@{$parts}) {
                   3626: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3627: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3628: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3629: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3630: 		) {
1.596.2.12.2.  8(raebur 3631:1):             if ($queueable->{$part}) {
                   3632:1): 	        push(@ungraded_parts, $part);
                   3633:1):             }
1.380     albertel 3634: 	}
                   3635:     }
                   3636:     if ( !@ungraded_parts ) {
                   3637: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3638: 					       $cnum,$domain,$stuname);
                   3639:     }
                   3640: }
                   3641: 
1.337     banghart 3642: sub handback_files {
                   3643:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3644:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3645:     my $res_error;
                   3646:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3647:     if ($res_error) {
                   3648:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3649:         return;
                   3650:     }
1.596.2.4  raeburn  3651:     my @handedback;
                   3652:     my $file_msg;
1.375     albertel 3653:     my @part_response_id = &flatten_responseType($responseType);
                   3654:     foreach my $part_response_id (@part_response_id) {
                   3655:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3656: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3657:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3658:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3659:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3660: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3661:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3662:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3663:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3664:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3665: 		        &file_name_version_ext($answer_file);
1.355     banghart 3666: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3667:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3668:):                     my ($dir_list,$listerror) =
                   3669:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3670:):                                                  $domain,$stuname,$getpropath);
                   3671:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3672:3):                     # fix filename
1.355     banghart 3673:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3674:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3675:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3676:             	                                $save_file_name);
1.337     banghart 3677:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3678:                         $request->print('<br /><span class="LC_error">'.
                   3679:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3680:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3681:                                         '</span>');
1.356     banghart 3682:                     } else {
1.360     banghart 3683:                         # mark the file as read only
1.596.2.4  raeburn  3684:                         push(@handedback,$save_file_name);
1.367     albertel 3685: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3686: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3687: 			}
                   3688:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3689: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3690: 
1.337     banghart 3691:                     }
1.596.2.12.2.  3(raebur 3692: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 3693:                 }
                   3694:             }
                   3695:         }
1.596.2.4  raeburn  3696:     }
                   3697:     if (@handedback > 0) {
                   3698:         $request->print('<br />');
                   3699:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3700:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3701:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3702:         my ($subject,$message);
                   3703:         if (scalar(@handedback) == 1) {
                   3704:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3705:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3706:         } else {
                   3707:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3708:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3709:         }
                   3710:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3711:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3712:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3713:         my ($feedurl,$showsymb) =
                   3714:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3715:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3716:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3717:         my $msgstatus =
                   3718:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3719:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3720:                  $restitle);
                   3721:         if ($msgstatus) {
                   3722:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3723:         }
                   3724:     }
1.338     banghart 3725:     return;
1.337     banghart 3726: }
                   3727: 
1.418     albertel 3728: sub get_feedurl_and_symb {
                   3729:     my ($symb,$uname,$udom) = @_;
                   3730:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3731:     $url = &Apache::lonnet::clutter($url);
                   3732:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3733: 					$symb,$udom,$uname);
                   3734:     if ($encrypturl =~ /^yes$/i) {
                   3735: 	&Apache::lonenc::encrypted(\$url,1);
                   3736: 	&Apache::lonenc::encrypted(\$symb,1);
                   3737:     }
                   3738:     return ($url,$symb);
                   3739: }
                   3740: 
1.313     banghart 3741: sub get_submitted_files {
                   3742:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3743:     my @files;
                   3744:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3745:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3746:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3747:     	    push(@files,$file_url.$file);
                   3748:         }
                   3749:     }
                   3750:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3751:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3752:     }
                   3753:     return (\@files);
                   3754: }
1.322     albertel 3755: 
1.269     raeburn  3756: # ----------- Provides number of tries since last reset.
                   3757: sub get_num_tries {
                   3758:     my ($record,$last_reset,$part) = @_;
                   3759:     my $timestamp = '';
                   3760:     my $num_tries = 0;
                   3761:     if ($$record{'version'}) {
                   3762:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3763:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3764:                 $timestamp = $$record{$version.':timestamp'};
                   3765:                 if ($timestamp > $last_reset) {
                   3766:                     $num_tries ++;
                   3767:                 } else {
                   3768:                     last;
                   3769:                 }
                   3770:             }
                   3771:         }
                   3772:     }
                   3773:     return $num_tries;
                   3774: }
                   3775: 
                   3776: # ----------- Determine decrements required in aggregate totals 
                   3777: sub decrement_aggs {
                   3778:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3779:     my %decrement = (
                   3780:                         attempts => 0,
                   3781:                         users => 0,
                   3782:                         correct => 0
                   3783:                     );
                   3784:     $decrement{'attempts'} = $aggtries;
                   3785:     if ($solvedstatus =~ /^correct/) {
                   3786:         $decrement{'correct'} = 1;
                   3787:     }
                   3788:     if ($aggtries == $totaltries) {
                   3789:         $decrement{'users'} = 1;
                   3790:     }
1.524     raeburn  3791:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3792:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3793:     }
                   3794:     return;
                   3795: }
                   3796: 
                   3797: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3798: sub get_last_resets {
1.270     albertel 3799:     my ($symb,$courseid,$partids) =@_;
                   3800:     my %last_resets;
1.269     raeburn  3801:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3802:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3803:     my @keys;
                   3804:     foreach my $part (@{$partids}) {
                   3805: 	push(@keys,"$symb\0$part\0resettime");
                   3806:     }
                   3807:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3808: 				     $cdom,$cname);
                   3809:     foreach my $part (@{$partids}) {
                   3810: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3811:     }
1.270     albertel 3812:     return %last_resets;
1.269     raeburn  3813: }
                   3814: 
1.251     banghart 3815: # ----------- Handles creating versions for portfolio files as answers
                   3816: sub version_portfiles {
1.343     banghart 3817:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3818:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3819:     my @returned_keys;
1.255     banghart 3820:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3821:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3822:     foreach my $key (keys(%$record)) {
1.259     banghart 3823:         my $new_portfiles;
1.263     banghart 3824:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3825:             my @versioned_portfiles;
1.367     albertel 3826:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3827:             foreach my $file (@portfiles) {
1.306     banghart 3828:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3829:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3830: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3831: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3832:):                 my $getpropath = 1;
                   3833:):                 my ($dir_list,$listerror) =
                   3834:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3835:):                                              $stu_name,$getpropath);
                   3836:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3837:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3838:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3839:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3840:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3841:                         [$directory.$new_answer],
1.306     banghart 3842:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3843:                 }
1.252     banghart 3844:             }
1.343     banghart 3845:             $$record{$key} = join(',',@versioned_portfiles);
                   3846:             push(@returned_keys,$key);
1.251     banghart 3847:         }
                   3848:     } 
1.343     banghart 3849:     return (@returned_keys);   
1.305     banghart 3850: }
                   3851: 
1.307     banghart 3852: sub get_next_version {
1.341     banghart 3853:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3854:     my $version;
1.596.2.12.2.  (raeburn 3855:):     if (ref($dir_list) eq 'ARRAY') {
                   3856:):         foreach my $row (@{$dir_list}) {
                   3857:):             my ($file) = split(/\&/,$row,2);
                   3858:):             my ($file_name,$file_version,$file_ext) =
                   3859:): 	        &file_name_version_ext($file);
                   3860:):             if (($file_name eq $answer_name) && 
                   3861:): 	        ($file_ext eq $answer_ext)) {
                   3862:):                 # gets here if filename and extension match, 
                   3863:):                 # regardless of version
1.307     banghart 3864:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3865:):                     # a versioned file is found  so save it for later
                   3866:):                     if ($file_version > $version) {
                   3867:): 		        $version = $file_version;
                   3868:):                     }
1.307     banghart 3869: 	        }
                   3870:             }
                   3871:         }
1.596.2.12.2.  (raeburn 3872:):     }
1.307     banghart 3873:     $version ++;
                   3874:     return($version);
                   3875: }
                   3876: 
1.305     banghart 3877: sub version_selected_portfile {
1.306     banghart 3878:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3879:     my ($answer_name,$answer_ver,$answer_ext) =
                   3880:         &file_name_version_ext($file_name);
                   3881:     my $new_answer;
                   3882:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3883:     if($env{'form.copy'} eq '-1') {
                   3884:         $new_answer = 'problem getting file';
                   3885:     } else {
                   3886:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3887:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3888:                             $stu_name,$domain,'copy',
                   3889: 		        '/portfolio'.$directory.$new_answer);
                   3890:     }    
                   3891:     return ($new_answer);
1.251     banghart 3892: }
                   3893: 
1.304     albertel 3894: sub file_name_version_ext {
                   3895:     my ($file)=@_;
                   3896:     my @file_parts = split(/\./, $file);
                   3897:     my ($name,$version,$ext);
                   3898:     if (@file_parts > 1) {
                   3899: 	$ext=pop(@file_parts);
                   3900: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3901: 	    $version=pop(@file_parts);
                   3902: 	}
                   3903: 	$name=join('.',@file_parts);
                   3904:     } else {
                   3905: 	$name=join('.',@file_parts);
                   3906:     }
                   3907:     return($name,$version,$ext);
                   3908: }
                   3909: 
1.44      ng       3910: #--------------------------------------------------------------------------------------
                   3911: #
                   3912: #-------------------------- Next few routines handles grading by section or whole class
                   3913: #
                   3914: #--- Javascript to handle grading by section or whole class
1.42      ng       3915: sub viewgrades_js {
                   3916:     my ($request) = shift;
                   3917: 
1.539     riegler  3918:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3919:6):     &js_escape(\$alertmsg);
          1(raebur 3920:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3921:    function writePoint(partid,weight,point) {
1.125     ng       3922: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3923: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3924: 	if (point == "textval") {
1.125     ng       3925: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3926: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3927: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3928: 		var resetbox = false;
                   3929: 		for (var i=0; i<radioButton.length; i++) {
                   3930: 		    if (radioButton[i].checked) {
                   3931: 			textbox.value = i;
                   3932: 			resetbox = true;
                   3933: 		    }
                   3934: 		}
                   3935: 		if (!resetbox) {
                   3936: 		    textbox.value = "";
                   3937: 		}
                   3938: 		return;
                   3939: 	    }
1.109     matthew  3940: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3941: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3942: 				   ") greater than the weight for the part. Accept?");
                   3943: 		if (resp == false) {
                   3944: 		    textbox.value = "";
                   3945: 		    return;
                   3946: 		}
                   3947: 	    }
1.42      ng       3948: 	    for (var i=0; i<radioButton.length; i++) {
                   3949: 		radioButton[i].checked=false;
1.109     matthew  3950: 		if (parseFloat(point) == i) {
1.42      ng       3951: 		    radioButton[i].checked=true;
                   3952: 		}
                   3953: 	    }
1.41      ng       3954: 
1.42      ng       3955: 	} else {
1.125     ng       3956: 	    textbox.value = parseFloat(point);
1.42      ng       3957: 	}
1.41      ng       3958: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3959: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3960: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3961: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3962: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3963: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3964: 	    if (saveval != "correct") {
                   3965: 		scorename.value = point;
1.43      ng       3966: 		if (selname[0].selected != true) {
                   3967: 		    selname[0].selected = true;
                   3968: 		}
1.42      ng       3969: 	    }
                   3970: 	}
1.125     ng       3971: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3972:     }
                   3973: 
                   3974:     function writeRadText(partid,weight) {
1.125     ng       3975: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3976: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3977:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3978: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3979: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3980: 	    for (var i=0; i<radioButton.length; i++) {
                   3981: 		radioButton[i].checked=false;
                   3982: 
                   3983: 	    }
                   3984: 	    textbox.value = "";
                   3985: 
                   3986: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3987: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3988: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3989: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3990: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3991: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3992: 		if ((saveval != "correct") || override) {
1.42      ng       3993: 		    scorename.value = "";
1.125     ng       3994: 		    if (selval[1].selected) {
                   3995: 			selname[1].selected = true;
                   3996: 		    } else {
                   3997: 			selname[2].selected = true;
                   3998: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3999: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   4000: 		    }
1.42      ng       4001: 		}
                   4002: 	    }
1.43      ng       4003: 	} else {
                   4004: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4005: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4006: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4007: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4008: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4009: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      4010: 		if ((saveval != "correct") || override) {
1.125     ng       4011: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       4012: 		    selname[0].selected = true;
                   4013: 		}
                   4014: 	    }
                   4015: 	}	    
1.42      ng       4016:     }
                   4017: 
                   4018:     function changeSelect(partid,user) {
1.125     ng       4019: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4020: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       4021: 	var point  = textbox.value;
1.125     ng       4022: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       4023: 
1.109     matthew  4024: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  4025: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       4026: 	    textbox.value = "";
                   4027: 	    return;
                   4028: 	}
1.109     matthew  4029: 	if (parseFloat(point) > parseFloat(weight)) {
                   4030: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       4031: 			       ") greater than the weight of the part. Accept?");
                   4032: 	    if (resp == false) {
                   4033: 		textbox.value = "";
                   4034: 		return;
                   4035: 	    }
                   4036: 	}
1.42      ng       4037: 	selval[0].selected = true;
                   4038:     }
                   4039: 
                   4040:     function changeOneScore(partid,user) {
1.125     ng       4041: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   4042: 	if (selval[1].selected || selval[2].selected) {
                   4043: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   4044: 	    if (selval[2].selected) {
                   4045: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4046: 	    }
1.269     raeburn  4047:         }
1.42      ng       4048:     }
                   4049: 
                   4050:     function resetEntry(numpart) {
                   4051: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4052: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4053: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4054: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4055: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4056: 	    for (var i=0; i<radioButton.length; i++) {
                   4057: 		radioButton[i].checked=false;
                   4058: 
                   4059: 	    }
                   4060: 	    textbox.value = "";
                   4061: 	    selval[0].selected = true;
                   4062: 
                   4063: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4064: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4065: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4066: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4067: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4068: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4069: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4070: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4071: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4072: 		if (saveselval == "excused") {
1.43      ng       4073: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4074: 		} else {
1.43      ng       4075: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4076: 		}
                   4077: 	    }
1.41      ng       4078: 	}
1.42      ng       4079:     }
                   4080: 
1.41      ng       4081: VIEWJAVASCRIPT
1.42      ng       4082: }
                   4083: 
1.44      ng       4084: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4085: sub viewgrades {
1.596.2.12.2.  1(raebur 4086:0):     my ($request,$symb) = @_;
          0.2.4(ra 4087:ul-23):     my ($is_tool,$toolsymb);
                   4088:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4089:ul-23):         $is_tool = 1;
                   4090:ul-23):         $toolsymb = $symb;
                   4091:ul-23):     }
1.42      ng       4092:     &viewgrades_js($request);
1.41      ng       4093: 
1.168     albertel 4094:     #need to make sure we have the correct data for later EXT calls, 
                   4095:     #thus invalidate the cache
                   4096:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4097:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4098:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4099:     &Apache::lonnet::clear_EXT_cache_status();
                   4100: 
1.398     albertel 4101:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4102: 
                   4103:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4104:     $result.=&jscriptNform($symb);
1.41      ng       4105: 
1.44      ng       4106:     #beginning of class grading form
1.442     banghart 4107:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4108:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4109: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4110: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4111: 	&build_section_inputs().
1.442     banghart 4112: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4113: 
1.596.2.12.2.  7(raebur 4114:6):     #retrieve selected groups
                   4115:6):     my (@groups,$group_display);
          8(raebur 4116:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 4117:6):     if (grep(/^all$/,@groups)) {
                   4118:6):         @groups = ('all');
                   4119:6):     } elsif (grep(/^none$/,@groups)) {
                   4120:6):         @groups = ('none');
                   4121:6):     } elsif (@groups > 0) {
                   4122:6):         $group_display = join(', ',@groups);
                   4123:6):     }
                   4124:6): 
                   4125:6):     my ($common_header,$specific_header,@sections,$section_display);
          6(raebur 4126:1):     if ($env{'request.course.sec'} ne '') {
                   4127:1):         @sections = ($env{'request.course.sec'});
                   4128:1):     } else {
                   4129:1):         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4130:1):     }
                   4131:1): 
                   4132:1): # Check if Save button should be usable
                   4133:1):     my $disabled = ' disabled="disabled"';
                   4134:1):     if ($perm{'mgr'}) {
                   4135:1):         if (grep(/^all$/,@sections)) {
                   4136:1):             undef($disabled);
                   4137:1):         } else {
                   4138:1):             foreach my $sec (@sections) {
                   4139:1):                 if (&canmodify($sec)) {
                   4140:1):                     undef($disabled);
                   4141:1):                     last;
                   4142:1):                 }
                   4143:1):             }
                   4144:1):         }
                   4145:1):     }
          7(raebur 4146:6):     if (grep(/^all$/,@sections)) {
                   4147:6):         @sections = ('all');
                   4148:6):         if ($group_display) {
                   4149:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4150:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4151:6):         } elsif (grep(/^none$/,@groups)) {
                   4152:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4153:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4154:6):         } else {
                   4155:6):             $common_header = &mt('Assign Common Grade to Class');
                   4156:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4157:6):         }
                   4158:6):     } elsif (grep(/^none$/,@sections)) {
                   4159:6):         @sections = ('none');
                   4160:6):         if ($group_display) {
                   4161:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4162:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4163:6):         } elsif (grep(/^none$/,@groups)) {
                   4164:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4165:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4166:6):         } else {
                   4167:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4168:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4169:6):         }
                   4170:6):     } else {
                   4171:6):         $section_display = join (", ",@sections);
                   4172:6):         if ($group_display) {
                   4173:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4174:6):                                  $section_display,$group_display);
                   4175:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4176:6):                                    $section_display,$group_display);
                   4177:6):         } elsif (grep(/^none$/,@groups)) {
                   4178:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4179:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4180:6):         } else {
                   4181:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4182:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4183:6):         }
1.52      albertel 4184:     }
1.596.2.12.2.  7(raebur 4185:6):     my %submit_types = &substatus_options();
                   4186:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4187:6): 
                   4188:6):     if ($env{'form.submitonly'} eq 'all') {
                   4189:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4190:6):     } else {
          0.2.4(ra 4191:ul-23):         my $text;
                   4192:ul-23):         if ($is_tool) {
                   4193:ul-23):             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4194:ul-23):         } else {
                   4195:ul-23):             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4196:ul-23):         }
                   4197:ul-23):         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
          7(raebur 4198:6):     }
                   4199:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4200:     #radio buttons/text box for assigning points for a section or class.
                   4201:     #handles different parts of a problem
1.582     raeburn  4202:     my $res_error;
                   4203:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4204:     if ($res_error) {
                   4205:         return &navmap_errormsg();
                   4206:     }
1.42      ng       4207:     my %weight = ();
                   4208:     my $ctsparts = 0;
1.45      ng       4209:     my %seen = ();
1.596.2.12.2.  0.2.4(ra 4210:ul-23):     my @part_response_id;
                   4211:ul-23):     if ($is_tool) {
                   4212:ul-23):         @part_response_id = ([0,'']);
                   4213:ul-23):     } else {
                   4214:ul-23):         @part_response_id = &flatten_responseType($responseType);
                   4215:ul-23):     }
1.375     albertel 4216:     foreach my $part_response_id (@part_response_id) {
                   4217:     	my ($partid,$respid) = @{ $part_response_id };
                   4218: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4219: 	next if $seen{$partid};
                   4220: 	$seen{$partid}++;
1.42      ng       4221: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4222: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4223: 
1.324     albertel 4224: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4225: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4226: 	my $ctr = 0;
1.42      ng       4227: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4228: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4229: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4230: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4231: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4232: 	    $ctr++;
                   4233: 	}
1.485     albertel 4234: 	$radio.='</tr></table>';
                   4235: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4236: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4237: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4238: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4239:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4240:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4241:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4242: 		$weight{$partid}.')"> '.
1.401     albertel 4243: 	    '<option selected="selected"> </option>'.
1.485     albertel 4244: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4245: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4246: 	    '</select></td>'.
                   4247:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4248: 	$line.='<input type="hidden" name="partid_'.
                   4249: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4250: 	$line.='<input type="hidden" name="weight_'.
                   4251: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4252: 
                   4253: 	$result.=
                   4254: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4255: 	    '<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 4256: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4257: 	$ctsparts++;
1.41      ng       4258:     }
1.474     albertel 4259:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4260: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4261:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4262: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4263: 
1.44      ng       4264:     #table listing all the students in a section/class
                   4265:     #header of table
1.596.2.12.2.  0.2.4(ra 4266:ul-23):     if ($env{'form.submitonly'} eq 'all') {
          7(raebur 4267:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4268:6):     } else {
          0.2.4(ra 4269:ul-23):         my $text;
                   4270:ul-23):         if ($is_tool) {
                   4271:ul-23):             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4272:ul-23):         } else {
                   4273:ul-23):             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4274:ul-23):         }
                   4275:ul-23):         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
          7(raebur 4276:6):     }
                   4277:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4278: 	      &Apache::loncommon::start_data_table_header_row().
                   4279: 	      '<th>'.&mt('No.').'</th>'.
                   4280: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4281:     my $partserror;
                   4282:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4283:     if ($partserror) {
                   4284:         return &navmap_errormsg();
                   4285:     }
1.324     albertel 4286:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4287:     my @partids = ();
1.41      ng       4288:     foreach my $part (@parts) {
1.596.2.12.2.  0.2.4(ra 4289:ul-23): 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4290:         my $narrowtext = &mt('Tries');
                   4291: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.596.2.12.2.  0.2.4(ra 4292:ul-23): 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4293: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4294:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4295:0): #
                   4296:0): # FIXME: Looks like $display looks at English text
                   4297:0): #
1.324     albertel 4298: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4299: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4300: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4301:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4302:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4303: 	    next;
1.485     albertel 4304: 	    
1.207     albertel 4305: 	} else {
1.485     albertel 4306: 	    if ($display =~ /Problem Status/) {
                   4307: 		my $grade_status_mt = &mt('Grade Status');
                   4308: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4309: 	    }
                   4310: 	    my $part_mt = &mt('Part:');
                   4311: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4312: 	}
1.485     albertel 4313: 
1.474     albertel 4314: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4315:     }
1.474     albertel 4316:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4317: 
1.270     albertel 4318:     my %last_resets = 
                   4319: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4320: 
1.41      ng       4321:     #get info for each student
1.44      ng       4322:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4323:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4324:     my $ctr = 0;
1.294     albertel 4325:     foreach (sort 
                   4326: 	     {
                   4327: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4328: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4329: 		 }
                   4330: 		 return $a cmp $b;
                   4331: 	     } (keys(%$fullname))) {
1.324     albertel 4332: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  0.2.4(ra 4333:ul-23): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4334:     }
1.474     albertel 4335:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4336:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.596.2.12.2.  6(raebur 4337:1):     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4338: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4339:6):     if ($ctr == 0) {
1.442     banghart 4340:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4341:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4342:6):                 '<span class="LC_warning">';
                   4343:6):         if ($env{'form.submitonly'} eq 'all') {
                   4344:6):             if (grep(/^all$/,@sections)) {
                   4345:6):                 if (grep(/^all$/,@groups)) {
                   4346:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4347:6):                                    $stu_status);
                   4348:6):                 } elsif (grep(/^none$/,@groups)) {
                   4349:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4350:6):                                    $stu_status);
                   4351:6):                 } else {
                   4352:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4353:6):                                    $group_display,$stu_status);
                   4354:6):                 }
                   4355:6):             } elsif (grep(/^none$/,@sections)) {
                   4356:6):                 if (grep(/^all$/,@groups)) {
                   4357:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4358:6):                                    $stu_status);
                   4359:6):                 } elsif (grep(/^none$/,@groups)) {
                   4360:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4361:6):                                    $stu_status);
                   4362:6):                 } else {
                   4363:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4364:6):                                    $group_display,$stu_status);
                   4365:6):                 }
                   4366:6):             } else {
                   4367:6):                 if (grep(/^all$/,@groups)) {
                   4368:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4369:6):                                    $section_display,$stu_status);
                   4370:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4371:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4372:6):                                    $section_display,$stu_status);
                   4373:6):                 } else {
                   4374:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4375:6):                                    $section_display,$group_display,$stu_status);
                   4376:6):                 }
                   4377:6):             }
                   4378:6):         } else {
                   4379:6):             if (grep(/^all$/,@sections)) {
                   4380:6):                 if (grep(/^all$/,@groups)) {
                   4381:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4382:6):                                    $stu_status,$submission_status);
                   4383:6):                 } elsif (grep(/^none$/,@groups)) {
                   4384:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4385:6):                                    $stu_status,$submission_status);
                   4386:6):                 } else {
                   4387:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4388:6):                                    $group_display,$stu_status,$submission_status);
                   4389:6):                 }
                   4390:6):             } elsif (grep(/^none$/,@sections)) {
                   4391:6):                 if (grep(/^all$/,@groups)) {
                   4392:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4393:6):                                    $stu_status,$submission_status);
                   4394:6):                 } elsif (grep(/^none$/,@groups)) {
                   4395: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.',
                   4396:6):                                    $stu_status,$submission_status);
                   4397:6):                 } else {
                   4398: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.',
                   4399:6):                                    $group_display,$stu_status,$submission_status);
                   4400:6):                 }
                   4401:6):             } else {
                   4402:6):                 if (grep(/^all$/,@groups)) {
                   4403:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4404:6):                                    $section_display,$stu_status,$submission_status);
                   4405:6):                 } elsif (grep(/^none$/,@groups)) {
                   4406: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.',
                   4407:6):                                    $section_display,$stu_status,$submission_status);
                   4408:6):                 } else {
                   4409: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.',
                   4410:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4411:6):                 }
                   4412:6):             }
                   4413:6): 	}
                   4414:6): 	$result .= '</span><br />';
1.96      albertel 4415:     }
1.41      ng       4416:     return $result;
                   4417: }
                   4418: 
1.596.2.12.2.  7(raebur 4419:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4420: sub viewstudentgrade {
1.596.2.12.2.  0.2.4(ra 4421:ul-23):     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4422:     my ($uname,$udom) = split(/:/,$student);
                   4423:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4424:6):     my $submitonly = $env{'form.submitonly'};
                   4425:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4426:6):         my %partstatus = ();
                   4427:6):         if (ref($parts) eq 'ARRAY') {
                   4428:6):             foreach my $apart (@{$parts}) {
                   4429:6):                 my ($part,$type) = &split_part_type($apart);
                   4430:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4431:6):                 $status = 'nothing' if ($status eq '');
                   4432:6):                 $partstatus{$part}      = $status;
                   4433:6):                 my $subkey = "resource.$part.submitted_by";
                   4434:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4435:6):             }
                   4436:6):             my $submitted = 0;
                   4437:6):             my $graded = 0;
                   4438:6):             my $incorrect = 0;
                   4439:6):             foreach my $key (keys(%partstatus)) {
                   4440:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4441:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4442:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4443:6): 
                   4444:6):                 my $partid = (split(/\./,$key))[1];
                   4445:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4446:6):                     $submitted = 0;
                   4447:6):                 }
                   4448:6):             }
                   4449:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4450:6):                                        $submitonly eq 'incorrect' ||
                   4451:6):                                        $submitonly eq 'graded'));
                   4452:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4453:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4454:6):         }
                   4455:6):     }
                   4456:6):     if ($submitonly eq 'queued') {
                   4457:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4458:6):         my %queue_status =
                   4459:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4460:6):                                                     $udom,$uname);
                   4461:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4462:6):     }
                   4463:6):     $$ctr++;
                   4464:6):     my %aggregates = ();
1.474     albertel 4465:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4466:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4467:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4468: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4469: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4470: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4471:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4472:     foreach my $apart (@$parts) {
                   4473: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4474: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4475:         $result.='<td align="center">';
1.269     raeburn  4476:         my ($aggtries,$totaltries);
                   4477:         unless (exists($aggregates{$part})) {
1.270     albertel 4478: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4479: 	    $aggtries = $totaltries;
1.269     raeburn  4480:             if ($$last_resets{$part}) {  
1.270     albertel 4481:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4482: 					   $part);
                   4483:             }
1.269     raeburn  4484:             $result.='<input type="hidden" name="'.
                   4485:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4486:             $result.='<input type="hidden" name="'.
                   4487:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4488:             $aggregates{$part} = 1;
                   4489:         }
1.41      ng       4490: 	if ($type eq 'awarded') {
1.320     albertel 4491: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4492: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4493: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4494: 	    $result.='<input type="text" name="'.
1.89      albertel 4495: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4496:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4497: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4498: 	} elsif ($type eq 'solved') {
                   4499: 	    my ($status,$foo)=split(/_/,$score,2);
                   4500: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4501: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4502: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4503: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4504: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4505:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4506: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4507: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4508: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4509: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4510: 	} else {
                   4511: 	    $result.='<input type="hidden" name="'.
                   4512: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4513: 		    "\n";
1.233     albertel 4514: 	    $result.='<input type="text" name="'.
1.122     ng       4515: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4516: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4517: 	}
                   4518:     }
1.474     albertel 4519:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4520:     return $result;
1.38      ng       4521: }
                   4522: 
1.44      ng       4523: #--- change scores for all the students in a section/class
                   4524: #    record does not get update if unchanged
1.38      ng       4525: sub editgrades {
1.596.2.12.2.  1(raebur 4526:0):     my ($request,$symb) = @_;
          0.2.4(ra 4527:ul-23):     my $toolsymb;
                   4528:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4529:ul-23):         $toolsymb = $symb;
                   4530:ul-23):     }
1.41      ng       4531: 
1.433     banghart 4532:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4533:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4534:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4535: 
1.477     albertel 4536:     my $result= &Apache::loncommon::start_data_table().
                   4537: 	&Apache::loncommon::start_data_table_header_row().
                   4538: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4539: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4540:     my %scoreptr = (
                   4541: 		    'correct'  =>'correct_by_override',
                   4542: 		    'incorrect'=>'incorrect_by_override',
                   4543: 		    'excused'  =>'excused',
                   4544: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4545:                     'credited' =>'credit_attempted',
1.43      ng       4546: 		    'nothing'  => '',
                   4547: 		    );
1.257     albertel 4548:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4549: 
1.44      ng       4550:     my (@partid);
                   4551:     my %weight = ();
1.54      albertel 4552:     my %columns = ();
1.44      ng       4553:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4554: 
1.582     raeburn  4555:     my $partserror;
                   4556:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4557:     if ($partserror) {
                   4558:         return &navmap_errormsg();
                   4559:     }
1.54      albertel 4560:     my $header;
1.257     albertel 4561:     while ($ctr < $env{'form.totalparts'}) {
                   4562: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4563: 	push(@partid,$partid);
1.257     albertel 4564: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4565: 	$ctr++;
1.54      albertel 4566:     }
1.324     albertel 4567:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4568:8):     my $totcolspan = 0;
1.54      albertel 4569:     foreach my $partid (@partid) {
1.478     albertel 4570: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4571: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4572: 	$columns{$partid}=2;
                   4573: 	foreach my $stores (@parts) {
                   4574: 	    my ($part,$type) = &split_part_type($stores);
                   4575: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4576: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.596.2.12.2.  0.2.4(ra 4577:ul-23): 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4578: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4579:             my $narrowtext = &mt('Tries');
                   4580: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4581: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4582: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4583: 	    $columns{$partid}+=2;
                   4584: 	}
1.596.2.12.2.  2(raebur 4585:8):         $totcolspan += $columns{$partid};
1.54      albertel 4586:     }
                   4587:     foreach my $partid (@partid) {
1.324     albertel 4588: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4589: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4590: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4591: 	    '</th>';
1.54      albertel 4592: 
1.44      ng       4593:     }
1.477     albertel 4594:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4595: 	&Apache::loncommon::start_data_table_header_row().
                   4596: 	$header.
                   4597: 	&Apache::loncommon::end_data_table_header_row();
                   4598:     my @noupdate;
1.126     ng       4599:     my ($updateCtr,$noupdateCtr) = (1,1);
1.596.2.12.2.  8(raebur 4600:1):     my ($got_types,%queueable);
1.257     albertel 4601:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4602: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4603: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4604: 	my %newrecord;
                   4605: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4606:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4607:8):         my $canmodify = &canmodify($usec);
                   4608:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4609:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4610:8):         if (!$canmodify) {
                   4611:8):             push(@noupdate,
                   4612:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4613:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4614:8):             next;
                   4615:8):         }
1.269     raeburn  4616:         my %aggregate = ();
                   4617:         my $aggregateflag = 0;
1.281     albertel 4618: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4619: 	foreach (@partid) {
1.257     albertel 4620: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4621: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4622: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4623: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4624: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4625: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4626: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4627: 	    my $score;
                   4628: 	    if ($partial eq '') {
1.257     albertel 4629: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4630: 	    } elsif ($partial > 0) {
                   4631: 		$score = 'correct_by_override';
                   4632: 	    } elsif ($partial == 0) {
                   4633: 		$score = 'incorrect_by_override';
                   4634: 	    }
1.257     albertel 4635: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4636: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4637: 
1.292     albertel 4638: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4639: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4640: 	    if ($dropMenu eq 'reset status' &&
                   4641: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4642: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4643: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4644: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4645: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4646: 		$updateflag = 1;
1.269     raeburn  4647:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4648:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4649:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4650:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4651:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4652:                     $aggregateflag = 1;
                   4653:                 }
1.139     albertel 4654: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4655: 		$updateflag = 1;
                   4656: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4657: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4658: 		$rec_update++;
1.125     ng       4659: 	    }
                   4660: 
1.93      albertel 4661: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4662: 		'<td align="center">'.$awarded.
                   4663: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4664: 
1.54      albertel 4665: 
                   4666: 	    my $partid=$_;
                   4667: 	    foreach my $stores (@parts) {
                   4668: 		my ($part,$type) = &split_part_type($stores);
                   4669: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4670: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4671: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4672: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4673: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4674: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4675: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4676: 		    $updateflag=1;
                   4677: 		}
1.93      albertel 4678: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4679: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4680: 	    }
1.44      ng       4681: 	}
1.477     albertel 4682: 	$line.="\n";
1.301     albertel 4683: 
                   4684: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4685: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4686: 
1.44      ng       4687: 	if ($updateflag) {
                   4688: 	    $count++;
1.257     albertel 4689: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4690: 				    $udom,$uname);
1.301     albertel 4691: 
                   4692: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4693: 					      $cnum,$udom,$uname)) {
                   4694: 		# need to figure out if should be in queue.
                   4695: 		my %record =  
                   4696: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4697: 					     $udom,$uname);
                   4698: 		my $all_graded = 1;
                   4699: 		my $none_graded = 1;
1.596.2.12.2.  8(raebur 4700:1):                 unless ($got_types) {
                   4701:1):                     my $error;
                   4702:1):                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4703:1):                     unless ($error) {
                   4704:1):                         foreach my $part (@parts) {
                   4705:1):                             if (ref($resptype->{$part}) eq 'HASH') {
                   4706:1):                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4707:1):                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4708:1):                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4709:1):                                         $queueable{$part} = 1;
                   4710:1):                                         last;
                   4711:1):                                     }
                   4712:1):                                 }
                   4713:1):                             }
                   4714:1):                         }
                   4715:1):                     }
                   4716:1):                     $got_types = 1;
                   4717:1):                 }
1.301     albertel 4718: 		foreach my $part (@parts) {
1.596.2.12.2.  8(raebur 4719:1):                     if ($queueable{$part}) {
                   4720:1): 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4721:1): 			    $all_graded = 0;
                   4722:1): 		        } else {
                   4723:1): 			    $none_graded = 0;
                   4724:1): 		        }
                   4725:1):                     }
1.301     albertel 4726: 		}
                   4727: 
                   4728: 		if ($all_graded || $none_graded) {
                   4729: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4730: 							   $symb,$cdom,$cnum,
                   4731: 							   $udom,$uname);
                   4732: 		}
                   4733: 	    }
                   4734: 
1.477     albertel 4735: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4736: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4737: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4738: 	    $updateCtr++;
1.93      albertel 4739: 	} else {
1.477     albertel 4740: 	    push(@noupdate,
                   4741: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4742: 	    $noupdateCtr++;
1.44      ng       4743: 	}
1.269     raeburn  4744:         if ($aggregateflag) {
                   4745:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4746: 				  $cdom,$cnum);
1.269     raeburn  4747:         }
1.93      albertel 4748:     }
1.477     albertel 4749:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4750:8):         my $numcols=$totcolspan+2;
1.477     albertel 4751: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4752: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4753: 	    &mt('No Changes Occurred For the Students Below').
                   4754: 	    '</td>'.
1.477     albertel 4755: 	    &Apache::loncommon::end_data_table_row();
                   4756: 	foreach my $line (@noupdate) {
                   4757: 	    $result.=
                   4758: 		&Apache::loncommon::start_data_table_row().
                   4759: 		$line.
                   4760: 		&Apache::loncommon::end_data_table_row();
                   4761: 	}
1.44      ng       4762:     }
1.596.2.12.2.  1(raebur 4763:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4764:     my $msg = '<p><b>'.
                   4765: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4766: 	    $rec_update,$count).'</b><br />'.
                   4767: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4768: 	'</b></p>';
1.44      ng       4769:     return $title.$msg.$result;
1.5       albertel 4770: }
1.54      albertel 4771: 
                   4772: sub split_part_type {
                   4773:     my ($partstr) = @_;
                   4774:     my ($temp,@allparts)=split(/_/,$partstr);
                   4775:     my $type=pop(@allparts);
1.439     albertel 4776:     my $part=join('_',@allparts);
1.54      albertel 4777:     return ($part,$type);
                   4778: }
                   4779: 
1.44      ng       4780: #------------- end of section for handling grading by section/class ---------
                   4781: #
                   4782: #----------------------------------------------------------------------------
                   4783: 
1.5       albertel 4784: 
1.44      ng       4785: #----------------------------------------------------------------------------
                   4786: #
                   4787: #-------------------------- Next few routines handles grading by csv upload
                   4788: #
                   4789: #--- Javascript to handle csv upload
1.27      albertel 4790: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4791:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4792:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4793:6):   &js_escape(\$error1);
                   4794:6):   &js_escape(\$error2);
1.27      albertel 4795:   return(<<ENDPICK);
                   4796:   function verify(vf) {
                   4797:     var foundsomething=0;
                   4798:     var founduname=0;
1.243     albertel 4799:     var foundID=0;
1.27      albertel 4800:     for (i=0;i<=vf.nfields.value;i++) {
                   4801:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4802:       if (i==0 && tw!=0) { foundID=1; }
                   4803:       if (i==1 && tw!=0) { founduname=1; }
                   4804:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4805:     }
1.246     albertel 4806:     if (founduname==0 && foundID==0) {
                   4807: 	alert('$error1');
                   4808: 	return;
1.27      albertel 4809:     }
                   4810:     if (foundsomething==0) {
1.246     albertel 4811: 	alert('$error2');
                   4812: 	return;
1.27      albertel 4813:     }
                   4814:     vf.submit();
                   4815:   }
                   4816:   function flip(vf,tf) {
                   4817:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4818:     var i;
                   4819:     for (i=0;i<=vf.nfields.value;i++) {
                   4820:       //can not pick the same destination field for both name and domain
                   4821:       if (((i ==0)||(i ==1)) && 
                   4822:           ((tf==0)||(tf==1)) && 
                   4823:           (i!=tf) &&
                   4824:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4825:         eval('vf.f'+i+'.selectedIndex=0;')
                   4826:       }
                   4827:     }
                   4828:   }
                   4829: ENDPICK
                   4830: }
                   4831: 
                   4832: sub csvupload_javascript_forward_associate {
1.573     bisitz   4833:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4834:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4835:6):   &js_escape(\$error1);
                   4836:6):   &js_escape(\$error2);
1.27      albertel 4837:   return(<<ENDPICK);
                   4838:   function verify(vf) {
                   4839:     var foundsomething=0;
                   4840:     var founduname=0;
1.243     albertel 4841:     var foundID=0;
1.27      albertel 4842:     for (i=0;i<=vf.nfields.value;i++) {
                   4843:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4844:       if (tw==1) { foundID=1; }
                   4845:       if (tw==2) { founduname=1; }
                   4846:       if (tw>3) { foundsomething=1; }
1.27      albertel 4847:     }
1.246     albertel 4848:     if (founduname==0 && foundID==0) {
                   4849: 	alert('$error1');
                   4850: 	return;
1.27      albertel 4851:     }
                   4852:     if (foundsomething==0) {
1.246     albertel 4853: 	alert('$error2');
                   4854: 	return;
1.27      albertel 4855:     }
                   4856:     vf.submit();
                   4857:   }
                   4858:   function flip(vf,tf) {
                   4859:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4860:     var i;
                   4861:     //can not pick the same destination field twice
                   4862:     for (i=0;i<=vf.nfields.value;i++) {
                   4863:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4864:         eval('vf.f'+i+'.selectedIndex=0;')
                   4865:       }
                   4866:     }
                   4867:   }
                   4868: ENDPICK
                   4869: }
                   4870: 
1.26      albertel 4871: sub csvuploadmap_header {
1.324     albertel 4872:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4873:     my $javascript;
1.257     albertel 4874:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4875: 	$javascript=&csvupload_javascript_reverse_associate();
                   4876:     } else {
                   4877: 	$javascript=&csvupload_javascript_forward_associate();
                   4878:     }
1.45      ng       4879: 
1.257     albertel 4880:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4881:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4882:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4883:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4884:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4885:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4886:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4887:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4888:0): <br />
                   4889:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4890: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4891: <input type="hidden" name="associate"  value="" />
                   4892: <input type="hidden" name="phase"      value="three" />
                   4893: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4894: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4895: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4896: <input type="hidden" name="upfile_associate" 
1.257     albertel 4897:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4898: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4899: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4900: <hr />
                   4901: ENDPICK
1.596.2.12.2.  1(raebur 4902:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4903:     return '';
1.26      albertel 4904: 
                   4905: }
                   4906: 
                   4907: sub csvupload_fields {
1.582     raeburn  4908:     my ($symb,$errorref) = @_;
1.596.2.12.2.  0.2.4(ra 4909:ul-23):     my $toolsymb;
                   4910:ul-23):     if ($symb =~ /ext\.tool$/) {
                   4911:ul-23):         $toolsymb = $symb;
                   4912:ul-23):     }
1.582     raeburn  4913:     my (@parts) = &getpartlist($symb,$errorref);
                   4914:     if (ref($errorref)) {
                   4915:         if ($$errorref) {
                   4916:             return;
                   4917:         }
                   4918:     }
                   4919: 
1.556     weissno  4920:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4921: 		['username','Student Username'],
                   4922: 		['domain','Student Domain']);
1.324     albertel 4923:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4924:     foreach my $part (sort(@parts)) {
                   4925: 	my @datum;
1.596.2.12.2.  0.2.4(ra 4926:ul-23): 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4927: 	my $name=$part;
                   4928: 	if  (!$display) { $display = $name; }
                   4929: 	@datum=($name,$display);
1.244     albertel 4930: 	if ($name=~/^stores_(.*)_awarded/) {
                   4931: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4932: 	}
1.41      ng       4933: 	push(@fields,\@datum);
                   4934:     }
                   4935:     return (@fields);
1.26      albertel 4936: }
                   4937: 
                   4938: sub csvuploadmap_footer {
1.41      ng       4939:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4940:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4941:     $request->print(<<ENDPICK);
1.26      albertel 4942: </table>
                   4943: <input type="hidden" name="nfields" value="$i" />
                   4944: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4945:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4946: </form>
                   4947: ENDPICK
                   4948: }
                   4949: 
1.283     albertel 4950: sub checkforfile_js {
1.539     riegler  4951:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4952:6):     &js_escape(\$alertmsg);
          1(raebur 4953:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4954:     function checkUpload(formname) {
                   4955: 	if (formname.upfile.value == "") {
1.539     riegler  4956: 	    alert("$alertmsg");
1.86      ng       4957: 	    return false;
                   4958: 	}
                   4959: 	formname.submit();
                   4960:     }
                   4961: CSVFORMJS
1.283     albertel 4962:     return $result;
                   4963: }
                   4964: 
                   4965: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4966:0):     my ($request,$symb) = @_;
1.283     albertel 4967:     if (!$symb) {return '';}
                   4968:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4969:0):     $result.=&Apache::loncommon::start_data_table().
                   4970:0):              &Apache::loncommon::start_data_table_header_row().
                   4971:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4972:0):              &Apache::loncommon::end_data_table_header_row().
                   4973:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4974:     my $upload=&mt("Upload Scores");
1.86      ng       4975:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4976:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4977:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4978:     $result.=<<ENDUPFORM;
1.106     albertel 4979: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4980: <input type="hidden" name="symb" value="$symb" />
                   4981: <input type="hidden" name="command" value="csvuploadmap" />
                   4982: $upfile_select
1.589     bisitz   4983: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4984: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4985: </form>
                   4986: ENDUPFORM
1.370     www      4987:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 4988:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   4989:0):             '</td>'.
                   4990:0):             &Apache::loncommon::end_data_table_row().
                   4991:0):             &Apache::loncommon::end_data_table();
1.86      ng       4992:     return $result;
                   4993: }
                   4994: 
                   4995: 
1.26      albertel 4996: sub csvuploadmap {
1.596.2.12.2.  1(raebur 4997:0):     my ($request,$symb) = @_;
1.41      ng       4998:     if (!$symb) {return '';}
1.72      ng       4999: 
1.41      ng       5000:     my $datatoken;
1.257     albertel 5001:     if (!$env{'form.datatoken'}) {
1.41      ng       5002: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 5003:     } else {
1.596.2.12.2.  3(raebur 5004:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5005:8):         if ($datatoken ne '') { 
                   5006:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5007:8):         }
1.26      albertel 5008:     }
1.41      ng       5009:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 5010:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 5011:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       5012:     my ($i,$keyfields);
                   5013:     if (@records) {
1.582     raeburn  5014:         my $fieldserror;
                   5015: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   5016:         if ($fieldserror) {
                   5017:             $request->print(&navmap_errormsg());
                   5018:             return;
                   5019:         }
1.257     albertel 5020: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       5021: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   5022: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   5023: 							  \@fields);
                   5024: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   5025: 	    chop($keyfields);
                   5026: 	} else {
                   5027: 	    unshift(@fields,['none','']);
                   5028: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   5029: 							    \@fields);
1.311     banghart 5030:             foreach my $rec (@records) {
                   5031:                 my %temp = &Apache::loncommon::record_sep($rec);
                   5032:                 if (%temp) {
                   5033:                     $keyfields=join(',',sort(keys(%temp)));
                   5034:                     last;
                   5035:                 }
                   5036:             }
1.41      ng       5037: 	}
                   5038:     }
                   5039:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       5040: 
1.41      ng       5041:     return '';
1.27      albertel 5042: }
                   5043: 
1.246     albertel 5044: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 5045:0):     my ($request,$symb)= @_;
                   5046:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 5047:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 5048:     my $ignore=&mt('Ignore First Line');
                   5049:     $request->print(<<ENDPICK);
                   5050: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   5051: <input type="hidden" name="command"    value="csvuploadassign" />
                   5052: <p>
                   5053: <label>
                   5054:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 5055:0):    $overwrite
1.246     albertel 5056: </label>
                   5057: </p>
                   5058: ENDPICK
                   5059:     my %fields=&get_fields();
                   5060:     if (!defined($fields{'domain'})) {
1.257     albertel 5061: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 5062:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 5063:     }
1.257     albertel 5064:     foreach my $key (sort(keys(%env))) {
1.246     albertel 5065: 	if ($key !~ /^form\.(.*)$/) { next; }
                   5066: 	my $cleankey=$1;
                   5067: 	if ($cleankey eq 'command') { next; }
                   5068: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 5069: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 5070:     }
                   5071:     # FIXME do a check for any duplicated user ids...
                   5072:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 5073:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5074: <hr /></form>'."\n");
1.246     albertel 5075:     return '';
                   5076: }
                   5077: 
                   5078: sub get_fields {
                   5079:     my %fields;
1.257     albertel 5080:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5081:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5082: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5083: 	    if ($env{'form.f'.$i} ne 'none') {
                   5084: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5085: 	    }
                   5086: 	} else {
1.257     albertel 5087: 	    if ($env{'form.f'.$i} ne 'none') {
                   5088: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       5089: 	    }
                   5090: 	}
1.27      albertel 5091:     }
1.246     albertel 5092:     return %fields;
                   5093: }
                   5094: 
                   5095: sub csvuploadassign {
1.596.2.12.2.  1(raebur 5096:0):     my ($request,$symb) = @_;
1.246     albertel 5097:     if (!$symb) {return '';}
1.345     bowersj2 5098:     my $error_msg = '';
1.596.2.12.2.  3(raebur 5099:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5100:8):     if ($datatoken ne '') {
                   5101:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5102:8):     }
1.246     albertel 5103:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 5104:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 5105:     my %fields=&get_fields();
1.257     albertel 5106:     my $courseid=$env{'request.course.id'};
1.97      albertel 5107:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 5108:     my @notallowed;
1.41      ng       5109:     my @skipped;
1.596.2.4  raeburn  5110:     my @warnings;
1.41      ng       5111:     my $countdone=0;
                   5112:     foreach my $grade (@gradedata) {
                   5113: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5114: 	my $domain;
                   5115: 	if ($entries{$fields{'domain'}}) {
                   5116: 	    $domain=$entries{$fields{'domain'}};
                   5117: 	} else {
1.257     albertel 5118: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5119: 	}
1.243     albertel 5120: 	$domain=~s/\s//g;
1.41      ng       5121: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5122: 	$username=~s/\s//g;
1.243     albertel 5123: 	if (!$username) {
                   5124: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5125: 	    $id=~s/\s//g;
1.243     albertel 5126: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   5127: 	    $username=$ids{$id};
                   5128: 	}
1.41      ng       5129: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5130: 	    my $id=$entries{$fields{'ID'}};
                   5131: 	    $id=~s/\s//g;
                   5132: 	    if ($id) {
                   5133: 		push(@skipped,"$id:$domain");
                   5134: 	    } else {
                   5135: 		push(@skipped,"$username:$domain");
                   5136: 	    }
1.41      ng       5137: 	    next;
                   5138: 	}
1.108     albertel 5139: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5140: 	if (!&canmodify($usec)) {
                   5141: 	    push(@notallowed,"$username:$domain");
                   5142: 	    next;
                   5143: 	}
1.244     albertel 5144: 	my %points;
1.41      ng       5145: 	my %grades;
                   5146: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5147: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5148: 		$dest eq 'domain') { next; }
                   5149: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5150: 	    if ($dest=~/stores_(.*)_points/) {
                   5151: 		my $part=$1;
                   5152: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5153: 					      $symb,$domain,$username);
1.345     bowersj2 5154:                 if ($wgt) {
                   5155:                     $entries{$fields{$dest}}=~s/\s//g;
                   5156:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5157:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5158:                                           : 'correct_by_override';
1.596.2.4  raeburn  5159:                     if ($pcr>1) {
                   5160:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   5161:                     }
1.345     bowersj2 5162:                     $grades{"resource.$part.awarded"}=$pcr;
                   5163:                     $grades{"resource.$part.solved"}=$award;
                   5164:                     $points{$part}=1;
                   5165:                 } else {
                   5166:                     $error_msg = "<br />" .
                   5167:                         &mt("Some point values were assigned"
                   5168:                             ." for problems with a weight "
                   5169:                             ."of zero. These values were "
                   5170:                             ."ignored.");
                   5171:                 }
1.244     albertel 5172: 	    } else {
                   5173: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5174: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5175: 		my $store_key=$dest;
                   5176: 		$store_key=~s/^stores/resource/;
                   5177: 		$store_key=~s/_/\./g;
                   5178: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5179: 	    }
1.41      ng       5180: 	}
1.596.2.12.2.  1(raebur 5181:0): 	if (! %grades) {
1.508     www      5182:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5183:         } else {
                   5184: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5185: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5186: 					   $env{'request.course.id'},
                   5187: 					   $domain,$username);
1.508     www      5188: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 5189:0): # Successfully stored
1.508     www      5190: 	      $request->print('.');
1.596.2.4  raeburn  5191: # Remove from grading queue
                   5192:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5193:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5194:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5195:                                              $domain,$username);
1.508     www      5196: 	   } else {
                   5197: 	      $request->print("<p><span class=\"LC_error\">".
                   5198:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5199:                                   "$username:$domain",$result)."</span></p>");
                   5200: 	   }
                   5201: 	   $request->rflush();
                   5202: 	   $countdone++;
                   5203:         }
1.41      ng       5204:     }
1.570     www      5205:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5206:     if (@warnings) {
                   5207:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5208:         $request->print(join(', ',@warnings));
                   5209:     }
1.41      ng       5210:     if (@skipped) {
1.571     www      5211: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5212:         $request->print(join(', ',@skipped));
1.106     albertel 5213:     }
                   5214:     if (@notallowed) {
1.571     www      5215: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5216: 	$request->print(join(', ',@notallowed));
1.41      ng       5217:     }
1.106     albertel 5218:     $request->print("<br />\n");
1.345     bowersj2 5219:     return $error_msg;
1.26      albertel 5220: }
1.44      ng       5221: #------------- end of section for handling csv file upload ---------
                   5222: #
                   5223: #-------------------------------------------------------------------
                   5224: #
1.122     ng       5225: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5226: #
                   5227: #--- Select a page/sequence and a student to grade
1.68      ng       5228: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5229:0):     my ($request,$symb) = @_;
1.68      ng       5230: 
1.539     riegler  5231:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5232:6):     &js_escape(\$alertmsg);
          1(raebur 5233:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5234: 
                   5235: function checkPickOne(formname) {
1.76      ng       5236:     if (radioSelection(formname.student) == null) {
1.539     riegler  5237: 	alert("$alertmsg");
1.68      ng       5238: 	return;
                   5239:     }
1.125     ng       5240:     ptr = pullDownSelection(formname.selectpage);
                   5241:     formname.page.value = formname["page"+ptr].value;
                   5242:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5243:     formname.submit();
                   5244: }
                   5245: 
                   5246: LISTJAVASCRIPT
1.118     ng       5247:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5248:0): 
1.257     albertel 5249:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5250:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5251:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5252:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5253: 
1.398     albertel 5254:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5255: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5256: 
1.80      ng       5257:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5258:     my $map_error;
                   5259:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5260:     if ($map_error) {
                   5261:         $request->print(&navmap_errormsg());
                   5262:         return; 
                   5263:     }
1.137     albertel 5264:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5265: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5266: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5267: 
1.596.2.12.2.  1(raebur 5268:0):     # Collection of hidden fields
                   5269:0):     my $ctr=0;
1.70      ng       5270:     foreach (@$titles) {
                   5271: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5272: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5273: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5274: 	$ctr++;
                   5275:     }
1.72      ng       5276:     $result.='<input type="hidden" name="page" />'."\n".
                   5277: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5278: 
1.432     banghart 5279:     $result.=&build_section_inputs();
1.442     banghart 5280:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5281:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5282:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5283:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5284:0): 
                   5285:0):     # Show grading options
                   5286:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5287:0):     my $select = '<select name="selectpage">'."\n";
                   5288:0):     $ctr=0;
                   5289:0):     foreach (@$titles) {
                   5290:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5291:0):         $select.='<option value="'.$ctr.'"'.
                   5292:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5293:0):             '>'.$showtitle.'</option>'."\n";
                   5294:0):         $ctr++;
                   5295:0):     }
                   5296:0):     $select.= '</select>';
1.72      ng       5297: 
1.596.2.12.2.  1(raebur 5298:0):     $result.=
                   5299:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5300:0):        .$select
                   5301:0):        .&Apache::lonhtmlcommon::row_closure();
                   5302:0): 
                   5303:0):     $result.=
                   5304:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5305:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5306:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5307:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5308:0):            .&mt('yes').'</label>'."\n"
                   5309:0):        .&Apache::lonhtmlcommon::row_closure();
                   5310:0): 
                   5311:0):     $result.=
                   5312:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5313:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5314:0):            .&mt('none').' </label>'."\n"
                   5315:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5316:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5317:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5318:0):            .&mt('all submissions with details').' </label>'
                   5319:0):        .&Apache::lonhtmlcommon::row_closure();
                   5320:0): 
                   5321:0):     $result.=
                   5322:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5323:0):        .'<input type="text" name="CODE" value="" />'
                   5324:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5325:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5326: 
1.596.2.12.2.  1(raebur 5327:0):     # Show list of students to select for grading
                   5328:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5329:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5330: 
1.68      ng       5331:     $request->print($result);
                   5332: 
1.485     albertel 5333:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5334: 	&Apache::loncommon::start_data_table().
                   5335: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5336: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5337: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5338: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5339: 	'<th>'.&nameUserString('header').'</th>'.
                   5340: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5341:  
1.596.2.12.2.  8(raebur 5342:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5343:     my $ptr = 1;
1.294     albertel 5344:     foreach my $student (sort 
                   5345: 			 {
                   5346: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5347: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5348: 			     }
                   5349: 			     return $a cmp $b;
                   5350: 			 } (keys(%$fullname))) {
1.68      ng       5351: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5352: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5353:                                   : '</td>');
1.126     ng       5354: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5355: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5356: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5357: 	$studentTable.=
                   5358: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5359:                          : '');
1.68      ng       5360: 	$ptr++;
                   5361:     }
1.484     albertel 5362:     if ($ptr%2 == 0) {
                   5363: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5364: 	    &Apache::loncommon::end_data_table_row();
                   5365:     }
                   5366:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5367:     $studentTable.='<input type="button" '.
1.589     bisitz   5368:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5369: 
                   5370:     $request->print($studentTable);
                   5371: 
                   5372:     return '';
                   5373: }
                   5374: 
                   5375: sub getSymbMap {
1.582     raeburn  5376:     my ($map_error) = @_;
1.132     bowersj2 5377:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5378:     unless (ref($navmap)) {
                   5379:         if (ref($map_error)) {
                   5380:             $$map_error = 'navmap';
                   5381:         }
                   5382:         return;
                   5383:     }
1.68      ng       5384:     my %symbx = ();
                   5385:     my @titles = ();
1.117     bowersj2 5386:     my $minder = 0;
                   5387: 
                   5388:     # Gather every sequence that has problems.
1.240     albertel 5389:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5390: 					       1,0,1);
1.117     bowersj2 5391:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.596.2.12.2.  0.2.4(ra 5392:ul-23): 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5393: 	    my $title = $minder.'.'.
                   5394: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5395: 	    push(@titles, $title); # minder in case two titles are identical
                   5396: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5397: 	    $minder++;
1.241     albertel 5398: 	}
1.68      ng       5399:     }
                   5400:     return \@titles,\%symbx;
                   5401: }
                   5402: 
1.72      ng       5403: #
                   5404: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5405: sub displayPage {
1.596.2.12.2.  1(raebur 5406:0):     my ($request,$symb) = @_;
1.257     albertel 5407:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5408:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5409:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5410:     my $pageTitle = $env{'form.page'};
1.103     albertel 5411:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5412:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5413:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5414: 
                   5415:     #need to make sure we have the correct data for later EXT calls, 
                   5416:     #thus invalidate the cache
                   5417:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5418:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5419:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5420:     &Apache::lonnet::clear_EXT_cache_status();
                   5421: 
1.103     albertel 5422:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5423:0): 	$request->print(
                   5424:0):             '<span class="LC_warning">'.
                   5425:0):             &mt('Unable to view requested student. ([_1])',
                   5426:0):                 $env{'form.student'}).
                   5427:0):             '</span>');
          8(raebur 5428:4):         return;
1.103     albertel 5429:     }
1.398     albertel 5430:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5431:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5432: 	'</h3>'."\n";
1.500     albertel 5433:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5434:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5435: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5436:     } else {
                   5437: 	delete($env{'form.CODE'});
                   5438:     }
1.71      ng       5439:     &sub_page_js($request);
                   5440:     $request->print($result);
                   5441: 
1.132     bowersj2 5442:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5443:     unless (ref($navmap)) {
                   5444:         $request->print(&navmap_errormsg());
                   5445:         return;
                   5446:     }
1.257     albertel 5447:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5448:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5449:     if (!$map) {
1.485     albertel 5450: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5451: 	return; 
                   5452:     }
1.68      ng       5453:     my $iterator = $navmap->getIterator($map->map_start(),
                   5454: 					$map->map_finish());
                   5455: 
1.71      ng       5456:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5457: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5458: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5459: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5460: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5461: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5462: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5463:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5464: 
1.382     albertel 5465:     if (defined($env{'form.CODE'})) {
                   5466: 	$studentTable.=
                   5467: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5468:     }
1.381     albertel 5469:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5470: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5471: 
1.594     bisitz   5472:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5473:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5474:         '</span>'."\n".
1.484     albertel 5475: 	&Apache::loncommon::start_data_table().
                   5476: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5477:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5478: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5479: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5480: 
1.329     albertel 5481:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5482:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5483:     $iterator->next(); # skip the first BEGIN_MAP
                   5484:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5485:     while ($depth > 0) {
1.68      ng       5486:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5487:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5488: 
1.596.2.12.2.  0.2.4(ra 5489:ul-23):         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5490: 	    my $parts = $curRes->parts();
1.68      ng       5491:             my $title = $curRes->compTitle();
1.71      ng       5492: 	    my $symbx = $curRes->symb();
1.596.2.12.2.  0.2.4(ra 5493:ul-23):             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5494: 	    $studentTable.=
                   5495: 		&Apache::loncommon::start_data_table_row().
                   5496: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5497: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5498:2): 		                        : '<br />('.&mt('[_1]parts',
                   5499:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5500: 		 ).
                   5501: 		 '</td>';
1.71      ng       5502: 	    $studentTable.='<td valign="top">';
1.382     albertel 5503: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.596.2.12.2.  0.2.4(ra 5504:ul-23):             if ($is_tool) {
                   5505:ul-23):                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5506:ul-23):             } else {
                   5507:ul-23): 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5508:ul-23): 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5509:ul-23): 			   		         undef,'both',\%form);
                   5510:ul-23): 	        } else {
                   5511:ul-23): 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5512:ul-23): 		    $companswer =~ s|<form(.*?)>||g;
                   5513:ul-23): 		    $companswer =~ s|</form>||g;
                   5514:ul-23): #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5515:ul-23): #		        $companswer =~ s/$1/ /ms;
                   5516:ul-23): #		        $request->print('match='.$1."<br />\n");
                   5517:ul-23): #		    }
                   5518:ul-23): #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5519:ul-23): 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5520:ul-23):                 }
1.71      ng       5521: 	    }
                   5522: 
1.257     albertel 5523: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5524: 
1.257     albertel 5525: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5526: 		if ($record{'version'} eq '') {
1.596.2.12.2.  0.2.4(ra 5527:ul-23):                     my $msg = &mt('No recorded submission for this problem.');
                   5528:ul-23):                     if ($is_tool) {
                   5529:ul-23):                         $msg = &mt('No recorded transactions for this external tool');
                   5530:ul-23):                     }
                   5531:ul-23): 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5532: 		} else {
1.116     ng       5533: 		    my %responseType = ();
                   5534: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5535: 			my @responseIds =$curRes->responseIds($partid);
                   5536: 			my @responseType =$curRes->responseType($partid);
                   5537: 			my %responseIds;
                   5538: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5539: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5540: 			}
                   5541: 			$responseType{$partid} = \%responseIds;
1.116     ng       5542: 		    }
1.148     albertel 5543: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5544: 
1.71      ng       5545: 		}
1.257     albertel 5546: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5547: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5548:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5549: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5550: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5551:5): 									'','.submission',undef,
                   5552:5):                                                                         $usec,$identifier);
1.71      ng       5553:  
                   5554: 	    }
1.103     albertel 5555: 	    if (&canmodify($usec)) {
1.585     bisitz   5556:             $studentTable.=&gradeBox_start();
1.103     albertel 5557: 		foreach my $partid (@{$parts}) {
                   5558: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5559: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5560: 		    $question++;
                   5561: 		}
1.585     bisitz   5562:             $studentTable.=&gradeBox_end();
1.196     albertel 5563: 		$prob++;
1.71      ng       5564: 	    }
                   5565: 	    $studentTable.='</td></tr>';
1.68      ng       5566: 
1.103     albertel 5567: 	}
1.68      ng       5568:         $curRes = $iterator->next();
                   5569:     }
1.596.2.12.2.  6(raebur 5570:1):     my $disabled;
                   5571:1):     unless (&canmodify($usec)) {
                   5572:1):         $disabled = ' disabled="disabled"';
                   5573:1):     }
1.68      ng       5574: 
1.589     bisitz   5575:     $studentTable.=
                   5576:         '</table>'."\n".
1.596.2.12.2.  6(raebur 5577:1):         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5578:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5579:         '</form>'."\n";
1.71      ng       5580:     $request->print($studentTable);
                   5581: 
                   5582:     return '';
1.119     ng       5583: }
                   5584: 
                   5585: sub displaySubByDates {
1.148     albertel 5586:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5587:     my $isCODE=0;
1.335     albertel 5588:     my $isTask = ($symb =~/\.task$/);
1.596.2.12.2.  0.2.4(ra 5589:ul-23):     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5590:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5591:     my $studentTable=&Apache::loncommon::start_data_table().
                   5592: 	&Apache::loncommon::start_data_table_header_row().
                   5593: 	'<th>'.&mt('Date/Time').'</th>'.
                   5594: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5595:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
          0.2.4(ra 5596:ul-23): 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5597: 	'<th>'.&mt('Status').'</th>'.
                   5598: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5599:     my ($version);
                   5600:     my %mark;
1.148     albertel 5601:     my %orders;
1.119     ng       5602:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5603:     if (!exists($$record{'1:timestamp'})) {
1.596.2.12.2.  0.2.4(ra 5604:ul-23):         if ($is_tool) {
                   5605:ul-23):             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5606:ul-23):         } else {
                   5607:ul-23): 	    return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5608:ul-23):         }
1.147     albertel 5609:     }
1.335     albertel 5610: 
                   5611:     my $interaction;
1.525     raeburn  5612:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5613:5):     my (%lastrndseed,%lasttype);
1.119     ng       5614:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5615: 	my $timestamp = 
                   5616: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5617: 	if (exists($$record{$version.':resource.0.version'})) {
                   5618: 	    $interaction = $$record{$version.':resource.0.version'};
                   5619: 	}
1.596.2.12.2.  (raeburn 5620:):         if ($isTask && $env{'form.previousversion'}) {
                   5621:):             next unless ($interaction == $env{'form.previousversion'});
                   5622:):         }
1.335     albertel 5623: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5624: 		             : "$version:resource");
1.467     albertel 5625: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5626: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5627: 	if ($isCODE) {
                   5628: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5629: 	}
1.596.2.12.2.  (raeburn 5630:):         if ($isTask) {
                   5631:):             $studentTable.='<td>'.$interaction.'</td>';
                   5632:):         }
1.119     ng       5633: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5634: 	my @displaySub = ();
                   5635: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5636:             my ($hidden,$type);
                   5637:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5638:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5639:                 $hidden = 1;
                   5640:             }
1.596.2.12.2.  1(raebur 5641:0): 	    my @matchKey;
                   5642:0):             if ($isTask) {
                   5643:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
          0.2.4(ra 5644:ul-23):             } elsif ($is_tool) {
                   5645:ul-23):                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
          1(raebur 5646:0):             } else {
                   5647:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5648:0):             }
1.122     ng       5649: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5650: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5651: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5652: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5653: 		    $$record{$version.':'.$matchKey} ne '') {
1.596.2.12.2.  0.2.4(ra 5654:ul-23):                     if ($is_tool) {
                   5655:ul-23):                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5656:                     } else {
1.596.2.12.2.  0.2.4(ra 5657:ul-23): 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5658:ul-23): 			    	                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5659:ul-23):                         $displaySub[0].='<span class="LC_nobreak">';
                   5660:ul-23):                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5661:ul-23):                                        .' <span class="LC_internal_info">'
                   5662:ul-23):                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5663:ul-23):                                        .'</span>'
                   5664:ul-23):                                        .' <b>';
                   5665:ul-23):                         if ($hidden) {
                   5666:ul-23):                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5667:ul-23):                         } else {
                   5668:ul-23):                             my ($trial,$rndseed,$newvariation);
                   5669:ul-23):                             if ($type eq 'randomizetry') {
                   5670:ul-23):                                 $trial = $$record{"$where.$partid.tries"};
                   5671:ul-23):                                 $rndseed = $$record{"$where.$partid.rndseed"};
1.596.2.2  raeburn  5672:                             }
1.596.2.12.2.  0.2.4(ra 5673:ul-23): 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5674:ul-23): 			        $displaySub[0].=&mt('Trial not counted');
                   5675:ul-23): 		            } else {
                   5676:ul-23): 			        $displaySub[0].=&mt('Trial: [_1]',
                   5677:ul-23): 				    	        $$record{"$where.$partid.tries"});
                   5678:ul-23):                                 if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
                   5679:ul-23):                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5680:ul-23):                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5681:ul-23):                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5682:ul-23):                                     }
                   5683:ul-23):                                 }
                   5684:ul-23):                                 $lastrndseed{$partid} = $rndseed;
                   5685:ul-23):                                 $lasttype{$partid} = $type;
                   5686:ul-23): 		           }
                   5687:ul-23): 		           my $responseType=($isTask ? 'Task'
                   5688:ul-23):                                                   : $responseType->{$partid}->{$responseId});
                   5689:ul-23): 		           if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5690:ul-23): 		           if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5691:ul-23): 			       $orders{$partid}->{$responseId}=
                   5692:ul-23): 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5693:ul-23):                                                $no_increment,$type,$trial,$rndseed);
                   5694:ul-23): 		            }
                   5695:ul-23): 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5696:ul-23): 		            $displaySub[0].='&nbsp; '.
                   5697:ul-23): 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5698:ul-23):                         }
1.596     raeburn  5699:                     }
1.147     albertel 5700: 		}
                   5701: 	    }
1.335     albertel 5702: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5703: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5704: 				    $$record{"$where.$partid.checkedin"},
                   5705: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5706: 					'<br />';
1.335     albertel 5707: 	    }
                   5708: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5709: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5710: 		    lc($$record{"$where.$partid.award"}).' '.
                   5711: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5712: 		    '<br />';
1.596.2.12.2.  0.2.4(ra 5713:ul-23):             } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5714:ul-23):                 if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5715:ul-23):                     $displaySub[1].=&mt('Grade passed back by external tool');
                   5716:ul-23):                 }
1.147     albertel 5717: 	    }
1.335     albertel 5718: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.596.2.12.2.  0.2.4(ra 5719:ul-23): 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5720:ul-23):                 unless ($is_tool) {
                   5721:ul-23): 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5722:ul-23):                 }
1.335     albertel 5723: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5724: 		$displaySub[2].=
1.596.2.12.2.  0.2.4(ra 5725:ul-23): 		    $$record{"$version:resource.$partid.regrader"};
                   5726:ul-23):                 unless ($is_tool) {
                   5727:ul-23): 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5728:ul-23):                 }
1.147     albertel 5729: 	    }
                   5730: 	}
                   5731: 	# needed because old essay regrader has not parts info
                   5732: 	if (exists $$record{"$version:resource.regrader"}) {
                   5733: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5734: 	}
                   5735: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5736: 	if ($displaySub[2]) {
1.467     albertel 5737: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5738: 	}
1.467     albertel 5739: 	$studentTable.='&nbsp;</td>'.
                   5740: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5741:     }
1.467     albertel 5742:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5743:     return $studentTable;
1.71      ng       5744: }
                   5745: 
                   5746: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5747:0):     my ($request,$symb) = @_;
1.71      ng       5748: 
1.257     albertel 5749:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5750:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5751:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5752:     my $pageTitle = $env{'form.page'};
1.103     albertel 5753:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5754:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5755:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5756:     if (!&canmodify($usec)) {
1.526     raeburn  5757: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5758: 	return;
                   5759:     }
1.398     albertel 5760:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5761:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5762: 	'</h3>'."\n";
1.70      ng       5763: 
1.68      ng       5764:     $request->print($result);
                   5765: 
1.582     raeburn  5766: 
1.132     bowersj2 5767:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5768:     unless (ref($navmap)) {
                   5769:         $request->print(&navmap_errormsg());
                   5770:         return;
                   5771:     }
1.257     albertel 5772:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5773:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5774:     if (!$map) {
1.527     raeburn  5775: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5776: 	return; 
                   5777:     }
1.71      ng       5778:     my $iterator = $navmap->getIterator($map->map_start(),
                   5779: 					$map->map_finish());
1.70      ng       5780: 
1.484     albertel 5781:     my $studentTable=
                   5782: 	&Apache::loncommon::start_data_table().
                   5783: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5784: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5785: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5786: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5787: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5788: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5789: 
                   5790:     $iterator->next(); # skip the first BEGIN_MAP
                   5791:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5792:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5793:     while ($depth > 0) {
1.71      ng       5794:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5795:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5796: 
1.385     albertel 5797:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5798: 	    my $parts = $curRes->parts();
1.71      ng       5799:             my $title = $curRes->compTitle();
                   5800: 	    my $symbx = $curRes->symb();
1.484     albertel 5801: 	    $studentTable.=
                   5802: 		&Apache::loncommon::start_data_table_row().
                   5803: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5804: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5805:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5806: 		.')').'</td>';
1.71      ng       5807: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5808: 
                   5809: 	    my %newrecord=();
                   5810: 	    my @displayPts=();
1.269     raeburn  5811:             my %aggregate = ();
                   5812:             my $aggregateflag = 0;
1.596.2.12.2.  9(raebur 5813:1):             my %queueable;
          1(raebur 5814:5):             if ($env{'form.HIDE'.$prob}) {
                   5815:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5816:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5817:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5818:5):                 $hideflag += $numchgs;
                   5819:5):             }
1.71      ng       5820: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5821: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5822: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.596.2.12.2.  9(raebur 5823:1):                 my @types = $curRes->responseType($partid);
          8(raebur 5824:1):                 if (grep(/^essay$/,@types)) {
                   5825:1):                     $queueable{$partid} = 1;
                   5826:1):                 } else {
          9(raebur 5827:1):                     my @ids = $curRes->responseIds($partid);
          8(raebur 5828:1):                     for (my $i=0; $i < scalar(@ids); $i++) {
          9(raebur 5829:1):                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
          8(raebur 5830:1):                                                           '.handgrade',$symb);
                   5831:1):                         if (lc($hndgrd) eq 'yes') {
                   5832:1):                             $queueable{$partid} = 1;
                   5833:1):                             last;
                   5834:1):                         }
                   5835:1):                     }
                   5836:1):                 }
1.257     albertel 5837: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5838: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5839: 		my $partial = $newpts/$wgt;
                   5840: 		my $score;
                   5841: 		if ($partial > 0) {
                   5842: 		    $score = 'correct_by_override';
1.125     ng       5843: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5844: 		    $score = 'incorrect_by_override';
                   5845: 		}
1.257     albertel 5846: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5847: 		if ($dropMenu eq 'excused') {
1.71      ng       5848: 		    $partial = '';
                   5849: 		    $score = 'excused';
1.125     ng       5850: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5851: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5852: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5853: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5854: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5855: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5856: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5857: 		    $changeflag++;
                   5858: 		    $newpts = '';
1.269     raeburn  5859:                     
                   5860:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5861:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5862:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5863:                     if ($aggtries > 0) {
                   5864:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5865:                         $aggregateflag = 1;
                   5866:                     }
1.71      ng       5867: 		}
1.324     albertel 5868: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5869: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5870: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5871: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5872: 		    '&nbsp;<br />';
1.526     raeburn  5873: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5874: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5875: 		    '&nbsp;<br />';
1.71      ng       5876: 		$question++;
1.380     albertel 5877: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5878: 
1.71      ng       5879: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5880: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5881: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5882: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5883: 
                   5884: 		$changeflag++;
                   5885: 	    }
                   5886: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5887: 		my %record = 
                   5888: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5889: 					     $udom,$uname);
                   5890: 
                   5891: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5892: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5893: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5894: 		    $newrecord{'resource.CODE'} = '';
                   5895: 		}
1.257     albertel 5896: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5897: 					$udom,$uname);
1.382     albertel 5898: 		%record = &Apache::lonnet::restore($symbx,
                   5899: 						   $env{'request.course.id'},
                   5900: 						   $udom,$uname);
1.380     albertel 5901: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.596.2.12.2.  8(raebur 5902:1): 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5903: 	    }
1.380     albertel 5904: 	    
1.269     raeburn  5905:             if ($aggregateflag) {
                   5906:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5907:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5908:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5909:             }
1.125     ng       5910: 
1.71      ng       5911: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5912: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5913: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5914: 
1.196     albertel 5915: 	    $prob++;
1.68      ng       5916: 	}
1.71      ng       5917:         $curRes = $iterator->next();
1.68      ng       5918:     }
1.98      albertel 5919: 
1.484     albertel 5920:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5921:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5922: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5923:5): 		  $changeflag).'<br />');
                   5924:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5925:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5926:5):                      $hideflag).'<br />');
                   5927:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5928: 
1.70      ng       5929:     return '';
                   5930: }
                   5931: 
1.72      ng       5932: #-------- end of section for handling grading by page/sequence ---------
                   5933: #
                   5934: #-------------------------------------------------------------------
                   5935: 
1.581     www      5936: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5937: #
                   5938: #------ start of section for handling grading by page/sequence ---------
                   5939: 
1.423     albertel 5940: =pod
                   5941: 
                   5942: =head1 Bubble sheet grading routines
                   5943: 
1.424     albertel 5944:   For this documentation:
                   5945: 
                   5946:    'scanline' refers to the full line of characters
                   5947:    from the file that we are parsing that represents one entire sheet
                   5948: 
                   5949:    'bubble line' refers to the data
1.596.2.6  raeburn  5950:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5951: 
                   5952: 
1.596.2.6  raeburn  5953: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5954: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5955: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5956: one of the predefined configurations for what each scanline looks
                   5957: like.
                   5958: 
                   5959: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5960: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5961: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5962:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5963: invalid student/employee ID
1.424     albertel 5964: 
                   5965: If the CODE option is used that determines the randomization of the
1.556     weissno  5966: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5967: username:domain.
                   5968: 
                   5969: During the validation phase the instructor can choose to skip scanlines. 
                   5970: 
1.596.2.6  raeburn  5971: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5972: 
                   5973:   scantron_original_filename (unmodified original file)
                   5974:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5975:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5976: 
                   5977: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5978: correction information that isn't representable in the bubblesheet
1.424     albertel 5979: file (see &scantron_getfile() for more information)
                   5980: 
                   5981: After all scanlines are either valid, marked as valid or skipped, then
                   5982: foreach line foreach problem in the picked sequence, an ssi request is
                   5983: made that simulates a user submitting their selected letter(s) against
                   5984: the homework problem.
1.423     albertel 5985: 
                   5986: =over 4
                   5987: 
                   5988: 
                   5989: 
                   5990: =item defaultFormData
                   5991: 
                   5992:   Returns html hidden inputs used to hold context/default values.
                   5993: 
                   5994:  Arguments:
                   5995:   $symb - $symb of the current resource 
                   5996: 
                   5997: =cut
1.422     foxr     5998: 
1.81      albertel 5999: sub defaultFormData {
1.324     albertel 6000:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 6001:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 6002: }
                   6003: 
1.447     foxr     6004: 
1.423     albertel 6005: =pod 
                   6006: 
                   6007: =item getSequenceDropDown
                   6008: 
                   6009:    Return html dropdown of possible sequences to grade
                   6010:  
                   6011:  Arguments:
1.582     raeburn  6012:    $symb - $symb of the current resource
                   6013:    $map_error - ref to scalar which will container error if
                   6014:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 6015: 
                   6016: =cut
1.422     foxr     6017: 
1.75      albertel 6018: sub getSequenceDropDown {
1.582     raeburn  6019:     my ($symb,$map_error)=@_;
1.75      albertel 6020:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  6021:     my ($titles,$symbx) = &getSymbMap($map_error);
                   6022:     if (ref($map_error)) {
                   6023:         return if ($$map_error);
                   6024:     }
1.137     albertel 6025:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 6026:     my $ctr=0;
                   6027:     foreach (@$titles) {
                   6028: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   6029: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 6030: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 6031: 	    '>'.$showtitle.'</option>'."\n";
                   6032: 	$ctr++;
                   6033:     }
                   6034:     $result.= '</select>';
                   6035:     return $result;
                   6036: }
                   6037: 
1.495     albertel 6038: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  6039:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 6040: 
                   6041: my %first_bubble_line;             # First bubble line no. for each bubble.
                   6042: 
1.509     raeburn  6043: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   6044:                                    # matchresponse or rankresponse, where 
                   6045:                                    # an individual response can have multiple 
                   6046:                                    # lines
1.503     raeburn  6047: 
                   6048: my %responsetype_per_response;     # responsetype for each response
                   6049: 
1.596.2.12.2.  6(raebur 6050:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   6051:3):                                    # numbered response. Needed when randomorder
                   6052:3):                                    # or randompick are in use. Key is ID, value 
                   6053:3):                                    # is response number.
                   6054:3): 
1.495     albertel 6055: # Save and restore the bubble lines array to the form env.
                   6056: 
                   6057: 
                   6058: sub save_bubble_lines {
                   6059:     foreach my $line (keys(%bubble_lines_per_response)) {
                   6060: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   6061: 	$env{"form.scantron.first_bubble_line.$line"} =
                   6062: 	    $first_bubble_line{$line};
1.503     raeburn  6063:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   6064:             $subdivided_bubble_lines{$line};
                   6065:         $env{"form.scantron.responsetype.$line"} =
                   6066:             $responsetype_per_response{$line};
1.495     albertel 6067:     }
1.596.2.12.2.  6(raebur 6068:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   6069:3):         my $line = $masterseq_id_responsenum{$resid};
                   6070:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   6071:3):     }
1.495     albertel 6072: }
                   6073: 
                   6074: 
                   6075: sub restore_bubble_lines {
                   6076:     my $line = 0;
                   6077:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 6078:3):     %masterseq_id_responsenum = ();
1.495     albertel 6079:     while ($env{"form.scantron.bubblelines.$line"}) {
                   6080: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   6081: 	$bubble_lines_per_response{$line} = $value;
                   6082: 	$first_bubble_line{$line}  =
                   6083: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  6084:         $subdivided_bubble_lines{$line} =
                   6085:             $env{"form.scantron.sub_bubblelines.$line"};
                   6086:         $responsetype_per_response{$line} =
                   6087:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 6088:3):         my $id = $env{"form.scantron.residpart.$line"};
                   6089:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 6090: 	$line++;
                   6091:     }
                   6092: }
                   6093: 
1.423     albertel 6094: =pod 
                   6095: 
                   6096: =item scantron_filenames
                   6097: 
                   6098:    Returns a list of the scantron files in the current course 
                   6099: 
                   6100: =cut
1.422     foxr     6101: 
1.202     albertel 6102: sub scantron_filenames {
1.257     albertel 6103:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6104:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6105:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 6106:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6107:):                                                         $cname,$getpropath);
1.202     albertel 6108:     my @possiblenames;
1.596.2.12.2.  (raeburn 6109:):     if (ref($dirlist) eq 'ARRAY') {
                   6110:):         foreach my $filename (sort(@{$dirlist})) {
                   6111:): 	    ($filename)=split(/&/,$filename);
                   6112:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6113:): 	    $filename=~s/^scantron_orig_//;
                   6114:): 	    push(@possiblenames,$filename);
                   6115:):         }
1.202     albertel 6116:     }
                   6117:     return @possiblenames;
                   6118: }
                   6119: 
1.423     albertel 6120: =pod 
                   6121: 
                   6122: =item scantron_uploads
                   6123: 
                   6124:    Returns  html drop-down list of scantron files in current course.
                   6125: 
                   6126:  Arguments:
                   6127:    $file2grade - filename to set as selected in the dropdown
                   6128: 
                   6129: =cut
1.422     foxr     6130: 
1.202     albertel 6131: sub scantron_uploads {
1.209     ng       6132:     my ($file2grade) = @_;
1.202     albertel 6133:     my $result=	'<select name="scantron_selectfile">';
                   6134:     $result.="<option></option>";
                   6135:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6136: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6137:     }
                   6138:     $result.="</select>";
                   6139:     return $result;
                   6140: }
                   6141: 
1.423     albertel 6142: =pod 
                   6143: 
                   6144: =item scantron_scantab
                   6145: 
                   6146:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6147:   file.
                   6148: 
                   6149: =cut
1.422     foxr     6150: 
1.82      albertel 6151: sub scantron_scantab {
                   6152:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6153:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 6154:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6155:     if (@lines > 0) {
                   6156:         foreach my $line (@lines) {
                   6157:             next if (($line =~ /^\#/) || ($line eq ''));
                   6158: 	    my ($name,$descrip)=split(/:/,$line);
                   6159: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6160:         }
1.82      albertel 6161:     }
                   6162:     $result.='</select>'."\n";
1.518     raeburn  6163:     return $result;
                   6164: }
                   6165: 
1.423     albertel 6166: =pod 
                   6167: 
                   6168: =item scantron_CODElist
                   6169: 
                   6170:   Returns html drop down of the saved CODE lists from current course,
                   6171:   generated from earlier printings.
                   6172: 
                   6173: =cut
1.422     foxr     6174: 
1.186     albertel 6175: sub scantron_CODElist {
1.257     albertel 6176:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6177:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6178:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6179:     my $namechoice='<option></option>';
1.225     albertel 6180:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6181: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6182: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6183: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6184:     }
                   6185:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6186:     return $namechoice;
                   6187: }
                   6188: 
1.423     albertel 6189: =pod 
                   6190: 
                   6191: =item scantron_CODEunique
                   6192: 
                   6193:   Returns the html for "Each CODE to be used once" radio.
                   6194: 
                   6195: =cut
1.422     foxr     6196: 
1.186     albertel 6197: sub scantron_CODEunique {
1.532     bisitz   6198:     my $result='<span class="LC_nobreak">
1.272     albertel 6199:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6200:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6201:                 </span>
1.532     bisitz   6202:                 <span class="LC_nobreak">
1.272     albertel 6203:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6204:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6205:                 </span>';
1.186     albertel 6206:     return $result;
                   6207: }
1.423     albertel 6208: 
                   6209: =pod 
                   6210: 
                   6211: =item scantron_selectphase
                   6212: 
1.596.2.6  raeburn  6213:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6214:   Allows for - starting a grading run.
1.424     albertel 6215:              - downloading existing scan data (original, corrected
1.423     albertel 6216:                                                 or skipped info)
                   6217: 
                   6218:              - uploading new scan data
                   6219: 
                   6220:  Arguments:
                   6221:   $r          - The Apache request object
                   6222:   $file2grade - name of the file that contain the scanned data to score
                   6223: 
                   6224: =cut
1.186     albertel 6225: 
1.75      albertel 6226: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 6227:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6228:     if (!$symb) {return '';}
1.582     raeburn  6229:     my $map_error;
                   6230:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6231:     if ($map_error) {
                   6232:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6233:         return;
                   6234:     }
1.324     albertel 6235:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6236:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6237:     my $format_selector=&scantron_scantab();
1.186     albertel 6238:     my $CODE_selector=&scantron_CODElist();
                   6239:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6240:     my $result;
1.422     foxr     6241: 
1.513     foxr     6242:     $ssi_error = 0;
                   6243: 
1.596.2.4  raeburn  6244:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6245:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6246: 
                   6247:         # Chunk of form to prompt for a scantron file upload.
                   6248: 
                   6249:         $r->print('
1.596.2.12.2.  9(raebur 6250:9):     <br />');
                   6251:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6252:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6253:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6254:9):         &js_escape(\$alertmsg);
                   6255:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6256:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6257:     function checkUpload(formname) {
                   6258:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6259:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6260:             return false;
                   6261:         }
                   6262:         formname.submit();
1.596.2.12.2.  9(raebur 6263:9):     }'."\n".$formatjs));
                   6264:9):         $r->print('
1.596.2.4  raeburn  6265:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6266:                 '.$default_form_data.'
                   6267:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6268:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6269:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6270:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6271:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6272:9):                 <th>
                   6273:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6274:9):                 </th>
                   6275:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6276:9):               '.&Apache::loncommon::start_data_table_row().'
                   6277:9):             <td>
                   6278:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6279:9):         if ($formatoptions) {
                   6280:9):             $r->print('</td>
                   6281:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6282:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6283:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6284:9):                  </td>
                   6285:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6286:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6287:9):                  <td>'
                   6288:9):             );
                   6289:9):         } else {
                   6290:9):             $r->print(' <br />');
                   6291:9):         }
                   6292:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6293:9):               </td>
                   6294:9):              '.&Apache::loncommon::end_data_table_row().'
                   6295:9):              '.&Apache::loncommon::end_data_table().'
                   6296:9):              </form>'
                   6297:9):         );
1.596.2.4  raeburn  6298: 
                   6299:     }
                   6300: 
1.422     foxr     6301:     # Chunk of form to prompt for a file to grade and how:
                   6302: 
1.489     albertel 6303:     $result.= '
                   6304:     <br />
                   6305:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6306:     <input type="hidden" name="command" value="scantron_warning" />
                   6307:     '.$default_form_data.'
                   6308:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6309:        '.&Apache::loncommon::start_data_table_header_row().'
                   6310:             <th colspan="2">
1.492     albertel 6311:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6312:             </th>
                   6313:        '.&Apache::loncommon::end_data_table_header_row().'
                   6314:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6315:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6316:        '.&Apache::loncommon::end_data_table_row().'
                   6317:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6318:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6319:        '.&Apache::loncommon::end_data_table_row().'
                   6320:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6321:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6322:        '.&Apache::loncommon::end_data_table_row().'
                   6323:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6324:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6325:        '.&Apache::loncommon::end_data_table_row().'
                   6326:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6327:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6328:        '.&Apache::loncommon::end_data_table_row().'
                   6329:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6330: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6331:             <td>
1.492     albertel 6332: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6333:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6334:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6335: 	    </td>
1.489     albertel 6336:        '.&Apache::loncommon::end_data_table_row().'
                   6337:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6338:             <td colspan="2">
1.572     www      6339:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6340:             </td>
1.489     albertel 6341:        '.&Apache::loncommon::end_data_table_row().'
                   6342:     '.&Apache::loncommon::end_data_table().'
                   6343:     </form>
                   6344: ';
1.162     albertel 6345:    
                   6346:     $r->print($result);
                   6347: 
1.422     foxr     6348:     # Chunk of the form that prompts to view a scoring office file,
                   6349:     # corrected file, skipped records in a file.
                   6350: 
1.489     albertel 6351:     $r->print('
                   6352:    <br />
                   6353:    <form action="/adm/grades" name="scantron_download">
                   6354:      '.$default_form_data.'
                   6355:      <input type="hidden" name="command" value="scantron_download" />
                   6356:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6357:        '.&Apache::loncommon::start_data_table_header_row().'
                   6358:               <th>
1.492     albertel 6359:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6360:               </th>
                   6361:        '.&Apache::loncommon::end_data_table_header_row().'
                   6362:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6363:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6364:                 <br />
1.492     albertel 6365:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6366:        '.&Apache::loncommon::end_data_table_row().'
                   6367:      '.&Apache::loncommon::end_data_table().'
                   6368:    </form>
                   6369:    <br />
                   6370: ');
1.162     albertel 6371: 
1.457     banghart 6372:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6373: 
1.596.2.12.2.  8(raebur 6374:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6375:              $default_form_data."\n".
                   6376:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6377:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6378:              '<th colspan="2">
1.572     www      6379:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6380:              '</th>'."\n".
                   6381:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6382:               &Apache::loncommon::start_data_table_row()."\n".
                   6383:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6384:               '<td> '.$sequence_selector.' </td>'.
                   6385:               &Apache::loncommon::end_data_table_row()."\n".
                   6386:               &Apache::loncommon::start_data_table_row()."\n".
                   6387:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6388:               '<td> '.$file_selector.' </td>'."\n".
                   6389:               &Apache::loncommon::end_data_table_row()."\n".
                   6390:               &Apache::loncommon::start_data_table_row()."\n".
                   6391:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6392:               '<td> '.$format_selector.' </td>'."\n".
                   6393:               &Apache::loncommon::end_data_table_row()."\n".
                   6394:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6395:               '<td> '.&mt('Options').' </td>'."\n".
                   6396:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6397:               &Apache::loncommon::end_data_table_row()."\n".
                   6398:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6399:               '<td colspan="2">'."\n".
                   6400:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6401:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6402:               '</td>'."\n".
                   6403:               &Apache::loncommon::end_data_table_row()."\n".
                   6404:               &Apache::loncommon::end_data_table()."\n".
                   6405:               '</form><br />');
                   6406:     return;
1.75      albertel 6407: }
                   6408: 
1.423     albertel 6409: =pod 
                   6410: 
                   6411: =item username_to_idmap
                   6412: 
1.556     weissno  6413:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6414:     student username:domain.
                   6415: 
                   6416:   Arguments:
                   6417: 
                   6418:     $classlist - reference to the class list hash. This is a hash
                   6419:                  keyed by student name:domain  whose elements are references
1.424     albertel 6420:                  to arrays containing various chunks of information
1.423     albertel 6421:                  about the student. (See loncoursedata for more info).
                   6422: 
                   6423:   Returns
                   6424:     %idmap - the constructed hash
                   6425: 
                   6426: =cut
                   6427: 
1.82      albertel 6428: sub username_to_idmap {
                   6429:     my ($classlist)= @_;
                   6430:     my %idmap;
                   6431:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6432:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6433:5):         unless ($id eq '') {
                   6434:5):             if (!exists($idmap{$id})) {
                   6435:5):                 $idmap{$id} = $student;
                   6436:5):             } else {
                   6437:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6438:5):                 if ($status eq 'Active') {
                   6439:5):                     $idmap{$id} = $student;
                   6440:5):                 }
                   6441:5):             }
                   6442:5):         }
1.82      albertel 6443:     }
                   6444:     return %idmap;
                   6445: }
1.423     albertel 6446: 
                   6447: =pod
                   6448: 
1.424     albertel 6449: =item scantron_fixup_scanline
1.423     albertel 6450: 
                   6451:    Process a requested correction to a scanline.
                   6452: 
                   6453:   Arguments:
1.596.2.12.2.  9(raebur 6454:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6455:     $scan_data         - hash of correction information 
                   6456:                           (see &scantron_getfile())
                   6457:     $line              - existing scanline
                   6458:     $whichline         - line number of the passed in scanline
                   6459:     $field             - type of change to process 
                   6460:                          (either 
1.573     bisitz   6461:                           'ID'     -> correct the student/employee ID
1.423     albertel 6462:                           'CODE'   -> correct the CODE
                   6463:                           'answer' -> fixup the submitted answers)
                   6464:     
                   6465:    $args               - hash of additional info,
                   6466:                           - 'ID' 
                   6467:                                'newid' -> studentID to use in replacement
1.424     albertel 6468:                                           of existing one
1.423     albertel 6469:                           - 'CODE' 
                   6470:                                'CODE_ignore_dup' - set to true if duplicates
                   6471:                                                    should be ignored.
                   6472: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6473:                                         if the existing unfound code should
1.423     albertel 6474:                                         be used as is
                   6475:                           - 'answer'
                   6476:                                'response' - new answer or 'none' if blank
                   6477:                                'question' - the bubble line to change
1.503     raeburn  6478:                                'questionnum' - the question identifier,
                   6479:                                                may include subquestion. 
1.423     albertel 6480: 
                   6481:   Returns:
                   6482:     $line - the modified scanline
                   6483: 
                   6484:   Side effects: 
                   6485:     $scan_data - may be updated
                   6486: 
                   6487: =cut
                   6488: 
1.82      albertel 6489: 
1.157     albertel 6490: sub scantron_fixup_scanline {
                   6491:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6492:     if ($field eq 'ID') {
                   6493: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6494: 	    return ($line,1,'New value too large');
1.157     albertel 6495: 	}
                   6496: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6497: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6498: 				     $args->{'newid'});
                   6499: 	}
                   6500: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6501: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6502: 	if ($args->{'newid'}=~/^\s*$/) {
                   6503: 	    &scan_data($scan_data,"$whichline.user",
                   6504: 		       $args->{'username'}.':'.$args->{'domain'});
                   6505: 	}
1.186     albertel 6506:     } elsif ($field eq 'CODE') {
1.192     albertel 6507: 	if ($args->{'CODE_ignore_dup'}) {
                   6508: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6509: 	}
                   6510: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6511: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6512: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6513: 		return ($line,1,'New CODE value too large');
                   6514: 	    }
                   6515: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6516: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6517: 	    }
                   6518: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6519: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6520: 	}
1.157     albertel 6521:     } elsif ($field eq 'answer') {
1.497     foxr     6522: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6523: 	my $off=$scantron_config->{'Qoff'};
                   6524: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6525: 	my $answer=${off}x$length;
                   6526: 	if ($args->{'response'} eq 'none') {
                   6527: 	    &scan_data($scan_data,
1.503     raeburn  6528: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6529: 	} else {
                   6530: 	    if ($on eq 'letter') {
                   6531: 		my @alphabet=('A'..'Z');
                   6532: 		$answer=$alphabet[$args->{'response'}];
                   6533: 	    } elsif ($on eq 'number') {
                   6534: 		$answer=$args->{'response'}+1;
                   6535: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6536: 	    } else {
1.497     foxr     6537: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6538: 	    }
1.497     foxr     6539: 	    &scan_data($scan_data,
1.503     raeburn  6540: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6541: 	}
1.497     foxr     6542: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6543: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6544:     }
                   6545:     return $line;
                   6546: }
1.423     albertel 6547: 
                   6548: =pod
                   6549: 
                   6550: =item scan_data
                   6551: 
                   6552:     Edit or look up  an item in the scan_data hash.
                   6553: 
                   6554:   Arguments:
                   6555:     $scan_data  - The hash (see scantron_getfile)
                   6556:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6557:                   scantronfilename_key).
1.423     albertel 6558:     $data        - New value of the hash entry.
                   6559:     $delete      - If true, the entry is removed from the hash.
                   6560: 
                   6561:   Returns:
                   6562:     The new value of the hash table field (undefined if deleted).
                   6563: 
                   6564: =cut
                   6565: 
                   6566: 
1.157     albertel 6567: sub scan_data {
                   6568:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6569:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6570:     if (defined($value)) {
                   6571: 	$scan_data->{$filename.'_'.$key} = $value;
                   6572:     }
                   6573:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6574:     return $scan_data->{$filename.'_'.$key};
                   6575: }
1.423     albertel 6576: 
1.495     albertel 6577: # ----- These first few routines are general use routines.----
                   6578: 
                   6579: # Return the number of occurences of a pattern in a string.
                   6580: 
                   6581: sub occurence_count {
                   6582:     my ($string, $pattern) = @_;
                   6583: 
                   6584:     my @matches = ($string =~ /$pattern/g);
                   6585: 
                   6586:     return scalar(@matches);
                   6587: }
                   6588: 
                   6589: 
                   6590: # Take a string known to have digits and convert all the
                   6591: # digits into letters in the range J,A..I.
                   6592: 
                   6593: sub digits_to_letters {
                   6594:     my ($input) = @_;
                   6595: 
                   6596:     my @alphabet = ('J', 'A'..'I');
                   6597: 
                   6598:     my @input    = split(//, $input);
                   6599:     my $output ='';
                   6600:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6601: 	if ($input[$i] =~ /\d/) {
                   6602: 	    $output .= $alphabet[$input[$i]];
                   6603: 	} else {
                   6604: 	    $output .= $input[$i];
                   6605: 	}
                   6606:     }
                   6607:     return $output;
                   6608: }
                   6609: 
1.423     albertel 6610: =pod 
                   6611: 
                   6612: =item scantron_parse_scanline
                   6613: 
                   6614:   Decodes a scanline from the selected scantron file
                   6615: 
                   6616:  Arguments:
                   6617:     line             - The text of the scantron file line to process
                   6618:     whichline        - Line number
                   6619:     scantron_config  - Hash describing the format of the scantron lines.
                   6620:     scan_data        - Hash of extra information about the scanline
                   6621:                        (see scantron_getfile for more information)
                   6622:     just_header      - True if should not process question answers but only
                   6623:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6624:3):     randomorder      - True if randomorder in use
                   6625:3):     randompick       - True if randompick in use
                   6626:3):     sequence         - Exam folder URL
                   6627:3):     master_seq       - Ref to array containing symbs in exam folder
                   6628:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6629:3):                        (corresponding values are resource objects)
                   6630:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6631:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6632:3):                        are refs to an array of resource objects, ordered
                   6633:3):                        according to order used for CODE, when randomorder
                   6634:3):                        and or randompick are in use.
                   6635:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6636:3):                        for current line to question number used for same question
                   6637:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6638:3):     startline        - Ref to hash where key is question number (0 is first)
                   6639:3):                        and value is number of first bubble line for current 
                   6640:3):                        student or code-based randompick and/or randomorder.
                   6641:3):     totalref         - Ref of scalar used to score total number of bubble
                   6642:3):                        lines needed for responses in a scan line (used when
                   6643:3):                        randompick in use. 
                   6644:3): 
1.423     albertel 6645:  Returns:
                   6646:    Hash containing the result of parsing the scanline
                   6647: 
                   6648:    Keys are all proceeded by the string 'scantron.'
                   6649: 
                   6650:        CODE    - the CODE in use for this scanline
                   6651:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6652:                  by the operator
                   6653:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6654:                             CODEs were selected, but the usage has been
                   6655:                             forced by the operator
1.556     weissno  6656:        ID  - student/employee ID
1.423     albertel 6657:        PaperID - if used, the ID number printed on the sheet when the 
                   6658:                  paper was scanned
                   6659:        FirstName - first name from the sheet
                   6660:        LastName  - last name from the sheet
                   6661: 
                   6662:      if just_header was not true these key may also exist
                   6663: 
1.447     foxr     6664:        missingerror - a list of bubble ranges that are considered to be answers
                   6665:                       to a single question that don't have any bubbles filled in.
                   6666:                       Of the form questionnumber:firstbubblenumber:count.
                   6667:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6668:                       to a single question that have more than one bubble filled in.
                   6669:                       Of the form questionnumber::firstbubblenumber:count
                   6670:    
                   6671:                 In the above, count is the number of bubble responses in the
                   6672:                 input line needed to represent the possible answers to the question.
                   6673:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6674:                 per line would have count = 2.
                   6675: 
1.423     albertel 6676:        maxquest     - the number of the last bubble line that was parsed
                   6677: 
                   6678:        (<number> starts at 1)
                   6679:        <number>.answer - zero or more letters representing the selected
                   6680:                          letters from the scanline for the bubble line 
                   6681:                          <number>.
                   6682:                          if blank there was either no bubble or there where
                   6683:                          multiple bubbles, (consult the keys missingerror and
                   6684:                          doubleerror if this is an error condition)
                   6685: 
                   6686: =cut
                   6687: 
1.82      albertel 6688: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6689:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6690:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6691:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6692: 
1.82      albertel 6693:     my %record;
1.596.2.12.2.  6(raebur 6694:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6695:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6696: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6697: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6698: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6699: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6700: 	    $record{'scantron.CODE'}=substr($data,
                   6701: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6702: 					    $$scantron_config{'CODElength'});
1.191     albertel 6703: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6704: 		$record{'scantron.useCODE'}=1;
                   6705: 	    }
1.192     albertel 6706: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6707: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6708: 	    }
1.82      albertel 6709: 	} else {
                   6710: 	    #FIXME interpret first N questions
                   6711: 	}
                   6712:     }
1.83      albertel 6713:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6714: 				  $$scantron_config{'IDlength'});
1.157     albertel 6715:     $record{'scantron.PaperID'}=
                   6716: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6717: 	       $$scantron_config{'PaperIDlength'});
                   6718:     $record{'scantron.FirstName'}=
                   6719: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6720: 	       $$scantron_config{'FirstNamelength'});
                   6721:     $record{'scantron.LastName'}=
                   6722: 	substr($data,$$scantron_config{'LastName'}-1,
                   6723: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6724:     if ($just_header) { return \%record; }
1.194     albertel 6725: 
1.82      albertel 6726:     my @alphabet=('A'..'Z');
                   6727:     my $questnum=0;
1.447     foxr     6728:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6729: 
1.596.2.12.2.  6(raebur 6730:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6731:3):     if ($randompick || $randomorder) {
                   6732:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6733:3):                                          $master_seq,$symb_to_resource,
                   6734:3):                                          $partids_by_symb,$orderedforcode,
                   6735:3):                                          $respnumlookup,$startline);
                   6736:3):         if ($total) {
                   6737:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6738:3):         }
                   6739:3):         if (ref($totalref)) {
                   6740:3):             $$totalref = $total;
                   6741:3):         }
                   6742:3):     }
                   6743:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6744:     chomp($questions);		# Get rid of any trailing \n.
                   6745:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6746:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6747:3):         my $answers_needed;
                   6748:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6749:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6750:3):         } else {
                   6751:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6752:3):         }
1.503     raeburn  6753:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6754:                              || 1;
                   6755:         $questnum++;
                   6756:         my $quest_id = $questnum;
                   6757:         my $currentquest = substr($questions,0,$answer_length);
                   6758:         $questions       = substr($questions,$answer_length);
                   6759:         if (length($currentquest) < $answer_length) { next; }
                   6760: 
1.596.2.12.2.  6(raebur 6761:3):         my $subdivided;
                   6762:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6763:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6764:3):         } else {
                   6765:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6766:3):         }
                   6767:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6768:             my $subquestnum = 1;
                   6769:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6770:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6771:             foreach my $subans (@subanswers_needed) {
                   6772:                 my $subans_length =
                   6773:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6774:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6775:                 $subquestions   = substr($subquestions,$subans_length);
                   6776:                 $quest_id = "$questnum.$subquestnum";
                   6777:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6778:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6779:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6780:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6781:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6782:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6783:                 } else {
                   6784:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6785:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6786:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6787:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6788:                 }
                   6789:                 $subquestnum ++;
                   6790:             }
                   6791:         } else {
                   6792:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6793:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6794:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6795:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6796:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6797:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6798:             } else {
                   6799:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6800:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6801:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6802:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6803:             }
                   6804:         }
                   6805:     }
                   6806:     $record{'scantron.maxquest'}=$questnum;
                   6807:     return \%record;
                   6808: }
1.447     foxr     6809: 
1.596.2.12.2.  6(raebur 6810:3): sub get_master_seq {
          0(raebur 6811:2):     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
          6(raebur 6812:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6813:3):                    (ref($symb_to_resource) eq 'HASH'));
          0(raebur 6814:2):     if ($need_symb_in_map) {
                   6815:2):         return unless (ref($symb_for_examcode) eq 'HASH');
                   6816:2):     }
          6(raebur 6817:3):     my $resource_error;
                   6818:3):     foreach my $resource (@{$resources}) {
                   6819:3):         my $ressymb;
                   6820:3):         if (ref($resource)) {
                   6821:3):             $ressymb = $resource->symb();
                   6822:3):             push(@{$master_seq},$ressymb);
                   6823:3):             $symb_to_resource->{$ressymb} = $resource;
          0(raebur 6824:2):             if ($need_symb_in_map) {
                   6825:2):                 unless ($resource->is_map()) {
                   6826:2):                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6827:2):                     unless (exists($symb_for_examcode->{$map})) {
                   6828:2):                         $symb_for_examcode->{$map} = $ressymb;
                   6829:2):                     }
                   6830:2):                 }
                   6831:2):             }
          6(raebur 6832:3):         } else {
                   6833:3):             $resource_error = 1;
                   6834:3):             last;
                   6835:3):         }
                   6836:3):     }
                   6837:3):     return $resource_error;
                   6838:3): }
                   6839:3): 
                   6840:3): sub get_respnum_lookups {
                   6841:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6842:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6843:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6844:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6845:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6846:3):                    (ref($startline) eq 'HASH'));
                   6847:3):     my ($user,$scancode);
                   6848:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6849:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6850:3):         $scancode = $record->{'scantron.CODE'};
                   6851:3):     } else {
                   6852:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6853:3):     }
                   6854:3):     my @mapresources =
                   6855:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6856:3):                      $orderedforcode);
                   6857:3):     my $total = 0;
                   6858:3):     my $count = 0;
                   6859:3):     foreach my $resource (@mapresources) {
                   6860:3):         my $id = $resource->id();
                   6861:3):         my $symb = $resource->symb();
                   6862:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6863:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6864:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6865:3):                 if ($respnum ne '') {
                   6866:3):                     $respnumlookup->{$count} = $respnum;
                   6867:3):                     $startline->{$count} = $total;
                   6868:3):                     $total += $bubble_lines_per_response{$respnum};
                   6869:3):                     $count ++;
                   6870:3):                 }
                   6871:3):             }
                   6872:3):         }
                   6873:3):     }
                   6874:3):     return $total;
                   6875:3): }
                   6876:3): 
1.503     raeburn  6877: sub scantron_validator_lettnum {
                   6878:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6879:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6880:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6881: 
                   6882:     # Qon 'letter' implies for each slot in currquest we have:
                   6883:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6884:     #    about anything else (esp. a value of Qoff) for missing
                   6885:     #    bubbles.
                   6886:     #
                   6887:     # Qon 'number' implies each slot gives a digit that indexes the
                   6888:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6889:     #    and * or ? for double bubbles on a single line.
                   6890:     #
1.447     foxr     6891: 
1.503     raeburn  6892:     my $matchon;
                   6893:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6894:         $matchon = '[A-Z]';
                   6895:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6896:         $matchon = '\d';
                   6897:     }
                   6898:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6899:3):     my $responsenum = $questnum-1;
                   6900:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6901:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6902:3):     }
                   6903:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6904:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6905:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6906:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6907:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6908:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6909:         my @singlelines = split('',$currquest);
                   6910:         foreach my $entry (@singlelines) {
                   6911:             $occurrences = &occurence_count($entry,$matchon);
                   6912:             if ($occurrences > 1) {
                   6913:                 last;
                   6914:             }
1.596.2.12.2.  6(raebur 6915:3):         }
1.503     raeburn  6916:     } else {
                   6917:         $occurrences = &occurence_count($currquest,$matchon); 
                   6918:     }
                   6919:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6920:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6921:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6922:             my $bubble = substr($currquest,$ans,1);
                   6923:             if ($bubble =~ /$matchon/ ) {
                   6924:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6925:                     if ($bubble == 0) {
                   6926:                         $bubble = 10; 
                   6927:                     }
                   6928:                     $record->{"scantron.$ansnum.answer"} = 
                   6929:                         $alphabet->[$bubble-1];
                   6930:                 } else {
                   6931:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6932:                 }
                   6933:             } else {
                   6934:                 $record->{"scantron.$ansnum.answer"}='';
                   6935:             }
                   6936:             $ansnum++;
                   6937:         }
                   6938:     } elsif (!defined($currquest)
                   6939:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6940:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6941:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6942:             $record->{"scantron.$ansnum.answer"}='';
                   6943:             $ansnum++;
                   6944:         }
                   6945:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6946:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6947:         }
                   6948:     } else {
                   6949:         if ($$scantron_config{'Qon'} eq 'number') {
                   6950:             $currquest = &digits_to_letters($currquest);            
                   6951:         }
                   6952:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6953:             my $bubble = substr($currquest,$ans,1);
                   6954:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6955:             $ansnum++;
                   6956:         }
                   6957:     }
                   6958:     return $ansnum;
                   6959: }
1.447     foxr     6960: 
1.503     raeburn  6961: sub scantron_validator_positional {
                   6962:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6963:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6964:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6965: 
1.503     raeburn  6966:     # Otherwise there's a positional notation;
                   6967:     # each bubble line requires Qlength items, and there are filled in
                   6968:     # bubbles for each case where there 'Qon' characters.
                   6969:     #
1.447     foxr     6970: 
1.503     raeburn  6971:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6972: 
1.503     raeburn  6973:     # If the split only gives us one element.. the full length of the
                   6974:     # answer string, no bubbles are filled in:
1.447     foxr     6975: 
1.507     raeburn  6976:     if ($answers_needed eq '') {
                   6977:         return;
                   6978:     }
                   6979: 
1.503     raeburn  6980:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6981:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6982:             $record->{"scantron.$ansnum.answer"}='';
                   6983:             $ansnum++;
                   6984:         }
                   6985:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6986:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6987:         }
                   6988:     } elsif (scalar(@array) == 2) {
                   6989:         my $location = length($array[0]);
                   6990:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6991:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6992:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6993:             if ($ans eq $line_num) {
                   6994:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6995:             } else {
                   6996:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6997:             }
                   6998:             $ansnum++;
                   6999:          }
                   7000:     } else {
                   7001:         #  If there's more than one instance of a bubble character
                   7002:         #  That's a double bubble; with positional notation we can
                   7003:         #  record all the bubbles filled in as well as the
                   7004:         #  fact this response consists of multiple bubbles.
                   7005:         #
1.596.2.12.2.  6(raebur 7006:3):         my $responsenum = $questnum-1;
                   7007:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   7008:3):             $responsenum = $respnumlookup->{$questnum-1}
                   7009:3):         }
                   7010:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7011:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7012:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7013:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7014:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7015:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  7016:             my $doubleerror = 0;
                   7017:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   7018:                    (!$doubleerror)) {
                   7019:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   7020:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   7021:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   7022:                if (length(@currarray) > 2) {
                   7023:                    $doubleerror = 1;
                   7024:                } 
                   7025:             }
                   7026:             if ($doubleerror) {
                   7027:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7028:             }
                   7029:         } else {
                   7030:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   7031:         }
                   7032:         my $item = $ansnum;
                   7033:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   7034:             $record->{"scantron.$item.answer"} = '';
                   7035:             $item ++;
                   7036:         }
1.447     foxr     7037: 
1.503     raeburn  7038:         my @ans=@array;
                   7039:         my $i=0;
                   7040:         my $increment = 0;
                   7041:         while ($#ans) {
                   7042:             $i+=length($ans[0]) + $increment;
                   7043:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   7044:             my $bubble = $i%$$scantron_config{'Qlength'};
                   7045:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   7046:             shift(@ans);
                   7047:             $increment = 1;
                   7048:         }
                   7049:         $ansnum += $answers_needed;
1.82      albertel 7050:     }
1.503     raeburn  7051:     return $ansnum;
1.82      albertel 7052: }
                   7053: 
1.423     albertel 7054: =pod
                   7055: 
                   7056: =item scantron_add_delay
                   7057: 
                   7058:    Adds an error message that occurred during the grading phase to a
                   7059:    queue of messages to be shown after grading pass is complete
                   7060: 
                   7061:  Arguments:
1.424     albertel 7062:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 7063:    $scanline    - the scanline that caused the error
                   7064:    $errormesage - the error message
                   7065:    $errorcode   - a numeric code for the error
                   7066: 
                   7067:  Side Effects:
1.424     albertel 7068:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 7069: 
                   7070: =cut
                   7071: 
1.82      albertel 7072: sub scantron_add_delay {
1.140     albertel 7073:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   7074:     push(@$delayqueue,
                   7075: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   7076: 	  'ecode' => $errorcode }
                   7077: 	 );
1.82      albertel 7078: }
                   7079: 
1.423     albertel 7080: =pod
                   7081: 
                   7082: =item scantron_find_student
                   7083: 
1.424     albertel 7084:    Finds the username for the current scanline
                   7085: 
                   7086:   Arguments:
                   7087:    $scantron_record - hash result from scantron_parse_scanline
                   7088:    $scan_data       - hash of correction information 
                   7089:                       (see &scantron_getfile() form more information)
                   7090:    $idmap           - hash from &username_to_idmap()
                   7091:    $line            - number of current scanline
                   7092:  
                   7093:   Returns:
                   7094:    Either 'username:domain' or undef if unknown
                   7095: 
1.423     albertel 7096: =cut
                   7097: 
1.82      albertel 7098: sub scantron_find_student {
1.157     albertel 7099:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 7100:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7101:     if ($scanID =~ /^\s*$/) {
                   7102:  	return &scan_data($scan_data,"$line.user");
                   7103:     }
1.83      albertel 7104:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7105:  	if (lc($id) eq lc($scanID)) {
                   7106:  	    return $$idmap{$id};
                   7107:  	}
1.83      albertel 7108:     }
                   7109:     return undef;
                   7110: }
                   7111: 
1.423     albertel 7112: =pod
                   7113: 
                   7114: =item scantron_filter
                   7115: 
1.424     albertel 7116:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7117:    hidden resources was selected
                   7118: 
1.423     albertel 7119: =cut
                   7120: 
1.83      albertel 7121: sub scantron_filter {
                   7122:     my ($curres)=@_;
1.331     albertel 7123: 
                   7124:     if (ref($curres) && $curres->is_problem()) {
                   7125: 	# if the user has asked to not have either hidden
                   7126: 	# or 'randomout' controlled resources to be graded
                   7127: 	# don't include them
                   7128: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7129: 	    && $curres->randomout) {
                   7130: 	    return 0;
                   7131: 	}
1.83      albertel 7132: 	return 1;
                   7133:     }
                   7134:     return 0;
1.82      albertel 7135: }
                   7136: 
1.423     albertel 7137: =pod
                   7138: 
                   7139: =item scantron_process_corrections
                   7140: 
1.424     albertel 7141:    Gets correction information out of submitted form data and corrects
                   7142:    the scanline
                   7143: 
1.423     albertel 7144: =cut
                   7145: 
1.157     albertel 7146: sub scantron_process_corrections {
                   7147:     my ($r) = @_;
1.596.2.12.2.  9(raebur 7148:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7149:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7150:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7151:     my $which=$env{'form.scantron_line'};
1.200     albertel 7152:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7153:     my ($skip,$err,$errmsg);
1.257     albertel 7154:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7155: 	$skip=1;
1.257     albertel 7156:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7157: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7158: 	    $env{'form.scantron_domain'};
1.157     albertel 7159: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7160: 	($line,$err,$errmsg)=
                   7161: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7162: 				     'ID',{'newid'=>$newid,
1.257     albertel 7163: 				    'username'=>$env{'form.scantron_username'},
                   7164: 				    'domain'=>$env{'form.scantron_domain'}});
                   7165:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7166: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7167: 	my $newCODE;
1.192     albertel 7168: 	my %args;
1.190     albertel 7169: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7170: 	    $newCODE='use_unfound';
1.190     albertel 7171: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7172: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7173: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7174: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7175: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7176: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7177: 	}
1.257     albertel 7178: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7179: 	    $args{'CODE_ignore_dup'}=1;
                   7180: 	}
                   7181: 	$args{'CODE'}=$newCODE;
1.186     albertel 7182: 	($line,$err,$errmsg)=
                   7183: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7184: 				     'CODE',\%args);
1.257     albertel 7185:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7186: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7187: 	    ($line,$err,$errmsg)=
                   7188: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7189: 					 $which,'answer',
                   7190: 					 { 'question'=>$question,
1.503     raeburn  7191: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7192:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7193: 	    if ($err) { last; }
                   7194: 	}
                   7195:     }
                   7196:     if ($err) {
1.596.2.12.2.  0(raebur 7197:3): 	$r->print(
                   7198:3):             '<p class="LC_error">'
                   7199:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7200:3):                 $errmsg)
          1(raebur 7201:3):            .'</p>');
1.157     albertel 7202:     } else {
1.200     albertel 7203: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7204: 	&scantron_putfile($scanlines,$scan_data);
                   7205:     }
                   7206: }
                   7207: 
1.423     albertel 7208: =pod
                   7209: 
                   7210: =item reset_skipping_status
                   7211: 
1.424     albertel 7212:    Forgets the current set of remember skipped scanlines (and thus
                   7213:    reverts back to considering all lines in the
                   7214:    scantron_skipped_<filename> file)
                   7215: 
1.423     albertel 7216: =cut
                   7217: 
1.200     albertel 7218: sub reset_skipping_status {
                   7219:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7220:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7221:     &scantron_putfile(undef,$scan_data);
                   7222: }
                   7223: 
1.423     albertel 7224: =pod
                   7225: 
                   7226: =item start_skipping
                   7227: 
1.424     albertel 7228:    Marks a scanline to be skipped. 
                   7229: 
1.423     albertel 7230: =cut
                   7231: 
1.376     albertel 7232: sub start_skipping {
1.200     albertel 7233:     my ($scan_data,$i)=@_;
                   7234:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7235:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7236: 	$remembered{$i}=2;
                   7237:     } else {
                   7238: 	$remembered{$i}=1;
                   7239:     }
1.200     albertel 7240:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7241: }
                   7242: 
1.423     albertel 7243: =pod
                   7244: 
                   7245: =item should_be_skipped
                   7246: 
1.424     albertel 7247:    Checks whether a scanline should be skipped.
                   7248: 
1.423     albertel 7249: =cut
                   7250: 
1.200     albertel 7251: sub should_be_skipped {
1.376     albertel 7252:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7253:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7254: 	# not redoing old skips
1.376     albertel 7255: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7256: 	return 0;
                   7257:     }
                   7258:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7259: 
                   7260:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7261: 	return 0;
                   7262:     }
1.200     albertel 7263:     return 1;
                   7264: }
                   7265: 
1.423     albertel 7266: =pod
                   7267: 
                   7268: =item remember_current_skipped
                   7269: 
1.424     albertel 7270:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7271:    file and remembers them into scan_data for later use.
                   7272: 
1.423     albertel 7273: =cut
                   7274: 
1.200     albertel 7275: sub remember_current_skipped {
                   7276:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7277:     my %to_remember;
                   7278:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7279: 	if ($scanlines->{'skipped'}[$i]) {
                   7280: 	    $to_remember{$i}=1;
                   7281: 	}
                   7282:     }
1.376     albertel 7283: 
1.200     albertel 7284:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7285:     &scantron_putfile(undef,$scan_data);
                   7286: }
                   7287: 
1.423     albertel 7288: =pod
                   7289: 
                   7290: =item check_for_error
                   7291: 
1.424     albertel 7292:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7293:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7294:     something went wrong.
                   7295: 
1.423     albertel 7296: =cut
                   7297: 
1.200     albertel 7298: sub check_for_error {
                   7299:     my ($r,$result)=@_;
                   7300:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7301: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7302:     }
                   7303: }
1.157     albertel 7304: 
1.423     albertel 7305: =pod
                   7306: 
                   7307: =item scantron_warning_screen
                   7308: 
1.424     albertel 7309:    Interstitial screen to make sure the operator has selected the
                   7310:    correct options before we start the validation phase.
                   7311: 
1.423     albertel 7312: =cut
                   7313: 
1.203     albertel 7314: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7315:0):     my ($button_text,$symb)=@_;
1.257     albertel 7316:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7317:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7318:     my $CODElist;
1.284     albertel 7319:     if ($scantron_config{'CODElocation'} &&
                   7320: 	$scantron_config{'CODEstart'} &&
                   7321: 	$scantron_config{'CODElength'}) {
                   7322: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7323:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7324: 	$CODElist=
1.492     albertel 7325: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7326: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7327:     }
1.596.2.12.2.  (raeburn 7328:):     my $lastbubblepoints;
                   7329:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7330:):         $lastbubblepoints =
                   7331:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7332:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7333:):     }
1.492     albertel 7334:     return ('
1.203     albertel 7335: <p>
1.492     albertel 7336: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7337:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7338: </p>
                   7339: <table>
1.492     albertel 7340: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7341: <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 7342:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7343: </table>
1.596.2.12.2.  1(raebur 7344:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7345: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 7346: 
                   7347: <br />
1.492     albertel 7348: ');
1.203     albertel 7349: }
                   7350: 
1.423     albertel 7351: =pod
                   7352: 
                   7353: =item scantron_do_warning
                   7354: 
1.424     albertel 7355:    Check if the operator has picked something for all required
                   7356:    fields. Error out if something is missing.
                   7357: 
1.423     albertel 7358: =cut
                   7359: 
1.203     albertel 7360: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7361:0):     my ($r,$symb)=@_;
1.203     albertel 7362:     if (!$symb) {return '';}
1.324     albertel 7363:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7364:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7365:     if ( $env{'form.selectpage'} eq '' ||
                   7366: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7367: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7368: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7369: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7370: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7371: 	} 
1.257     albertel 7372: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7373: 	    $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 7374: 	} 
1.257     albertel 7375: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7376: 	    $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 7377: 	} 
                   7378:     } else {
1.596.2.12.2.  1(raebur 7379:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7380:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7381: 	$r->print('
1.596.2.12.2.  (raeburn 7382:): '.$warning.$bubbledbyhand.'
1.492     albertel 7383: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7384: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7385: ');
1.237     albertel 7386:     }
1.596.2.12.2.  1(raebur 7387:0):     $r->print("</form><br />");
1.203     albertel 7388:     return '';
                   7389: }
                   7390: 
1.423     albertel 7391: =pod
                   7392: 
                   7393: =item scantron_form_start
                   7394: 
1.424     albertel 7395:     html hidden input for remembering all selected grading options
                   7396: 
1.423     albertel 7397: =cut
                   7398: 
1.203     albertel 7399: sub scantron_form_start {
                   7400:     my ($max_bubble)=@_;
                   7401:     my $result= <<SCANTRONFORM;
                   7402: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7403:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7404:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7405:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7406:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7407:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7408:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7409:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7410:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7411:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7412: SCANTRONFORM
1.447     foxr     7413: 
                   7414:   my $line = 0;
                   7415:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7416:        my $chunk =
                   7417: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7418:        $chunk .=
                   7419: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7420:        $chunk .= 
                   7421:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7422:        $chunk .=
                   7423:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7424:3):        $chunk .=
                   7425:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7426:        $result .= $chunk;
                   7427:        $line++;
1.596.2.12.2.  6(raebur 7428:3):     }
1.203     albertel 7429:     return $result;
                   7430: }
                   7431: 
1.423     albertel 7432: =pod
                   7433: 
                   7434: =item scantron_validate_file
                   7435: 
1.596.2.6  raeburn  7436:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7437: 
                   7438:     Also processes any necessary information resets that need to
                   7439:     occur before validation begins (ignore previous corrections,
                   7440:     restarting the skipped records processing)
                   7441: 
1.423     albertel 7442: =cut
                   7443: 
1.157     albertel 7444: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7445:0):     my ($r,$symb) = @_;
1.157     albertel 7446:     if (!$symb) {return '';}
1.324     albertel 7447:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7448:     
1.596.2.12.2.  0(raebur 7449:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7450:     # them when doing the corrections reset
1.257     albertel 7451:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7452: 	&reset_skipping_status();
                   7453:     }
1.257     albertel 7454:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7455: 	&remember_current_skipped();
1.257     albertel 7456: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7457:     }
                   7458: 
1.257     albertel 7459:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7460: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7461: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7462: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7463: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7464:     }
1.200     albertel 7465: 
1.257     albertel 7466:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7467: 	&scantron_process_corrections($r);
                   7468:     }
1.503     raeburn  7469:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7470:     #get the student pick code ready
                   7471:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7472:     my $nav_error;
1.596.2.12.2.  9(raebur 7473:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7474:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7475:     if ($nav_error) {
                   7476:         $r->print(&navmap_errormsg());
                   7477:         return '';
                   7478:     }
1.203     albertel 7479:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7480:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7481:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7482:):     }
1.157     albertel 7483:     $r->print($result);
                   7484:     
1.334     albertel 7485:     my @validate_phases=( 'sequence',
                   7486: 			  'ID',
1.157     albertel 7487: 			  'CODE',
                   7488: 			  'doublebubble',
                   7489: 			  'missingbubbles');
1.257     albertel 7490:     if (!$env{'form.validatepass'}) {
                   7491: 	$env{'form.validatepass'} = 0;
1.157     albertel 7492:     }
1.257     albertel 7493:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7494: 
1.448     foxr     7495: 
1.157     albertel 7496:     my $stop=0;
                   7497:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7498: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7499: 	$r->rflush();
1.596.2.12.2.  6(raebur 7500:3): 
1.157     albertel 7501: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7502: 	{
                   7503: 	    no strict 'refs';
                   7504: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7505: 	}
                   7506:     }
                   7507:     if (!$stop) {
1.596.2.12.2.  1(raebur 7508:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7509: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7510:                   $warning.
                   7511:                   &mt('Perform verification for each student after storage of submissions?').
                   7512:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7513:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7514:                   ('&nbsp;'x3).'<label>'.
                   7515:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7516:                   '</label></span><br />'.
                   7517:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7518:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7519:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7520:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7521:     } else {
                   7522: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7523: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7524:     }
                   7525:     if ($stop) {
1.334     albertel 7526: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7527: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7528: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7529: 
1.596.2.12.2.  1(raebur 7530: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 7531: 	} else {
1.503     raeburn  7532:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7533: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7534:             } else {
1.539     riegler  7535:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7536:             }
1.492     albertel 7537: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7538: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7539: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7540: 	}
1.157     albertel 7541:     }
1.596.2.12.2.  1(raebur 7542:0):     $r->print(" </form><br />");
1.157     albertel 7543:     return '';
                   7544: }
                   7545: 
1.423     albertel 7546: 
                   7547: =pod
                   7548: 
                   7549: =item scantron_remove_file
                   7550: 
1.596.2.6  raeburn  7551:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7552:    scantron_original_<filename> is never removed
                   7553: 
                   7554: 
1.423     albertel 7555: =cut
                   7556: 
1.200     albertel 7557: sub scantron_remove_file {
1.192     albertel 7558:     my ($which)=@_;
1.257     albertel 7559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7561:     my $file='scantron_';
1.200     albertel 7562:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7563: 	$file.=$which.'_';
1.192     albertel 7564:     } else {
                   7565: 	return 'refused';
                   7566:     }
1.257     albertel 7567:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7568:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7569: }
                   7570: 
1.423     albertel 7571: 
                   7572: =pod
                   7573: 
                   7574: =item scantron_remove_scan_data
                   7575: 
1.596.2.6  raeburn  7576:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7577:    data file.  (In the case that both the are doing skipped records we need
                   7578:    to remember the old skipped lines for the time being so that element
                   7579:    persists for a while.)
                   7580: 
1.423     albertel 7581: =cut
                   7582: 
1.200     albertel 7583: sub scantron_remove_scan_data {
1.257     albertel 7584:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7585:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7586:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7587:     my @todelete;
1.257     albertel 7588:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7589:     foreach my $key (@keys) {
                   7590: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7591: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7592: 		$key=~/remember_skipping/) {
                   7593: 		next;
                   7594: 	    }
1.192     albertel 7595: 	    push(@todelete,$key);
                   7596: 	}
                   7597:     }
1.200     albertel 7598:     my $result;
1.192     albertel 7599:     if (@todelete) {
1.491     albertel 7600: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7601: 				       \@todelete,$cdom,$cname);
                   7602:     } else {
                   7603: 	$result = 'ok';
1.192     albertel 7604:     }
                   7605:     return $result;
                   7606: }
                   7607: 
1.423     albertel 7608: 
                   7609: =pod
                   7610: 
                   7611: =item scantron_getfile
                   7612: 
1.596.2.6  raeburn  7613:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7614:     the scan_data hash
                   7615:   
                   7616:   Arguments:
                   7617:     None
                   7618: 
                   7619:   Returns:
                   7620:     2 hash references
                   7621: 
                   7622:      - first one has 
                   7623:          orig      -
                   7624:          corrected -
                   7625:          skipped   -  each of which points to an array ref of the specified
                   7626:                       file broken up into individual lines
                   7627:          count     - number of scanlines
                   7628:  
                   7629:      - second is the scan_data hash possible keys are
1.425     albertel 7630:        ($number refers to scanline numbered $number and thus the key affects
                   7631:         only that scanline
                   7632:         $bubline refers to the specific bubble line element and the aspects
                   7633:         refers to that specific bubble line element)
                   7634: 
                   7635:        $number.user - username:domain to use
                   7636:        $number.CODE_ignore_dup 
                   7637:                     - ignore the duplicate CODE error 
                   7638:        $number.useCODE
                   7639:                     - use the CODE in the scanline as is
                   7640:        $number.no_bubble.$bubline
                   7641:                     - it is valid that there is no bubbled in bubble
                   7642:                       at $number $bubline
                   7643:        remember_skipping
                   7644:                     - a frozen hash containing keys of $number and values
                   7645:                       of either 
                   7646:                         1 - we are on a 'do skipped records pass' and plan
                   7647:                             on processing this line
                   7648:                         2 - we are on a 'do skipped records pass' and this
                   7649:                             scanline has been marked to skip yet again
1.424     albertel 7650: 
1.423     albertel 7651: =cut
                   7652: 
1.157     albertel 7653: sub scantron_getfile {
1.200     albertel 7654:     #FIXME really would prefer a scantron directory
1.257     albertel 7655:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7656:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7657:     my $lines;
                   7658:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7659: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7660:     my %scanlines;
                   7661:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7662:     my $temp=$scanlines{'orig'};
                   7663:     $scanlines{'count'}=$#$temp;
                   7664: 
                   7665:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7666: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7667:     if ($lines eq '-1') {
                   7668: 	$scanlines{'corrected'}=[];
                   7669:     } else {
                   7670: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7671:     }
                   7672:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7673: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7674:     if ($lines eq '-1') {
                   7675: 	$scanlines{'skipped'}=[];
                   7676:     } else {
                   7677: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7678:     }
1.175     albertel 7679:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7680:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7681:     my %scan_data = @tmp;
                   7682:     return (\%scanlines,\%scan_data);
                   7683: }
                   7684: 
1.423     albertel 7685: =pod
                   7686: 
                   7687: =item lonnet_putfile
                   7688: 
1.424     albertel 7689:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7690: 
                   7691:  Arguments:
                   7692:    $contents - data to store
                   7693:    $filename - filename to store $contents into
                   7694: 
                   7695:  Returns:
                   7696:    result value from &Apache::lonnet::finishuserfileupload
                   7697: 
1.423     albertel 7698: =cut
                   7699: 
1.157     albertel 7700: sub lonnet_putfile {
                   7701:     my ($contents,$filename)=@_;
1.257     albertel 7702:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7703:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7704:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7705:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7706: 
                   7707: }
                   7708: 
1.423     albertel 7709: =pod
                   7710: 
                   7711: =item scantron_putfile
                   7712: 
1.596.2.6  raeburn  7713:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7714:     scan_data hash. (Does not modify the original version only the
                   7715:     corrected and skipped versions.
                   7716: 
                   7717:  Arguments:
                   7718:     $scanlines - hash ref that looks like the first return value from
                   7719:                  &scantron_getfile()
                   7720:     $scan_data - hash ref that looks like the second return value from
                   7721:                  &scantron_getfile()
                   7722: 
1.423     albertel 7723: =cut
                   7724: 
1.157     albertel 7725: sub scantron_putfile {
                   7726:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7727:     #FIXME really would prefer a scantron directory
1.257     albertel 7728:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7729:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7730:     if ($scanlines) {
                   7731: 	my $prefix='scantron_';
1.157     albertel 7732: # no need to update orig, shouldn't change
                   7733: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7734: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7735: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7736: 			$prefix.'corrected_'.
1.257     albertel 7737: 			$env{'form.scantron_selectfile'});
1.200     albertel 7738: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7739: 			$prefix.'skipped_'.
1.257     albertel 7740: 			$env{'form.scantron_selectfile'});
1.200     albertel 7741:     }
1.175     albertel 7742:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7743: }
                   7744: 
1.423     albertel 7745: =pod
                   7746: 
                   7747: =item scantron_get_line
                   7748: 
1.424     albertel 7749:    Returns the correct version of the scanline
                   7750: 
                   7751:  Arguments:
                   7752:     $scanlines - hash ref that looks like the first return value from
                   7753:                  &scantron_getfile()
                   7754:     $scan_data - hash ref that looks like the second return value from
                   7755:                  &scantron_getfile()
                   7756:     $i         - number of the requested line (starts at 0)
                   7757: 
                   7758:  Returns:
                   7759:    A scanline, (either the original or the corrected one if it
                   7760:    exists), or undef if the requested scanline should be
                   7761:    skipped. (Either because it's an skipped scanline, or it's an
                   7762:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7763:    pass.
                   7764: 
1.423     albertel 7765: =cut
                   7766: 
1.157     albertel 7767: sub scantron_get_line {
1.200     albertel 7768:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7769:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7770:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7771:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7772:     return $scanlines->{'orig'}[$i]; 
                   7773: }
                   7774: 
1.423     albertel 7775: =pod
                   7776: 
                   7777: =item scantron_todo_count
                   7778: 
1.424     albertel 7779:     Counts the number of scanlines that need processing.
                   7780: 
                   7781:  Arguments:
                   7782:     $scanlines - hash ref that looks like the first return value from
                   7783:                  &scantron_getfile()
                   7784:     $scan_data - hash ref that looks like the second return value from
                   7785:                  &scantron_getfile()
                   7786: 
                   7787:  Returns:
                   7788:     $count - number of scanlines to process
                   7789: 
1.423     albertel 7790: =cut
                   7791: 
1.200     albertel 7792: sub get_todo_count {
                   7793:     my ($scanlines,$scan_data)=@_;
                   7794:     my $count=0;
                   7795:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7796: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7797: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7798: 	$count++;
                   7799:     }
                   7800:     return $count;
                   7801: }
                   7802: 
1.423     albertel 7803: =pod
                   7804: 
                   7805: =item scantron_put_line
                   7806: 
1.596.2.6  raeburn  7807:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7808:     data file.
                   7809: 
                   7810:  Arguments:
                   7811:     $scanlines - hash ref that looks like the first return value from
                   7812:                  &scantron_getfile()
                   7813:     $scan_data - hash ref that looks like the second return value from
                   7814:                  &scantron_getfile()
                   7815:     $i         - line number to update
                   7816:     $newline   - contents of the updated scanline
                   7817:     $skip      - if true make the line for skipping and update the
                   7818:                  'skipped' file
                   7819: 
1.423     albertel 7820: =cut
                   7821: 
1.157     albertel 7822: sub scantron_put_line {
1.200     albertel 7823:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7824:     if ($skip) {
                   7825: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7826: 	&start_skipping($scan_data,$i);
1.157     albertel 7827: 	return;
                   7828:     }
                   7829:     $scanlines->{'corrected'}[$i]=$newline;
                   7830: }
                   7831: 
1.423     albertel 7832: =pod
                   7833: 
                   7834: =item scantron_clear_skip
                   7835: 
1.424     albertel 7836:    Remove a line from the 'skipped' file
                   7837: 
                   7838:  Arguments:
                   7839:     $scanlines - hash ref that looks like the first return value from
                   7840:                  &scantron_getfile()
                   7841:     $scan_data - hash ref that looks like the second return value from
                   7842:                  &scantron_getfile()
                   7843:     $i         - line number to update
                   7844: 
1.423     albertel 7845: =cut
                   7846: 
1.376     albertel 7847: sub scantron_clear_skip {
                   7848:     my ($scanlines,$scan_data,$i)=@_;
                   7849:     if (exists($scanlines->{'skipped'}[$i])) {
                   7850: 	undef($scanlines->{'skipped'}[$i]);
                   7851: 	return 1;
                   7852:     }
                   7853:     return 0;
                   7854: }
                   7855: 
1.423     albertel 7856: =pod
                   7857: 
                   7858: =item scantron_filter_not_exam
                   7859: 
1.424     albertel 7860:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7861:    filter out resources that are not marked as 'exam' mode
                   7862: 
1.423     albertel 7863: =cut
                   7864: 
1.334     albertel 7865: sub scantron_filter_not_exam {
                   7866:     my ($curres)=@_;
                   7867:     
                   7868:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7869: 	# if the user has asked to not have either hidden
                   7870: 	# or 'randomout' controlled resources to be graded
                   7871: 	# don't include them
                   7872: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7873: 	    && $curres->randomout) {
                   7874: 	    return 0;
                   7875: 	}
                   7876: 	return 1;
                   7877:     }
                   7878:     return 0;
                   7879: }
                   7880: 
1.423     albertel 7881: =pod
                   7882: 
                   7883: =item scantron_validate_sequence
                   7884: 
1.424     albertel 7885:     Validates the selected sequence, checking for resource that are
                   7886:     not set to exam mode.
                   7887: 
1.423     albertel 7888: =cut
                   7889: 
1.334     albertel 7890: sub scantron_validate_sequence {
                   7891:     my ($r,$currentphase) = @_;
                   7892: 
                   7893:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7894:     unless (ref($navmap)) {
                   7895:         $r->print(&navmap_errormsg());
                   7896:         return (1,$currentphase);
                   7897:     }
1.334     albertel 7898:     my (undef,undef,$sequence)=
                   7899: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7900: 
                   7901:     my $map=$navmap->getResourceByUrl($sequence);
                   7902: 
                   7903:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7904:                                     value="ignore" />');
                   7905:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7906: 	my @resources=
                   7907: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7908: 	if (@resources) {
1.596.2.12.2.  0(raebur 7909:2): 	    $r->print('<p class="LC_warning">'
                   7910:2):                .&mt('Some resources in the sequence currently are not set to'
                   7911:2):                    .' exam mode. Grading these resources currently may not'
                   7912:2):                    .' work correctly.')
                   7913:2):                .'</p>'
                   7914:2):             );
1.334     albertel 7915: 	    return (1,$currentphase);
                   7916: 	}
                   7917:     }
                   7918: 
                   7919:     return (0,$currentphase+1);
                   7920: }
                   7921: 
1.423     albertel 7922: 
                   7923: 
1.157     albertel 7924: sub scantron_validate_ID {
                   7925:     my ($r,$currentphase) = @_;
                   7926:     
                   7927:     #get student info
                   7928:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7929:     my %idmap=&username_to_idmap($classlist);
                   7930: 
                   7931:     #get scantron line setup
1.596.2.12.2.  9(raebur 7932:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7933:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7934: 
                   7935:     my $nav_error;
1.596.2.12.2.  (raeburn 7936:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7937:     if ($nav_error) {
                   7938:         $r->print(&navmap_errormsg());
                   7939:         return(1,$currentphase);
                   7940:     }
1.157     albertel 7941: 
                   7942:     my %found=('ids'=>{},'usernames'=>{});
                   7943:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7944: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7945: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7946: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7947: 						 $scan_data);
                   7948: 	my $id=$$scan_record{'scantron.ID'};
                   7949: 	my $found;
                   7950: 	foreach my $checkid (keys(%idmap)) {
                   7951: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7952: 	}
                   7953: 	if ($found) {
                   7954: 	    my $username=$idmap{$found};
                   7955: 	    if ($found{'ids'}{$found}) {
                   7956: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7957: 					 $line,'duplicateID',$found);
1.194     albertel 7958: 		return(1,$currentphase);
1.157     albertel 7959: 	    } elsif ($found{'usernames'}{$username}) {
                   7960: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7961: 					 $line,'duplicateID',$username);
1.194     albertel 7962: 		return(1,$currentphase);
1.157     albertel 7963: 	    }
1.186     albertel 7964: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7965: 	    $found{'ids'}{$found}++;
                   7966: 	    $found{'usernames'}{$username}++;
                   7967: 	} else {
                   7968: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7969: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7970: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7971: 		    &scantron_get_correction($r,$i,$scan_record,
                   7972: 					     \%scantron_config,
                   7973: 					     $line,'duplicateID',$username);
1.194     albertel 7974: 		    return(1,$currentphase);
1.157     albertel 7975: 		} elsif (!defined($username)) {
                   7976: 		    &scantron_get_correction($r,$i,$scan_record,
                   7977: 					     \%scantron_config,
                   7978: 					     $line,'incorrectID');
1.194     albertel 7979: 		    return(1,$currentphase);
1.157     albertel 7980: 		}
                   7981: 		$found{'usernames'}{$username}++;
                   7982: 	    } else {
                   7983: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7984: 					 $line,'incorrectID');
1.194     albertel 7985: 		return(1,$currentphase);
1.157     albertel 7986: 	    }
                   7987: 	}
                   7988:     }
                   7989: 
                   7990:     return (0,$currentphase+1);
                   7991: }
                   7992: 
1.423     albertel 7993: 
1.157     albertel 7994: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7995:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7996:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7997: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7998: #to show both the current line and the previous one and allow skipping
                   7999: #the previous one or the current one
                   8000: 
1.333     albertel 8001:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  8002:         $r->print(
                   8003:             '<p class="LC_warning">'
                   8004:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   8005:                 "<b>$error</b>",
                   8006:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   8007:            ."</p> \n");
1.157     albertel 8008:     } else {
1.596.2.6  raeburn  8009:         $r->print(
                   8010:             '<p class="LC_warning">'
                   8011:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8012:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8013:            ."</p> \n");
                   8014:     }
                   8015:     my $message =
                   8016:         '<p>'
                   8017:        .&mt('The ID on the form is [_1]',
                   8018:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8019:        .'<br />'
1.596.2.12  raeburn  8020:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  8021:             $$scan_record{'scantron.LastName'},
                   8022:             $$scan_record{'scantron.FirstName'})
                   8023:        .'</p>';
1.242     albertel 8024: 
1.157     albertel 8025:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8026:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8027:                            # Array populated for doublebubble or
                   8028:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8029:                            # to validate radio button checking   
                   8030: 
1.157     albertel 8031:     if ($error =~ /ID$/) {
1.186     albertel 8032: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  8033: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8034: 		      "</p>\n");
1.157     albertel 8035: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  8036: 	    $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 8037: 	}
1.242     albertel 8038: 	$r->print($message);
1.492     albertel 8039: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8040: 	$r->print("\n<ul><li> ");
                   8041: 	#FIXME it would be nice if this sent back the user ID and
                   8042: 	#could do partial userID matches
                   8043: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8044: 				       'scantron_username','scantron_domain'));
                   8045: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 8046:3): 	$r->print("\n:\n".
1.257     albertel 8047: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8048: 
                   8049: 	$r->print('</li>');
1.186     albertel 8050:     } elsif ($error =~ /CODE$/) {
                   8051: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  8052: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8053: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  8054: 	    $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 8055: 	}
1.596.2.6  raeburn  8056:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   8057:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8058:                  ."</p>\n");
1.242     albertel 8059: 	$r->print($message);
1.596.2.6  raeburn  8060: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8061: 	$r->print("\n<br /> ");
1.194     albertel 8062: 	my $i=0;
1.273     albertel 8063: 	if ($error eq 'incorrectCODE' 
                   8064: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8065: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8066: 	    if ($closest > 0) {
                   8067: 		foreach my $testcode (@{$closest}) {
                   8068: 		    my $checked='';
1.569     bisitz   8069: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8070: 		    $r->print("
                   8071:    <label>
1.569     bisitz   8072:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8073:        ".&mt("Use the similar CODE [_1] instead.",
                   8074: 	    "<b><tt>".$testcode."</tt></b>")."
                   8075:     </label>
                   8076:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8077: 		    $r->print("\n<br />");
                   8078: 		    $i++;
                   8079: 		}
1.194     albertel 8080: 	    }
                   8081: 	}
1.273     albertel 8082: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8083: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8084: 	    $r->print("
                   8085:     <label>
1.569     bisitz   8086:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  8087:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8088: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8089:     </label>");
1.273     albertel 8090: 	    $r->print("\n<br />");
                   8091: 	}
1.194     albertel 8092: 
1.596.2.12.2.  1(raebur 8093:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8094: function change_radio(field) {
1.190     albertel 8095:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8096:     var i;
                   8097:     for (i=0;i<slct.length;i++) {
                   8098:         if (slct[i].value==field) { slct[i].checked=true; }
                   8099:     }
                   8100: }
                   8101: ENDSCRIPT
1.187     albertel 8102: 	my $href="/adm/pickcode?".
1.359     www      8103: 	   "form=".&escape("scantronupload").
                   8104: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8105: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8106: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8107: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8108: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8109: 	    $r->print("
                   8110:     <label>
                   8111:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8112:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8113: 	     "<a target='_blank' href='$href'>","</a>")."
                   8114:     </label> 
1.558     bisitz   8115:     ".&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 8116: 	    $r->print("\n<br />");
                   8117: 	}
1.492     albertel 8118: 	$r->print("
                   8119:     <label>
                   8120:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8121:        ".&mt("Use [_1] as the CODE.",
                   8122: 	     "</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 8123: 	$r->print("\n<br /><br />");
1.157     albertel 8124:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  8125: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8126: 
                   8127: 	# The form field scantron_questions is acutally a list of line numbers.
                   8128: 	# represented by this form so:
                   8129: 
1.596.2.12.2.  6(raebur 8130:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8131:3):                                                 $respnumlookup,$startline);
1.497     foxr     8132: 
1.157     albertel 8133: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8134: 		  $line_list.'" />');
1.242     albertel 8135: 	$r->print($message);
1.492     albertel 8136: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8137: 	foreach my $question (@{$arg}) {
1.503     raeburn  8138: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8139:3):                                                    $scan_record, $error,
                   8140:3):                                                    $randomorder,$randompick,
                   8141:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8142:             push(@lines_to_correct,@linenums);
1.157     albertel 8143: 	}
1.503     raeburn  8144:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8145:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  8146: 	$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 8147: 	$r->print($message);
1.492     albertel 8148: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8149: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8150: 
1.503     raeburn  8151: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8152: 	# a list of question numbers. Therefore:
                   8153: 	#
                   8154: 	
1.596.2.12.2.  6(raebur 8155:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8156:3):                                                 $respnumlookup,$startline);
1.497     foxr     8157: 
1.157     albertel 8158: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8159: 		  $line_list.'" />');
1.157     albertel 8160: 	foreach my $question (@{$arg}) {
1.503     raeburn  8161: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8162:3):                                                    $scan_record, $error,
                   8163:3):                                                    $randomorder,$randompick,
                   8164:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8165:             push(@lines_to_correct,@linenums);
1.157     albertel 8166: 	}
1.503     raeburn  8167:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8168:     } else {
                   8169: 	$r->print("\n<ul>");
                   8170:     }
                   8171:     $r->print("\n</li></ul>");
1.497     foxr     8172: }
                   8173: 
1.503     raeburn  8174: sub verify_bubbles_checked {
                   8175:     my (@ansnums) = @_;
                   8176:     my $ansnumstr = join('","',@ansnums);
                   8177:     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 8178:6):     &js_escape(\$warning);
          1(raebur 8179:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8180: function verify_bubble_radio(form) {
                   8181:     var ansnumArray = new Array ("$ansnumstr");
                   8182:     var need_bubble_count = 0;
                   8183:     for (var i=0; i<ansnumArray.length; i++) {
                   8184:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8185:             var bubble_picked = 0; 
                   8186:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8187:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8188:                     bubble_picked = 1;
                   8189:                 }
                   8190:             }
                   8191:             if (bubble_picked == 0) {
                   8192:                 need_bubble_count ++;
                   8193:             }
                   8194:         }
                   8195:     }
                   8196:     if (need_bubble_count) {
                   8197:         alert("$warning");
                   8198:         return;
                   8199:     }
                   8200:     form.submit(); 
                   8201: }
                   8202: ENDSCRIPT
                   8203:     return $output;
                   8204: }
                   8205: 
1.497     foxr     8206: =pod
                   8207: 
                   8208: =item  questions_to_line_list
1.157     albertel 8209: 
1.497     foxr     8210: Converts a list of questions into a string of comma separated
                   8211: line numbers in the answer sheet used by the questions.  This is
                   8212: used to fill in the scantron_questions form field.
                   8213: 
                   8214:   Arguments:
                   8215:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 8216:3):      randomorder  - True if randomorder in use.
                   8217:3):      randompick   - True if randompick in use.
                   8218:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8219:3):                      for current line to question number used for same question
                   8220:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   8221:3):      startline    - Reference to hash where key is question number (0 is first)
                   8222:3):                     and key is number of first bubble line for current student
                   8223:3):                     or code-based randompick and/or randomorder.
1.497     foxr     8224: 
                   8225: =cut
                   8226: 
                   8227: 
                   8228: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 8229:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8230:     my @lines;
                   8231: 
1.503     raeburn  8232:     foreach my $item (@{$questions}) {
                   8233:         my $question = $item;
                   8234:         my ($first,$count,$last);
                   8235:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8236:             $question = $1;
                   8237:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 8238:3):             my $responsenum = $question-1;
                   8239:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8240:3):                 $responsenum = $respnumlookup->{$question-1};
                   8241:3):                 if (ref($startline) eq 'HASH') {
                   8242:3):                     $first = $startline->{$question-1} + 1;
                   8243:3):                 }
                   8244:3):             } else {
                   8245:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8246:3):             }
          7(raebur 8247:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8248:             my $subcount = 1;
                   8249:             while ($subcount<$subquestion) {
                   8250:                 $first += $subans[$subcount-1];
                   8251:                 $subcount ++;
                   8252:             }
                   8253:             $count = $subans[$subquestion-1];
                   8254:         } else {
1.596.2.12.2.  7(raebur 8255:3):             my $responsenum = $question-1;
                   8256:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8257:3):                 $responsenum = $respnumlookup->{$question-1};
                   8258:3):                 if (ref($startline) eq 'HASH') {
                   8259:3):                     $first = $startline->{$question-1} + 1;
                   8260:3):                 }
                   8261:3):             } else {
                   8262:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8263:3):             }
                   8264:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8265:         }
1.506     raeburn  8266:         $last = $first+$count-1;
1.503     raeburn  8267:         push(@lines, ($first..$last));
1.497     foxr     8268:     }
                   8269:     return join(',', @lines);
                   8270: }
                   8271: 
                   8272: =pod 
                   8273: 
                   8274: =item prompt_for_corrections
                   8275: 
                   8276: Prompts for a potentially multiline correction to the
                   8277: user's bubbling (factors out common code from scantron_get_correction
                   8278: for multi and missing bubble cases).
                   8279: 
                   8280:  Arguments:
                   8281:    $r           - Apache request object.
                   8282:    $question    - The question number to prompt for.
                   8283:    $scan_config - The scantron file configuration hash.
                   8284:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8285:    $error       - Type of error
1.596.2.12.2.  7(raebur 8286:3):    $randomorder - True if randomorder in use.
                   8287:3):    $randompick  - True if randompick in use.
                   8288:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8289:3):                     for current line to question number used for same question
                   8290:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8291:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8292:3):                   and value is number of first bubble line for current student
                   8293:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8294: 
                   8295:  Implicit inputs:
                   8296:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8297:                                   Numbered from 0 (but question numbers are from
                   8298:                                   1.
                   8299:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8300:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8301:                                   type problems render as separate sub-questions, 
1.503     raeburn  8302:                                   in exam mode. This hash contains a 
                   8303:                                   comma-separated list of the lines per 
                   8304:                                   sub-question.
1.510     raeburn  8305:    %responsetype_per_response   - essayresponse, formularesponse,
                   8306:                                   stringresponse, imageresponse, reactionresponse,
                   8307:                                   and organicresponse type problem parts can have
1.503     raeburn  8308:                                   multiple lines per response if the weight
                   8309:                                   assigned exceeds 10.  In this case, only
                   8310:                                   one bubble per line is permitted, but more 
                   8311:                                   than one line might contain bubbles, e.g.
                   8312:                                   bubbling of: line 1 - J, line 2 - J, 
                   8313:                                   line 3 - B would assign 22 points.  
1.497     foxr     8314: 
                   8315: =cut
                   8316: 
                   8317: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8318:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8319:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8320:     my ($current_line,$lines);
                   8321:     my @linenums;
                   8322:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8323:3):     my ($first,$responsenum);
1.503     raeburn  8324:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8325:         $question = $1;
                   8326:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8327:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8328:3):             $responsenum = $respnumlookup->{$question-1};
                   8329:3):             if (ref($startline) eq 'HASH') {
                   8330:3):                 $first = $startline->{$question-1};
                   8331:3):             }
                   8332:3):         } else {
                   8333:3):             $responsenum = $question-1;
          7(raebur 8334:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8335:3):         }
                   8336:3):         $current_line = $first + 1 ;
                   8337:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8338:         my $subcount = 1;
                   8339:         while ($subcount<$subquestion) {
                   8340:             $current_line += $subans[$subcount-1];
                   8341:             $subcount ++;
                   8342:         }
                   8343:         $lines = $subans[$subquestion-1];
                   8344:     } else {
1.596.2.12.2.  6(raebur 8345:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8346:3):             $responsenum = $respnumlookup->{$question-1};
                   8347:3):             if (ref($startline) eq 'HASH') {
                   8348:3):                 $first = $startline->{$question-1};
                   8349:3):             }
                   8350:3):         } else {
                   8351:3):             $responsenum = $question-1;
                   8352:3):             $first = $first_bubble_line{$responsenum};
                   8353:3):         }
                   8354:3):         $current_line = $first + 1;
                   8355:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8356:     }
1.497     foxr     8357:     if ($lines > 1) {
1.503     raeburn  8358:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8359:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8360:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8361:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8362:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8363:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8364:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8365: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  8366:         } else {
                   8367:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8368:         }
1.497     foxr     8369:     }
                   8370:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8371:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8372:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8373: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8374:         push(@linenums,$current_line);
1.497     foxr     8375: 	$current_line++;
                   8376:     }
                   8377:     if ($lines > 1) {
                   8378: 	$r->print("<hr /><br />");
                   8379:     }
1.503     raeburn  8380:     return @linenums;
1.157     albertel 8381: }
1.423     albertel 8382: 
                   8383: =pod
                   8384: 
                   8385: =item scantron_bubble_selector
                   8386:   
                   8387:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8388:    possibly showing the existing the selected bubbles if known
1.423     albertel 8389: 
                   8390:  Arguments:
                   8391:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8392:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8393:     $line        - Number of the line being displayed.
1.503     raeburn  8394:     $questionnum - Question number (may include subquestion)
                   8395:     $error       - Type of error.
1.497     foxr     8396:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8397: 
                   8398: =cut
                   8399: 
1.157     albertel 8400: sub scantron_bubble_selector {
1.503     raeburn  8401:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8402:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8403: 
                   8404:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8405:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8406:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8407:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8408:):             $max=$$scan_config{'BubblesPerRow'};
                   8409:):             if (($scmode eq 'number') && ($max > 10)) {
                   8410:):                 $max = 10;
                   8411:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8412:):                 $max = 26;
                   8413:):             }
                   8414:):         } else {
                   8415:):             $max = 10;
                   8416:):         }
                   8417:):     }
1.274     albertel 8418: 
1.157     albertel 8419:     my @alphabet=('A'..'Z');
1.503     raeburn  8420:     $r->print(&Apache::loncommon::start_data_table().
                   8421:               &Apache::loncommon::start_data_table_row());
                   8422:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8423:     for (my $i=0;$i<$max+1;$i++) {
                   8424: 	$r->print("\n".'<td align="center">');
                   8425: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8426: 	else { $r->print('&nbsp;'); }
                   8427: 	$r->print('</td>');
                   8428:     }
1.503     raeburn  8429:     $r->print(&Apache::loncommon::end_data_table_row().
                   8430:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8431:     for (my $i=0;$i<$max;$i++) {
                   8432: 	$r->print("\n".
                   8433: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8434: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8435:     }
1.503     raeburn  8436:     my $nobub_checked = ' ';
                   8437:     if ($error eq 'missingbubble') {
                   8438:         $nobub_checked = ' checked = "checked" ';
                   8439:     }
                   8440:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8441: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8442:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8443:               $line.'" value="'.$questionnum.'" /></td>');
                   8444:     $r->print(&Apache::loncommon::end_data_table_row().
                   8445:               &Apache::loncommon::end_data_table());
1.157     albertel 8446: }
                   8447: 
1.423     albertel 8448: =pod
                   8449: 
                   8450: =item num_matches
                   8451: 
1.424     albertel 8452:    Counts the number of characters that are the same between the two arguments.
                   8453: 
                   8454:  Arguments:
                   8455:    $orig - CODE from the scanline
                   8456:    $code - CODE to match against
                   8457: 
                   8458:  Returns:
                   8459:    $count - integer count of the number of same characters between the
                   8460:             two arguments
                   8461: 
1.423     albertel 8462: =cut
                   8463: 
1.194     albertel 8464: sub num_matches {
                   8465:     my ($orig,$code) = @_;
                   8466:     my @code=split(//,$code);
                   8467:     my @orig=split(//,$orig);
                   8468:     my $same=0;
                   8469:     for (my $i=0;$i<scalar(@code);$i++) {
                   8470: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8471:     }
                   8472:     return $same;
                   8473: }
                   8474: 
1.423     albertel 8475: =pod
                   8476: 
                   8477: =item scantron_get_closely_matching_CODEs
                   8478: 
1.424     albertel 8479:    Cycles through all CODEs and finds the set that has the greatest
                   8480:    number of same characters as the provided CODE
                   8481: 
                   8482:  Arguments:
                   8483:    $allcodes - hash ref returned by &get_codes()
                   8484:    $CODE     - CODE from the current scanline
                   8485: 
                   8486:  Returns:
                   8487:    2 element list
                   8488:     - first elements is number of how closely matching the best fit is 
                   8489:       (5 means best set has 5 matching characters)
                   8490:     - second element is an arrary ref containing the set of valid CODEs
                   8491:       that best fit the passed in CODE
                   8492: 
1.423     albertel 8493: =cut
                   8494: 
1.194     albertel 8495: sub scantron_get_closely_matching_CODEs {
                   8496:     my ($allcodes,$CODE)=@_;
                   8497:     my @CODEs;
                   8498:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8499: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8500:     }
                   8501: 
                   8502:     return ($#CODEs,$CODEs[-1]);
                   8503: }
                   8504: 
1.423     albertel 8505: =pod
                   8506: 
                   8507: =item get_codes
                   8508: 
1.424     albertel 8509:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8510:    set of remembered CODEs.
                   8511: 
                   8512:  Arguments:
                   8513:   $old_name - name of the set of remembered CODEs
                   8514:   $cdom     - domain of the course
                   8515:   $cnum     - internal course name
                   8516: 
                   8517:  Returns:
                   8518:   %allcodes - keys are the valid CODEs, values are all 1
                   8519: 
1.423     albertel 8520: =cut
                   8521: 
1.194     albertel 8522: sub get_codes {
1.280     foxr     8523:     my ($old_name, $cdom, $cnum) = @_;
                   8524:     if (!$old_name) {
                   8525: 	$old_name=$env{'form.scantron_CODElist'};
                   8526:     }
                   8527:     if (!$cdom) {
                   8528: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8529:     }
                   8530:     if (!$cnum) {
                   8531: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8532:     }
1.278     albertel 8533:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8534: 				    $cdom,$cnum);
                   8535:     my %allcodes;
                   8536:     if ($result{"type\0$old_name"} eq 'number') {
                   8537: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8538:     } else {
                   8539: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8540:     }
1.194     albertel 8541:     return %allcodes;
                   8542: }
                   8543: 
1.423     albertel 8544: =pod
                   8545: 
                   8546: =item scantron_validate_CODE
                   8547: 
1.424     albertel 8548:    Validates all scanlines in the selected file to not have any
                   8549:    invalid or underspecified CODEs and that none of the codes are
                   8550:    duplicated if this was requested.
                   8551: 
1.423     albertel 8552: =cut
                   8553: 
1.157     albertel 8554: sub scantron_validate_CODE {
                   8555:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8556:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8557:     if ($scantron_config{'CODElocation'} &&
                   8558: 	$scantron_config{'CODEstart'} &&
                   8559: 	$scantron_config{'CODElength'}) {
1.257     albertel 8560: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8561: 	    &FIXME_blow_up()
                   8562: 	}
                   8563:     } else {
                   8564: 	return (0,$currentphase+1);
                   8565:     }
                   8566:     
                   8567:     my %usedCODEs;
                   8568: 
1.194     albertel 8569:     my %allcodes=&get_codes();
1.186     albertel 8570: 
1.582     raeburn  8571:     my $nav_error;
1.596.2.12.2.  (raeburn 8572:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8573:     if ($nav_error) {
                   8574:         $r->print(&navmap_errormsg());
                   8575:         return(1,$currentphase);
                   8576:     }
1.447     foxr     8577: 
1.186     albertel 8578:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8579:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8580: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8581: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8582: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8583: 						 $scan_data);
                   8584: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8585: 	my $error=0;
1.224     albertel 8586: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8587: 	    &scantron_get_correction($r,$i,$scan_record,
                   8588: 				     \%scantron_config,
                   8589: 				     $line,'incorrectCODE',\%allcodes);
                   8590: 	    return(1,$currentphase);
                   8591: 	}
1.221     albertel 8592: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8593: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8594: 	    &scantron_get_correction($r,$i,$scan_record,
                   8595: 				     \%scantron_config,
1.194     albertel 8596: 				     $line,'incorrectCODE',\%allcodes);
                   8597: 	    return(1,$currentphase);
1.186     albertel 8598: 	}
1.214     albertel 8599: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8600: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8601: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8602: 	    &scantron_get_correction($r,$i,$scan_record,
                   8603: 				     \%scantron_config,
1.194     albertel 8604: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8605: 	    return(1,$currentphase);
1.186     albertel 8606: 	}
1.524     raeburn  8607: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8608:     }
1.157     albertel 8609:     return (0,$currentphase+1);
                   8610: }
                   8611: 
1.423     albertel 8612: =pod
                   8613: 
                   8614: =item scantron_validate_doublebubble
                   8615: 
1.424     albertel 8616:    Validates all scanlines in the selected file to not have any
                   8617:    bubble lines with multiple bubbles marked.
                   8618: 
1.423     albertel 8619: =cut
                   8620: 
1.157     albertel 8621: sub scantron_validate_doublebubble {
                   8622:     my ($r,$currentphase) = @_;
                   8623:     #get student info
                   8624:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8625:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8626:3):     my (undef,undef,$sequence)=
                   8627:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8628: 
                   8629:     #get scantron line setup
1.596.2.12.2.  9(raebur 8630:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8631:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8632:3): 
                   8633:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8634:3):     unless (ref($navmap)) {
                   8635:3):         $r->print(&navmap_errormsg());
                   8636:3):         return(1,$currentphase);
                   8637:3):     }
                   8638:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8639:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8640:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8641:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8642:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8643:3): 
1.583     raeburn  8644:     my $nav_error;
1.596.2.12.2.  6(raebur 8645:3):     if (ref($map)) {
                   8646:3):         $randomorder = $map->randomorder();
                   8647:3):         $randompick = $map->randompick();
          0(raebur 8648:2):         unless ($randomorder || $randompick) {
                   8649:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8650:2):                 if ($res->randomorder()) {
                   8651:2):                     $randomorder = 1;
                   8652:2):                 }
                   8653:2):                 if ($res->randompick()) {
                   8654:2):                     $randompick = 1;
                   8655:2):                 }
                   8656:2):                 last if ($randomorder || $randompick);
                   8657:2):             }
                   8658:2):         }
          6(raebur 8659:3):         if ($randomorder || $randompick) {
                   8660:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8661:3):             if ($nav_error) {
                   8662:3):                 $r->print(&navmap_errormsg());
                   8663:3):                 return(1,$currentphase);
                   8664:3):             }
                   8665:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8666:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8667:3):         }
                   8668:3):     } else {
                   8669:3):         $r->print(&navmap_errormsg());
                   8670:3):         return(1,$currentphase);
                   8671:3):     }
                   8672:3): 
          (raeburn 8673:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8674:     if ($nav_error) {
                   8675:         $r->print(&navmap_errormsg());
                   8676:         return(1,$currentphase);
                   8677:     }
1.447     foxr     8678: 
1.157     albertel 8679:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8680: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8681: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8682: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8683:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8684:3):                                                  $randompick,$sequence,\@master_seq,
                   8685:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8686:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8687: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8688: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8689: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8690:3): 				 $$scan_record{'scantron.doubleerror'},
                   8691:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8692:     	return (1,$currentphase);
                   8693:     }
                   8694:     return (0,$currentphase+1);
                   8695: }
                   8696: 
1.423     albertel 8697: 
1.503     raeburn  8698: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8699:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8700:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8701: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8702: 	&restore_bubble_lines();
1.257     albertel 8703: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8704:     }
1.330     albertel 8705: 
1.447     foxr     8706:     my (undef, undef, $sequence) =
1.257     albertel 8707: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8708: 
1.447     foxr     8709:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8710:     unless (ref($navmap)) {
                   8711:         if (ref($nav_error)) {
                   8712:             $$nav_error = 1;
                   8713:         }
1.591     raeburn  8714:         return;
1.582     raeburn  8715:     }
1.191     albertel 8716:     my $map=$navmap->getResourceByUrl($sequence);
                   8717:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8718:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8719: 
                   8720:     &Apache::lonxml::clear_problem_counter();
                   8721: 
1.557     raeburn  8722:     my $uname       = $env{'user.name'};
                   8723:     my $udom        = $env{'user.domain'};
1.435     foxr     8724:     my $cid         = $env{'request.course.id'};
                   8725:     my $total_lines = 0;
                   8726:     %bubble_lines_per_response = ();
1.447     foxr     8727:     %first_bubble_line         = ();
1.503     raeburn  8728:     %subdivided_bubble_lines   = ();
                   8729:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8730:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8731: 
1.447     foxr     8732:     my $response_number = 0;
                   8733:     my $bubble_line     = 0;
1.191     albertel 8734:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8735:3):         my $resid = $resource->id();
          (raeburn 8736:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8737:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8738:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8739: 	    foreach my $part_id (@{$parts}) {
                   8740:                 my $lines;
                   8741: 
                   8742: 	        # TODO - make this a persistent hash not an array.
                   8743: 
                   8744:                 # optionresponse, matchresponse and rankresponse type items 
                   8745:                 # render as separate sub-questions in exam mode.
                   8746:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8747:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8748:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8749:                     my ($numbub,$numshown);
                   8750:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8751:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8752:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8753:                         }
                   8754:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8755:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8756:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8757:                         }
                   8758:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8759:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8760:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8761:                         }
                   8762:                     }
                   8763:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8764:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8765:                     }
1.596.2.12.2.  (raeburn 8766:):                     my $bubbles_per_row =
                   8767:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8768:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8769:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8770:                         $inner_bubble_lines++;
                   8771:                     }
                   8772:                     for (my $i=0; $i<$numshown; $i++) {
                   8773:                         $subdivided_bubble_lines{$response_number} .= 
                   8774:                             $inner_bubble_lines.',';
                   8775:                     }
                   8776:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8777:                     $lines = $numshown * $inner_bubble_lines;
                   8778:                 } else {
                   8779:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8780:):                 }
1.542     raeburn  8781: 
                   8782:                 $first_bubble_line{$response_number} = $bubble_line;
                   8783: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8784:                 $responsetype_per_response{$response_number} = 
                   8785:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8786:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8787: 	        $response_number++;
                   8788: 
                   8789: 	        $bubble_line +=  $lines;
                   8790: 	        $total_lines +=  $lines;
                   8791: 	    }
                   8792:         }
                   8793:     }
1.552     raeburn  8794:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8795: 
                   8796:     &save_bubble_lines();
                   8797:     $env{'form.scantron_maxbubble'} =
                   8798: 	$total_lines;
                   8799:     return $env{'form.scantron_maxbubble'};
                   8800: }
1.523     raeburn  8801: 
1.596.2.12.2.  (raeburn 8802:): sub bubblesheet_bubbles_per_row {
                   8803:):     my ($scantron_config) = @_;
                   8804:):     my $bubbles_per_row;
                   8805:):     if (ref($scantron_config) eq 'HASH') {
                   8806:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8807:):     }
                   8808:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8809:):         $bubbles_per_row = 10;
                   8810:):     }
                   8811:):     return $bubbles_per_row;
                   8812:): }
                   8813:): 
1.157     albertel 8814: sub scantron_validate_missingbubbles {
                   8815:     my ($r,$currentphase) = @_;
                   8816:     #get student info
                   8817:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8818:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8819:3):     my (undef,undef,$sequence)=
                   8820:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8821: 
                   8822:     #get scantron line setup
1.596.2.12.2.  9(raebur 8823:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8824:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8825:3): 
                   8826:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8827:3):     unless (ref($navmap)) {
                   8828:3):         $r->print(&navmap_errormsg());
                   8829:3):         return(1,$currentphase);
                   8830:3):     }
                   8831:3): 
                   8832:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8833:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8834:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8835:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8836:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8837:3): 
1.582     raeburn  8838:     my $nav_error;
1.596.2.12.2.  6(raebur 8839:3):     if (ref($map)) {
                   8840:3):         $randomorder = $map->randomorder();
                   8841:3):         $randompick = $map->randompick();
          0(raebur 8842:2):         unless ($randomorder || $randompick) {
                   8843:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8844:2):                 if ($res->randomorder()) {
                   8845:2):                     $randomorder = 1;
                   8846:2):                 }
                   8847:2):                 if ($res->randompick()) {
                   8848:2):                     $randompick = 1;
                   8849:2):                 }
                   8850:2):                 last if ($randomorder || $randompick);
                   8851:2):             }
                   8852:2):         }
          7(raebur 8853:3):         if ($randomorder || $randompick) {
                   8854:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8855:3):             if ($nav_error) {
                   8856:3):                 $r->print(&navmap_errormsg());
                   8857:3):                 return(1,$currentphase);
                   8858:3):             }
                   8859:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8860:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8861:3):         }
          6(raebur 8862:3):     } else {
                   8863:3):         $r->print(&navmap_errormsg());
          7(raebur 8864:3):         return(1,$currentphase);
          6(raebur 8865:3):     }
                   8866:3): 
                   8867:3): 
          (raeburn 8868:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8869:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8870:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8871:         return(1,$currentphase);
                   8872:     }
1.596.2.12.2.  6(raebur 8873:3): 
1.157     albertel 8874:     if (!$max_bubble) { $max_bubble=2**31; }
                   8875:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8876: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8877: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8878:3):         my $scan_record =
                   8879:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8880:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8881:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8882:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8883: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8884: 	my @to_correct;
1.470     foxr     8885: 	
                   8886: 	# Probably here's where the error is...
                   8887: 
1.157     albertel 8888: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8889:             my $lastbubble;
                   8890:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8891:3):                 my $question = $1;
                   8892:3):                 my $subquestion = $2;
                   8893:3):                 my ($first,$responsenum);
                   8894:3):                 if ($randomorder || $randompick) {
                   8895:3):                     $responsenum = $respnumlookup{$question-1};
                   8896:3):                     $first = $startline{$question-1};
                   8897:3):                 } else {
                   8898:3):                     $responsenum = $question-1;
                   8899:3):                     $first = $first_bubble_line{$responsenum};
                   8900:3):                 }
                   8901:3):                 if (!defined($first)) { next; }
          7(raebur 8902:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8903:3):                 my $subcount = 1;
                   8904:3):                 while ($subcount<$subquestion) {
                   8905:3):                     $first += $subans[$subcount-1];
                   8906:3):                     $subcount ++;
                   8907:3):                 }
                   8908:3):                 my $count = $subans[$subquestion-1];
                   8909:3):                 $lastbubble = $first + $count;
1.505     raeburn  8910:             } else {
1.596.2.12.2.  6(raebur 8911:3):                 my ($first,$responsenum);
                   8912:3):                 if ($randomorder || $randompick) {
                   8913:3):                     $responsenum = $respnumlookup{$missing-1};
                   8914:3):                     $first = $startline{$missing-1};
                   8915:3):                 } else {
                   8916:3):                     $responsenum = $missing-1;
                   8917:3):                     $first = $first_bubble_line{$responsenum};
                   8918:3):                 }
                   8919:3):                 if (!defined($first)) { next; }
                   8920:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8921:             }
                   8922:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8923: 	    push(@to_correct,$missing);
                   8924: 	}
                   8925: 	if (@to_correct) {
                   8926: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8927:3): 				     $line,'missingbubble',\@to_correct,
                   8928:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8929:3):                                      \%startline);
1.157     albertel 8930: 	    return (1,$currentphase);
                   8931: 	}
                   8932: 
                   8933:     }
                   8934:     return (0,$currentphase+1);
                   8935: }
                   8936: 
1.596.2.12.2.  (raeburn 8937:): sub hand_bubble_option {
                   8938:):     my (undef, undef, $sequence) =
                   8939:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8940:):     return if ($sequence eq '');
                   8941:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8942:):     unless (ref($navmap)) {
                   8943:):         return;
                   8944:):     }
                   8945:):     my $needs_hand_bubbles;
                   8946:):     my $map=$navmap->getResourceByUrl($sequence);
                   8947:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8948:):     foreach my $res (@resources) {
                   8949:):         if (ref($res)) {
                   8950:):             if ($res->is_problem()) {
                   8951:):                 my $partlist = $res->parts();
                   8952:):                 foreach my $part (@{ $partlist }) {
                   8953:):                     my @types = $res->responseType($part);
                   8954:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8955:):                         $needs_hand_bubbles = 1;
                   8956:):                         last;
                   8957:):                     }
                   8958:):                 }
                   8959:):             }
                   8960:):         }
                   8961:):     }
                   8962:):     if ($needs_hand_bubbles) {
          9(raebur 8963:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8964:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8965:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8966:):                &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 />').
                   8967:):                '<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 8968:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8969:):     }
                   8970:):     return;
                   8971:): }
1.423     albertel 8972: 
1.82      albertel 8973: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8974:0):     my ($r,$symb) = @_;
1.513     foxr     8975: 
1.257     albertel 8976:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8977:     if (!$symb) {
                   8978: 	return '';
                   8979:     }
1.324     albertel 8980:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8981: 
1.596.2.12.2.  9(raebur 8982:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8983:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8984:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8985:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8986:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8987:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8988:     unless (ref($navmap)) {
                   8989:         $r->print(&navmap_errormsg());
                   8990:         return '';
1.596.2.12.2.  6(raebur 8991:3):     }
1.83      albertel 8992:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8993:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
          0(raebur 8994:2):         %grader_randomlists_by_symb,%symb_for_examcode);
          1(raebur 8995:2):     if (ref($map)) {
                   8996:2):         $randomorder = $map->randomorder();
          6(raebur 8997:3):         $randompick = $map->randompick();
          0(raebur 8998:2):         unless ($randomorder || $randompick) {
                   8999:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9000:2):                 if ($res->randomorder()) {
                   9001:2):                     $randomorder = 1;
                   9002:2):                 }
                   9003:2):                 if ($res->randompick()) {
                   9004:2):                     $randompick = 1;
                   9005:2):                 }
                   9006:2):                 last if ($randomorder || $randompick);
                   9007:2):             }
                   9008:2):         }
          6(raebur 9009:3):     } else {
                   9010:3):         $r->print(&navmap_errormsg());
                   9011:3):         return '';
          1(raebur 9012:2):     }
          6(raebur 9013:3):     my $nav_error;
1.83      albertel 9014:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9015:3):     if ($randomorder || $randompick) {
          0(raebur 9016:2):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
          6(raebur 9017:3):         if ($nav_error) {
                   9018:3):             $r->print(&navmap_errormsg());
                   9019:3):             return '';
1.586     raeburn  9020:         }
                   9021:     }
1.596.2.12.2.  6(raebur 9022:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9023:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  9024: 
1.554     raeburn  9025:     my ($uname,$udom);
1.82      albertel 9026:     my $result= <<SCANTRONFORM;
1.81      albertel 9027: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   9028:   <input type="hidden" name="command" value="scantron_configphase" />
                   9029:   $default_form_data
                   9030: SCANTRONFORM
1.82      albertel 9031:     $r->print($result);
                   9032: 
                   9033:     my @delayqueue;
1.542     raeburn  9034:     my (%completedstudents,%scandata);
1.140     albertel 9035:     
1.520     www      9036:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9037:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 9038:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 9039:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9040:     $r->print('<br />');
1.140     albertel 9041:     my $start=&Time::HiRes::time();
1.158     albertel 9042:     my $i=-1;
1.542     raeburn  9043:     my $started;
1.447     foxr     9044: 
1.596.2.12.2.  (raeburn 9045:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9046:     if ($nav_error) {
                   9047:         $r->print(&navmap_errormsg());
                   9048:         return '';
                   9049:     }
                   9050: 
1.513     foxr     9051:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9052:     # the user and return.
                   9053: 
                   9054:     if ($ssi_error) {
                   9055: 	$r->print("</form>");
                   9056: 	&ssi_print_error($r);
1.520     www      9057:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9058: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9059:     }
1.447     foxr     9060: 
1.596.2.12.2.  9(raebur 9061:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9062:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 9063:3):     my %orderedforcode;
1.542     raeburn  9064: 
1.157     albertel 9065:     while ($i<$scanlines->{'count'}) {
                   9066:  	($uname,$udom)=('','');
                   9067:  	$i++;
1.200     albertel 9068:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9069:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9070: 	if ($started) {
1.596.2.12.2.  1(raebur 9071:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9072: 	}
                   9073: 	$started=1;
1.596.2.12.2.  6(raebur 9074:3):         my %respnumlookup = ();
                   9075:3):         my %startline = ();
                   9076:3):         my $total;
1.157     albertel 9077:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 9078:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   9079:3):                                                  $randompick,$sequence,\@master_seq,
                   9080:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9081:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9082:3):                                                  \$total);
1.157     albertel 9083:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9084:  					      \%idmap,$i)) {
                   9085:   	    &scantron_add_delay(\@delayqueue,$line,
                   9086:  				'Unable to find a student that matches',1);
                   9087:  	    next;
                   9088:   	}
                   9089:  	if (exists $completedstudents{$uname}) {
                   9090:  	    &scantron_add_delay(\@delayqueue,$line,
                   9091:  				'Student '.$uname.' has multiple sheets',2);
                   9092:  	    next;
                   9093:  	}
1.596.2.12.2.  1(raebur 9094:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9095:2):         my $user = $uname.':'.$usec;
1.157     albertel 9096:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9097: 
1.596.2.12.2.  1(raebur 9098:2):         my $scancode;
                   9099:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9100:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9101:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9102:2):         } else {
                   9103:2):             $scancode = '';
                   9104:2):         }
                   9105:2): 
                   9106:2):         my @mapresources = @resources;
          6(raebur 9107:3):         if ($randomorder || $randompick) {
          1(raebur 9108:2):             @mapresources =
          6(raebur 9109:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9110:3):                              \%orderedforcode);
          1(raebur 9111:2):         }
1.586     raeburn  9112:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 9113:2):         foreach my $resource (@mapresources) {
1.586     raeburn  9114:             my $ressymb;
                   9115:             if (ref($resource)) {
                   9116:                 $ressymb = $resource->symb();
                   9117:             } else {
                   9118:                 $res_error = 1;
                   9119:                 last;
                   9120:             }
1.557     raeburn  9121:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9122:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9123:7):                 my $currcode;
                   9124:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9125:7):                     $currcode = $scancode;
                   9126:7):                 }
1.557     raeburn  9127:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 9128:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 9129:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   9130:7):                                               $currcode);
1.557     raeburn  9131:                 $partids_by_symb{$ressymb} = $parts;
                   9132:             } else {
                   9133:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9134:             }
1.554     raeburn  9135:         }
                   9136: 
1.586     raeburn  9137:         if ($res_error) {
                   9138:             &scantron_add_delay(\@delayqueue,$line,
                   9139:                                 'An error occurred while grading student '.$uname,2);
                   9140:             next;
                   9141:         }
                   9142: 
1.330     albertel 9143: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9144:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9145: 
                   9146: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9147: 	    &scantron_putfile($scanlines,$scan_data);
                   9148: 	}
1.161     albertel 9149: 	
1.542     raeburn  9150:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9151:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 9152:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   9153:3):                                    \%respnumlookup,\%startline) 
                   9154:3):             eq 'ssi_error') {
1.542     raeburn  9155:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9156:             $r->print("</form>");
                   9157:             &ssi_print_error($r);
                   9158:             &Apache::lonnet::remove_lock($lock);
                   9159:             return '';      # Why return ''?  Beats me.
                   9160:         }
1.513     foxr     9161: 
1.596.2.12.2.  6(raebur 9162:3):         if (($scancode) && ($randomorder || $randompick)) {
          0(raebur 9163:2):             foreach my $key (keys(%symb_for_examcode)) {
                   9164:2):                 my $symb_in_map = $symb_for_examcode{$key};
                   9165:2):                 if ($symb_in_map ne '') {
                   9166:2):                     my $parmresult =
                   9167:2):                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9168:2):                                                                '0_examcode',2,$scancode,
                   9169:2):                                                                'string_examcode',$uname,
                   9170:2):                                                                $udom);
                   9171:2):                 }
                   9172:2):             }
          6(raebur 9173:3):         }
1.140     albertel 9174: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9175:         if ($env{'form.verifyrecord'}) {
                   9176:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 9177:3):             if ($randompick) {
                   9178:3):                 if ($total) {
                   9179:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   9180:3):                 }
                   9181:3):             }
                   9182:3): 
1.542     raeburn  9183:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9184:             chomp($studentdata);
                   9185:             $studentdata =~ s/\r$//;
                   9186:             my $studentrecord = '';
                   9187:             my $counter = -1;
1.596.2.12.2.  1(raebur 9188:2):             foreach my $resource (@mapresources) {
1.554     raeburn  9189:                 my $ressymb = $resource->symb();
1.542     raeburn  9190:                 ($counter,my $recording) =
                   9191:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9192:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9193:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9194:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9195:                 $studentrecord .= $recording;
                   9196:             }
                   9197:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9198:                 &Apache::lonxml::clear_problem_counter();
                   9199:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9200:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 9201:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   9202:3):                                            \%respnumlookup,\%startline)
                   9203:3):                     eq 'ssi_error') {
1.554     raeburn  9204:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9205:                     $r->print("</form>");
                   9206:                     &ssi_print_error($r);
                   9207:                     &Apache::lonnet::remove_lock($lock);
                   9208:                     delete($completedstudents{$uname});
                   9209:                     return '';
                   9210:                 }
1.542     raeburn  9211:                 $counter = -1;
                   9212:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 9213:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  9214:                     my $ressymb = $resource->symb();
1.542     raeburn  9215:                     ($counter,my $recording) =
                   9216:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9217:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9218:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   9219:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   9220:3):                                                  \%startline);
1.542     raeburn  9221:                     $studentrecord .= $recording;
                   9222:                 }
                   9223:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  9224:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9225:                     if ($scancode eq '') {
1.596.2.6  raeburn  9226:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9227:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9228:                     } else {
1.596.2.6  raeburn  9229:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9230:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9231:                     }
                   9232:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9233:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9234:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9235:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9236:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9237:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 9238:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9239:                               &Apache::loncommon::end_data_table_row().
                   9240:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9241:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 9242:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9243:                               &Apache::loncommon::end_data_table_row().
                   9244:                               &Apache::loncommon::end_data_table().'</p>');
                   9245:                 } else {
                   9246:                     $r->print('<br /><span class="LC_warning">'.
                   9247:                              &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 />'.
                   9248:                              &mt("As a consequence, this user's submission history records two tries.").
                   9249:                                  '</span><br />');
                   9250:                 }
                   9251:             }
                   9252:         }
1.543     raeburn  9253:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9254:     } continue {
1.330     albertel 9255: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9256: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9257:     }
1.140     albertel 9258:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9259:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9260: #    my $lasttime = &Time::HiRes::time()-$start;
                   9261: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9262: 
1.200     albertel 9263:     $r->print("</form>");
1.157     albertel 9264:     return '';
1.75      albertel 9265: }
1.157     albertel 9266: 
1.557     raeburn  9267: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 9268:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9269:):         $bubbles_per_row) = @_;
1.557     raeburn  9270:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9271:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9272:         foreach my $resource (@{$resources}) {
                   9273:             my $ressymb = $resource->symb();
                   9274:             my ($analysis,$parts) =
                   9275:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 9276:):                                           $env{'user.name'},$env{'user.domain'},
                   9277:):                                           1,$bubbles_per_row);
1.557     raeburn  9278:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9279:             if (ref($analysis) eq 'HASH') {
                   9280:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9281:                     $grader_randomlists_by_symb->{$ressymb} =
                   9282:                         $analysis->{'parts_withrandomlist'};
                   9283:                 }
                   9284:             }
                   9285:         }
                   9286:     }
                   9287:     return;
                   9288: }
                   9289: 
1.596.2.12.2.  1(raebur 9290:2): =pod
                   9291:2): 
                   9292:2): =item users_order
                   9293:2): 
                   9294:2):   Returns array of resources in current map, ordered based on either CODE,
                   9295:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9296:2):   "NAMEd" exam.
                   9297:2): 
          6(raebur 9298:3):   Should be used when randomorder and/or randompick applied when the 
                   9299:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9300:3):   for the version of the exam the student received.
          1(raebur 9301:2): 
                   9302:2): =cut
                   9303:2): 
                   9304:2): sub users_order  {
          6(raebur 9305:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9306:2):     my @mapresources;
          6(raebur 9307:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9308:2):         return @mapresources;
                   9309:2):     }
          6(raebur 9310:3):     if ($scancode) {
                   9311:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9312:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9313:3):         } else {
                   9314:3):             $env{'form.CODE'} = $scancode;
                   9315:3):             my $actual_seq =
                   9316:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9317:3):                                                                $master_seq,
                   9318:3):                                                                $user,$scancode,1);
                   9319:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9320:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9321:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9322:3):                     if (@mapresources > 0) {
                   9323:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9324:3):                     }
                   9325:3):                 }
                   9326:3):             }
                   9327:3):             delete($env{'form.CODE'});
          1(raebur 9328:2):         }
                   9329:2):     } else {
                   9330:2):         my $actual_seq =
                   9331:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9332:2):                                                            $master_seq,
          5(raebur 9333:3):                                                            $user,undef,1);
          1(raebur 9334:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9335:2):             @mapresources =
                   9336:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9337:2):         }
          6(raebur 9338:3):     }
                   9339:3):     return @mapresources;
          1(raebur 9340:2): }
                   9341:2): 
1.542     raeburn  9342: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9343:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9344:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9345:3):     my $uselookup = 0;
                   9346:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9347:3):         (ref($startline) eq 'HASH')) {
                   9348:3):         $uselookup = 1;
                   9349:3):     }
                   9350:3): 
1.554     raeburn  9351:     if (ref($resources) eq 'ARRAY') {
                   9352:         my $count = 0;
                   9353:         foreach my $resource (@{$resources}) {
                   9354:             my $ressymb = $resource->symb();
                   9355:             my %form = ('submitted'      => 'scantron',
                   9356:                         'grade_target'   => 'grade',
                   9357:                         'grade_username' => $uname,
                   9358:                         'grade_domain'   => $udom,
                   9359:                         'grade_courseid' => $env{'request.course.id'},
                   9360:                         'grade_symb'     => $ressymb,
                   9361:                         'CODE'           => $scancode
                   9362:                        );
1.596.2.12.2.  (raeburn 9363:):             if ($bubbles_per_row ne '') {
                   9364:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9365:):             }
                   9366:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9367:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9368:):             }
1.554     raeburn  9369:             if (ref($parts) eq 'HASH') {
                   9370:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9371:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9372:3):                         if ($uselookup) {
                   9373:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9374:3):                         } else {
                   9375:3):                             $form{'scantron_questnum_start.'.$part} =
                   9376:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9377:3):                         }
1.554     raeburn  9378:                         $count++;
                   9379:                     }
                   9380:                 }
                   9381:             }
                   9382:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9383:             return 'ssi_error' if ($ssi_error);
                   9384:             last if (&Apache::loncommon::connection_aborted($r));
                   9385:         }
1.542     raeburn  9386:     }
                   9387:     return;
                   9388: }
                   9389: 
1.157     albertel 9390: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9391:0):     my ($r,$symb) = @_;
1.565     raeburn  9392:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9393:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9394:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9395:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9396:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9397: 							  'domainid',
1.565     raeburn  9398: 							  'coursename',$dom);
                   9399:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9400:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9401:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9402:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9403:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9404:     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 9405:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9406:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9407:     function checkUpload(formname) {
                   9408: 	if (formname.upfile.value == "") {
1.579     raeburn  9409: 	    alert("'.$nofile_alert.'");
1.157     albertel 9410: 	    return false;
                   9411: 	}
1.565     raeburn  9412:         if (formname.courseid.value == "") {
1.579     raeburn  9413:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9414:             return false;
                   9415:         }
1.157     albertel 9416: 	formname.submit();
                   9417:     }
1.565     raeburn  9418: 
                   9419:     function ToSyllabus() {
                   9420:         var cdom = '."'$dom'".';
                   9421:         var cnum = document.rules.courseid.value;
                   9422:         if (cdom == "" || cdom == null) {
                   9423:             return;
                   9424:         }
                   9425:         if (cnum == "" || cnum == null) {
                   9426:            return;
                   9427:         }
                   9428:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9429:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9430:         return;
                   9431:     }
                   9432: 
1.596.2.12.2.  9(raebur 9433:9):     '.$formatjs.'
                   9434:9): '));
                   9435:9):     $r->print('
1.596.2.4  raeburn  9436: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9437: 
1.492     albertel 9438: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9439: '.$default_form_data.
                   9440:   &Apache::lonhtmlcommon::start_pick_box().
                   9441:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9442:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9443:   &Apache::lonhtmlcommon::row_closure().
                   9444:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9445:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9446:   &Apache::lonhtmlcommon::row_closure().
                   9447:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9448:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9449:9):   &Apache::lonhtmlcommon::row_closure());
                   9450:9):     if ($formatoptions) {
                   9451:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9452:9):                   &Apache::lonhtmlcommon::row_closure());
                   9453:9):     }
                   9454:9):     $r->print(
1.565     raeburn  9455:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9456:   '<input type="file" name="upfile" size="50" />'.
                   9457:   &Apache::lonhtmlcommon::row_closure(1).
                   9458:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9459: 
1.492     albertel 9460: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9461: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9462: </form>
1.492     albertel 9463: ');
1.157     albertel 9464:     return '';
                   9465: }
                   9466: 
1.596.2.12.2.  9(raebur 9467:9): sub scantron_upload_dataformat {
                   9468:9):     my ($dom) = @_;
                   9469:9):     my ($formatoptions,$formattitle,$formatjs);
                   9470:9):     $formatjs = <<'END';
                   9471:9): function toggleScantab(form) {
                   9472:9):    return;
                   9473:9): }
                   9474:9): END
                   9475:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9476:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9477:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9478:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9479:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9480:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9481:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9482:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9483:9):                             my ($onclick,$formatextra,$singleline);
                   9484:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9485:9):                             my $count = 0;
                   9486:9):                             foreach my $line (@lines) {
          0.2.1(ra 9487:an-23):                                 next if (($line =~ /^\#/) || ($line eq ''));
          9(raebur 9488:9):                                 $singleline = $line;
                   9489:9):                                 $count ++;
                   9490:9):                             }
                   9491:9):                             if ($count > 1) {
                   9492:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9493:9):                                                '<span class="LC_nobreak">'.
          4(raebur 9494:0):                                                &mt('Bubblesheet type').':&nbsp;'.
          9(raebur 9495:9):                                                &scantron_scantab().'</span></div>';
                   9496:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9497:9):                                 $formatjs = <<"END";
                   9498:9): function toggleScantab(form) {
                   9499:9):     var divid = 'bubbletype';
                   9500:9):     if (document.getElementById(divid)) {
                   9501:9):         var radioname = 'fileformat';
                   9502:9):         var num = form.elements[radioname].length;
                   9503:9):         if (num) {
                   9504:9):             for (var i=0; i<num; i++) {
                   9505:9):                 if (form.elements[radioname][i].checked) {
                   9506:9):                     var chosen = form.elements[radioname][i].value;
                   9507:9):                     if (chosen == 'dat') {
                   9508:9):                         document.getElementById(divid).style.display = 'none';
                   9509:9):                     } else if (chosen == 'csv') {
                   9510:9):                         document.getElementById(divid).style.display = 'block';
                   9511:9):                     }
                   9512:9):                 }
                   9513:9):             }
                   9514:9):         }
                   9515:9):     }
                   9516:9):     return;
                   9517:9): }
                   9518:9): 
                   9519:9): END
                   9520:9):                             } elsif ($count == 1) {
                   9521:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9522:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9523:9):                             }
                   9524:9):                             $formattitle = &mt('File format');
                   9525:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9526:9):                                              &mt('Plain Text (no delimiters)').
                   9527:9):                                              '</label>'.('&nbsp;'x2).
                   9528:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9529:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9530:9):                         }
                   9531:9):                     }
                   9532:9):                 }
                   9533:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9534:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9535:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9536:9):                         $formattitle = &mt('Bubblesheet type');
                   9537:9):                         $formatoptions = &scantron_scantab();
                   9538:9):                     }
                   9539:9):                 }
                   9540:9):             }
                   9541:9):         }
                   9542:9):     }
                   9543:9):     return ($formatoptions,$formattitle,$formatjs);
                   9544:9): }
1.423     albertel 9545: 
1.157     albertel 9546: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9547:0):     my ($r,$symb) = @_;
1.182     albertel 9548:     my $doanotherupload=
                   9549: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9550: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9551: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9552: 	'</form>'."\n";
1.257     albertel 9553:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9554: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9555: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9556: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9557:0):         unless ($symb) {
1.182     albertel 9558: 	    $r->print($doanotherupload);
                   9559: 	}
1.162     albertel 9560: 	return '';
                   9561:     }
1.257     albertel 9562:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9563:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9564:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9565:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9566:3):         $r->print(
                   9567:3):             &Apache::lonhtmlcommon::confirm_success(
                   9568:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9569:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9570:     } else {
1.596.2.12.2.  9(raebur 9571:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9572:9):         my $parser;
                   9573:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9574:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9575:9):                 my $is_csv;
                   9576:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9577:9):                 if (@possibles > 1) {
                   9578:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9579:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9580:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9581:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9582:9):                                     $is_csv = 1;
                   9583:9):                                 }
                   9584:9):                             }
                   9585:9):                         }
                   9586:9):                     }
                   9587:9):                 } elsif (@possibles == 1) {
                   9588:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9589:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9590:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9591:9):                                 $is_csv = 1;
                   9592:9):                             }
                   9593:9):                         }
                   9594:9):                     }
                   9595:9):                 }
                   9596:9):                 if ($is_csv) {
                   9597:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9598:9):                 }
                   9599:9):             }
                   9600:9):         }
                   9601:9):         my $result =
                   9602:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9603:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9604: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9605:3):             $r->print(
                   9606:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9607:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9608:3):                         (length($env{'form.upfile'})-1),
                   9609:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9610:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9611:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9612:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9613: 	} else {
1.596.2.12.2.  5(raebur 9614:3):             $r->print(
                   9615:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9616:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9617:3):                           $result,
1.568     raeburn  9618: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9619: 	}
                   9620:     }
1.174     albertel 9621:     if ($symb) {
1.596.2.12.2.  1(raebur 9622:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9623:     } else {
1.182     albertel 9624: 	$r->print($doanotherupload);
1.174     albertel 9625:     }
1.157     albertel 9626:     return '';
                   9627: }
                   9628: 
1.567     raeburn  9629: sub validate_uploaded_scantron_file {
                   9630:     my ($cdom,$cname,$fname) = @_;
                   9631:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9632:     my @lines;
                   9633:     if ($scanlines ne '-1') {
                   9634:         @lines=split("\n",$scanlines,-1);
                   9635:     }
                   9636:     my $output;
                   9637:     if (@lines) {
                   9638:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9639:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9640:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9641:         my %idmap = &username_to_idmap($classlist);
                   9642:         foreach my $key (keys(%idmap)) {
                   9643:             my $lckey = lc($key);
                   9644:             $idmap{$lckey} = $idmap{$key};
                   9645:         }
                   9646:         my %unique_formats;
1.596.2.12.2.  9(raebur 9647:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9648:         foreach my $line (@formatlines) {
1.596.2.12.2.  0.2.1(ra 9649:an-23):             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  9650:             my @config = split(/:/,$line);
                   9651:             my $idstart = $config[5];
                   9652:             my $idlength = $config[6];
                   9653:             if (($idstart ne '') && ($idlength > 0)) {
                   9654:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9655:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9656:                 } else {
                   9657:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9658:                 }
                   9659:             }
                   9660:         }
                   9661:         foreach my $key (keys(%unique_formats)) {
                   9662:             my ($idstart,$idlength) = split(':',$key);
                   9663:             %{$counts{$key}} = (
                   9664:                                'found'   => 0,
                   9665:                                'total'   => 0,
                   9666:                               );
                   9667:             foreach my $line (@lines) {
                   9668:                 next if ($line =~ /^#/);
                   9669:                 next if ($line =~ /^[\s\cz]*$/);
                   9670:                 my $id = substr($line,$idstart-1,$idlength);
                   9671:                 $id = lc($id);
                   9672:                 if (exists($idmap{$id})) {
                   9673:                     $counts{$key}{'found'} ++;
                   9674:                 }
                   9675:                 $counts{$key}{'total'} ++;
                   9676:             }
                   9677:             if ($counts{$key}{'total'}) {
                   9678:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9679:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9680:                     $max_match_pct = $percent_match;
                   9681:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9682:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9683:                     $max_match_count = $counts{$key}{'total'};
                   9684:                 }
                   9685:             }
                   9686:         }
                   9687:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9688:             my $format_descs;
                   9689:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9690:             for (my $i=0; $i<$numwithformat; $i++) {
                   9691:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9692:                 if ($i<$numwithformat-2) {
                   9693:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9694:                 } elsif ($i==$numwithformat-2) {
                   9695:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9696:                 } elsif ($i==$numwithformat-1) {
                   9697:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9698:                 }
                   9699:             }
                   9700:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9701:3):             $output .= '<br />';
                   9702:3):             if ($found_match_count == $max_match_count) {
                   9703:3):                 # 100% matching entries
                   9704:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9705:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9706:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9707:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9708:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9709:3):                     ' in the file (for the format defined for [_3]).',
                   9710:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9711:3):             } else {
                   9712:3):                 # Not all entries matching? -> Show warning and additional info
                   9713:3):                 $output .=
                   9714:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9715:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9716:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9717:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9718:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9719:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9720:3):                         ' in the file (for the format defined for [_3]).',
                   9721:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9722:3):                     '<p class="LC_info">'.
                   9723:3):                     &mt('A low percentage of matches results from one of the following:').
                   9724:3):                     '</p><ul>'.
                   9725:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9726:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9727:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9728:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9729:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9730:3):                     '</ul>';
                   9731:3):             }
1.567     raeburn  9732:         }
                   9733:     } else {
1.596.2.12.2.  5(raebur 9734:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9735:     }
                   9736:     return $output;
                   9737: }
                   9738: 
1.202     albertel 9739: sub valid_file {
                   9740:     my ($requested_file)=@_;
                   9741:     foreach my $filename (sort(&scantron_filenames())) {
                   9742: 	if ($requested_file eq $filename) { return 1; }
                   9743:     }
                   9744:     return 0;
                   9745: }
                   9746: 
                   9747: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9748:0):     my ($r,$symb) = @_;
          (raeburn 9749:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9750:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9751:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9752:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9753:     if (! &valid_file($file)) {
1.492     albertel 9754: 	$r->print('
1.202     albertel 9755: 	<p>
1.596.2.12.2.  3(raebur 9756:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9757:         </p>
1.492     albertel 9758: ');
1.202     albertel 9759: 	return;
                   9760:     }
                   9761:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9762:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9763:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9764:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9765:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9766:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9767:     $r->print('
1.202     albertel 9768:     <p>
1.596.2.12.2.  1(raebur 9769:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9770: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9771:     </p>
                   9772:     <p>
1.492     albertel 9773: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9774: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9775:     </p>
                   9776:     <p>
1.492     albertel 9777: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9778: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9779:     </p>
1.492     albertel 9780: ');
1.202     albertel 9781:     return '';
                   9782: }
1.157     albertel 9783: 
1.523     raeburn  9784: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9785:0):     my ($r,$symb) = @_;
1.523     raeburn  9786:     if (!$symb) {return '';}
                   9787:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9788:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9789:     my $numletts = scalar(keys(%lettdig));
                   9790:     my $cnum = $env{'course.'.$cid.'.num'};
                   9791:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9792:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9793:     my %record;
                   9794:     my %scantron_config =
1.596.2.12.2.  9(raebur 9795:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9796:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9797:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9798:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9799:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9800:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9801:     unless (ref($navmap)) {
                   9802:         $r->print(&navmap_errormsg());
                   9803:         return '';
                   9804:     }
1.523     raeburn  9805:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9806:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9807:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9808:2):     if (ref($map)) {
                   9809:2):         $randomorder=$map->randomorder();
          7(raebur 9810:3):         $randompick=$map->randompick();
          0(raebur 9811:2):         unless ($randomorder || $randompick) {
                   9812:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9813:2):                 if ($res->randomorder()) {
                   9814:2):                     $randomorder = 1;
                   9815:2):                 }
                   9816:2):                 if ($res->randompick()) {
                   9817:2):                     $randompick = 1;
                   9818:2):                 }
                   9819:2):                 last if ($randomorder || $randompick);
                   9820:2):             }
                   9821:2):         }
          1(raebur 9822:2):     }
1.557     raeburn  9823:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9824:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9825:3):     if ($nav_error) {
                   9826:3):         $r->print(&navmap_errormsg());
                   9827:3):         return '';
          1(raebur 9828:2):     }
          (raeburn 9829:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9830:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9831:     my ($uname,$udom);
1.523     raeburn  9832:     my (%scandata,%lastname,%bylast);
                   9833:     $r->print('
                   9834: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9835: 
                   9836:     my @delayqueue;
                   9837:     my %completedstudents;
                   9838: 
1.596.2.12.2.  6(raebur 9839:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9840:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9841:3):     my ($username,$domain,$started);
          (raeburn 9842:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9843:     if ($nav_error) {
                   9844:         $r->print(&navmap_errormsg());
                   9845:         return '';
                   9846:     }
1.523     raeburn  9847: 
                   9848:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9849:                                           'Processing first student');
                   9850:     my $start=&Time::HiRes::time();
                   9851:     my $i=-1;
                   9852: 
                   9853:     while ($i<$scanlines->{'count'}) {
                   9854:         ($username,$domain,$uname)=('','','');
                   9855:         $i++;
                   9856:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9857:         if ($line=~/^[\s\cz]*$/) { next; }
                   9858:         if ($started) {
                   9859:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9860:                                                      'last student');
                   9861:         }
                   9862:         $started=1;
                   9863:         my $scan_record=
                   9864:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9865:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9866:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9867:3):                                               \%idmap,$i)) {
1.523     raeburn  9868:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9869:                                 'Unable to find a student that matches',1);
                   9870:             next;
                   9871:         }
                   9872:         if (exists $completedstudents{$uname}) {
                   9873:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9874:                                 'Student '.$uname.' has multiple sheets',2);
                   9875:             next;
                   9876:         }
                   9877:         my $pid = $scan_record->{'scantron.ID'};
                   9878:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9879:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9880:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9881:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9882:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9883:2): 
                   9884:2):         my $scancode;
                   9885:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9886:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9887:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9888:2):         } else {
                   9889:2):             $scancode = '';
                   9890:2):         }
                   9891:2): 
                   9892:2):         my @mapresources = @resources;
          6(raebur 9893:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9894:3):         my %respnumlookup=();
                   9895:3):         my %startline=();
                   9896:3):         if ($randomorder || $randompick) {
          1(raebur 9897:2):             @mapresources =
          6(raebur 9898:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9899:3):                              \%orderedforcode);
                   9900:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9901:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9902:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9903:3):                                              \%respnumlookup,\%startline);
                   9904:3):             if ($randompick && $total) {
                   9905:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9906:3):             }
          1(raebur 9907:2):         }
          6(raebur 9908:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9909:3):         chomp($scandata{$pid});
                   9910:3):         $scandata{$pid} =~ s/\r$//;
                   9911:3): 
1.523     raeburn  9912:         my $counter = -1;
1.596.2.12.2.  1(raebur 9913:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9914:             my $parts;
1.554     raeburn  9915:             my $ressymb = $resource->symb();
1.557     raeburn  9916:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9917:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9918:7):                 my $currcode;
                   9919:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9920:7):                     $currcode = $scancode;
                   9921:7):                 }
1.557     raeburn  9922:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9923:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9924:):                                               $username,$domain,undef,
          1(raebur 9925:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9926:             } else {
                   9927:                 $parts = $grader_partids_by_symb{$ressymb};
                   9928:             }
1.542     raeburn  9929:             ($counter,my $recording) =
                   9930:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9931:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9932:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9933:3):                                          $randomorder,$randompick,
                   9934:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9935:             $record{$pid} .= $recording;
1.523     raeburn  9936:         }
                   9937:     }
                   9938:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9939:     $r->print('<br />');
                   9940:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9941:     $passed = 0;
                   9942:     $failed = 0;
                   9943:     $numstudents = 0;
                   9944:     foreach my $last (sort(keys(%bylast))) {
                   9945:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9946:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9947:                 my $showscandata = $scandata{$pid};
                   9948:                 my $showrecord = $record{$pid};
                   9949:                 $showscandata =~ s/\s/&nbsp;/g;
                   9950:                 $showrecord =~ s/\s/&nbsp;/g;
                   9951:                 if ($scandata{$pid} eq $record{$pid}) {
                   9952:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9953:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9954: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9955: '</tr>'."\n".
                   9956: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9957:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9958:                     $passed ++;
                   9959:                 } else {
                   9960:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9961:                     $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  9962: '</tr>'."\n".
                   9963: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9964:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9965: '</tr>'."\n";
                   9966:                     $failed ++;
                   9967:                 }
                   9968:                 $numstudents ++;
                   9969:             }
                   9970:         }
                   9971:     }
1.596.2.4  raeburn  9972:     $r->print('<p>'.
1.596.2.8  raeburn  9973:               &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  9974:                   '<b>',
                   9975:                   $numstudents,
                   9976:                   '</b>',
                   9977:                   $env{'form.scantron_maxbubble'}).
                   9978:               '</p>'
                   9979:     );
1.596.2.12.2.  2(raebur 9980:2):     $r->print('<p>'
                   9981:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9982:2):              .'<br />'
                   9983:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9984:2):              .'</p>');
1.523     raeburn  9985:     if ($passed) {
1.572     www      9986:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9987:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9988:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9989:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9990:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9991:                  $okstudents."\n".
                   9992:                  &Apache::loncommon::end_data_table().'<br />');
                   9993:     }
                   9994:     if ($failed) {
1.572     www      9995:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9996:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9997:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9998:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9999:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10000:                  $badstudents."\n".
                   10001:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10002:                  &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  10003:     }
1.596.2.12.2.  1(raebur 10004:0):     $r->print('</form><br />');
1.523     raeburn  10005:     return;
                   10006: }
                   10007: 
1.542     raeburn  10008: sub verify_scantron_grading {
1.554     raeburn  10009:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 10010:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10011:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  10012:     my ($record,%expected,%startpos);
                   10013:     return ($counter,$record) if (!ref($resource));
                   10014:     return ($counter,$record) if (!$resource->is_problem());
                   10015:     my $symb = $resource->symb();
1.554     raeburn  10016:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10017:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10018:         $counter ++;
                   10019:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 10020:3):         my $respnum = $counter;
                   10021:3):         if ($randomorder || $randompick) {
                   10022:3):             $respnum = $respnumlookup->{$counter};
                   10023:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   10024:3):         } else {
                   10025:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10026:3):         }
                   10027:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10028:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10029:             foreach my $item (@sub_lines) {
                   10030:                 $expected{$part_id} += $item;
                   10031:             }
                   10032:         } else {
1.596.2.12.2.  6(raebur 10033:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10034:         }
                   10035:     }
                   10036:     if ($symb) {
                   10037:         my %recorded;
                   10038:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10039:         if ($returnhash{'version'}) {
                   10040:             my %lasthash=();
                   10041:             my $version;
                   10042:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10043:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10044:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10045:                 }
                   10046:             }
                   10047:             foreach my $key (keys(%lasthash)) {
                   10048:                 if ($key =~ /\.scantron$/) {
                   10049:                     my $value = &unescape($lasthash{$key});
                   10050:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10051:                     if ($value eq '') {
                   10052:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10053:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10054:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10055:                             }
                   10056:                         }
                   10057:                     } else {
                   10058:                         my @tocheck;
                   10059:                         my @items = split(//,$value);
                   10060:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10061:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10062:                             if (@items < $expected{$part_id}) {
                   10063:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10064:                                 my @singles = split(//,$fragment);
                   10065:                                 foreach my $pos (@singles) {
                   10066:                                     if ($pos eq ' ') {
                   10067:                                         push(@tocheck,$pos);
                   10068:                                     } else {
                   10069:                                         my $next = shift(@items);
                   10070:                                         push(@tocheck,$next);
                   10071:                                     }
                   10072:                                 }
                   10073:                             } else {
                   10074:                                 @tocheck = @items;
                   10075:                             }
                   10076:                             foreach my $letter (@tocheck) {
                   10077:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10078:                                     if ($letter !~ /^[A-J]$/) {
                   10079:                                         $letter = $scantron_config->{'Qoff'};
                   10080:                                     }
                   10081:                                     $recorded{$part_id} .= $letter;
                   10082:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10083:                                     my $digit;
                   10084:                                     if ($letter !~ /^[A-J]$/) {
                   10085:                                         $digit = $scantron_config->{'Qoff'};
                   10086:                                     } else {
                   10087:                                         $digit = $lettdig->{$letter};
                   10088:                                     }
                   10089:                                     $recorded{$part_id} .= $digit;
                   10090:                                 }
                   10091:                             }
                   10092:                         } else {
                   10093:                             @tocheck = @items;
                   10094:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10095:                                 my $curr_sub = shift(@tocheck);
                   10096:                                 my $digit;
                   10097:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10098:                                     $digit = $lettdig->{$curr_sub}-1;
                   10099:                                 }
                   10100:                                 if ($curr_sub eq 'J') {
                   10101:                                     $digit += scalar($numletts);
                   10102:                                 }
                   10103:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10104:                                     if ($j == $digit) {
                   10105:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10106:                                     } else {
                   10107:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10108:                                     }
                   10109:                                 }
                   10110:                             }
                   10111:                         }
                   10112:                     }
                   10113:                 }
                   10114:             }
                   10115:         }
1.554     raeburn  10116:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10117:             if ($recorded{$part_id} eq '') {
                   10118:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10119:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10120:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10121:                     }
                   10122:                 }
                   10123:             }
                   10124:             $record .= $recorded{$part_id};
                   10125:         }
                   10126:     }
                   10127:     return ($counter,$record);
                   10128: }
                   10129: 
1.75      albertel 10130: #-------- end of section for handling grading scantron forms -------
                   10131: #
                   10132: #-------------------------------------------------------------------
                   10133: 
1.72      ng       10134: #-------------------------- Menu interface -------------------------
                   10135: #
1.596.2.12.2.  (raeburn 10136:): #--- Href with symb and command ---
                   10137:): 
                   10138:): sub href_symb_cmd {
                   10139:):     my ($symb,$cmd)=@_;
                   10140:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   10141:): }
                   10142:): 
1.443     banghart 10143: sub grading_menu {
1.596.2.12.2.  1(raebur 10144:0):     my ($request,$symb) = @_;
1.443     banghart 10145:     if (!$symb) {return '';}
                   10146: 
                   10147:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 10148:0):                   'command'=>'individual');
                   10149:0): 
                   10150:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10151:0): 
                   10152:0):     $fields{'command'}='ungraded';
                   10153:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10154:0): 
                   10155:0):     $fields{'command'}='table';
                   10156:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10157:0): 
                   10158:0):     $fields{'command'}='all_for_one';
                   10159:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10160:0): 
                   10161:0):     $fields{'command'}='downloadfilesselect';
                   10162:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10163:     
1.443     banghart 10164:     $fields{'command'} = 'csvform';
1.538     schulted 10165:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10166:     
1.443     banghart 10167:     $fields{'command'} = 'processclicker';
1.538     schulted 10168:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10169:     
1.443     banghart 10170:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10171:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 10172:0): 
                   10173:0):     $fields{'command'} = 'initialverifyreceipt';
                   10174:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
          6(raebur 10175:1): 
                   10176:1):     my %permissions;
                   10177:1):     if ($perm{'mgr'}) {
                   10178:1):         $permissions{'either'} = 'F';
                   10179:1):         $permissions{'mgr'} = 'F';
                   10180:1):     }
                   10181:1):     if ($perm{'vgr'}) {
                   10182:1):         $permissions{'either'} = 'F';
                   10183:1):         $permissions{'vgr'} = 'F';
                   10184:1):     }
                   10185:1): 
          1(raebur 10186:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10187:             items =>[
1.596.2.12.2.  1(raebur 10188:0):                         {       linktext => 'Select individual students to grade',
                   10189:0):                                 url => $url1a,
          6(raebur 10190:1):                                 permission => $permissions{'either'},
          1(raebur 10191:0):                                 icon => 'grade_students.png',
                   10192:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   10193:0):                         },
                   10194:0):                         {       linktext => 'Grade ungraded submissions',
                   10195:0):                                 url => $url1b,
          6(raebur 10196:1):                                 permission => $permissions{'either'},
          1(raebur 10197:0):                                 icon => 'ungrade_sub.png',
                   10198:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   10199:0):                         },
                   10200:0): 
                   10201:0):                         {       linktext => 'Grading table',
                   10202:0):                                 url => $url1c,
          6(raebur 10203:1):                                 permission => $permissions{'either'},
          1(raebur 10204:0):                                 icon => 'grading_table.png',
                   10205:0):                                 linktitle => 'Grade current resource for all students.'
                   10206:0):                         },
                   10207:0):                         {       linktext => 'Grade page/folder for one student',
                   10208:0):                                 url => $url1d,
          6(raebur 10209:1):                                 permission => $permissions{'either'},
          1(raebur 10210:0):                                 icon => 'grade_PageFolder.png',
                   10211:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 10212:                         },
1.596.2.12.2.  3(raebur 10213:0):                         {       linktext => 'Download submitted files',
          1(raebur 10214:0):                                 url => $url1e,
          6(raebur 10215:1):                                 permission => $permissions{'either'},
          1(raebur 10216:0):                                 icon => 'download_sub.png',
          3(raebur 10217:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 10218:0):                         }]},
                   10219:0):                          { categorytitle=>'Automated Grading',
                   10220:0):                items =>[
                   10221:0): 
1.538     schulted 10222:                 	    {	linktext => 'Upload Scores',
                   10223:                     		url => $url2,
1.596.2.12.2.  6(raebur 10224:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10225:                     		icon => 'uploadscores.png',
                   10226:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10227:                 	    },
                   10228:                 	    {	linktext => 'Process Clicker',
                   10229:                     		url => $url3,
1.596.2.12.2.  6(raebur 10230:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10231:                     		icon => 'addClickerInfoFile.png',
                   10232:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10233:                 	    },
1.587     raeburn  10234:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10235:                     		url => $url4,
1.596.2.12.2.  6(raebur 10236:1):                     		permission => $permissions{'mgr'},
          1(raebur 10237:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  10238:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 10239:0):                 	    },
                   10240:0):                             {   linktext => 'Verify Receipt Number',
                   10241:0):                                 url => $url5,
          6(raebur 10242:1):                                 permission => $permissions{'either'},
          1(raebur 10243:0):                                 icon => 'receipt_number.png',
                   10244:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10245:0):                             }
                   10246:0): 
1.538     schulted 10247:                     ]
                   10248:             });
                   10249: 
1.443     banghart 10250:     # Create the menu
                   10251:     my $Str;
1.445     banghart 10252:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10253:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 10254:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 10255: 
1.596.2.12.2.  1(raebur 10256:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10257:     return $Str;    
                   10258: }
                   10259: 
1.596.2.12.2.  1(raebur 10260:0): sub ungraded {
                   10261:0):     my ($request)=@_;
                   10262:0):     &submit_options($request);
                   10263:0): }
1.443     banghart 10264: 
1.596.2.12.2.  1(raebur 10265:0): sub submit_options_sequence {
                   10266:0):     my ($request,$symb) = @_;
1.72      ng       10267:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 10268:0):     &commonJSfunctions($request);
                   10269:0):     my $result;
1.72      ng       10270: 
1.596.2.12.2.  1(raebur 10271:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10272:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10273:0):     $result.=&selectfield(0).
                   10274:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   10275:0):             <div>
                   10276:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10277:0):             </div>
                   10278:0):         </div>
                   10279:0):   </form>';
                   10280:0):     return $result;
                   10281:0): }
                   10282:0): 
                   10283:0): sub submit_options_table {
                   10284:0):     my ($request,$symb) = @_;
                   10285:0):     if (!$symb) {return '';}
1.118     ng       10286:     &commonJSfunctions($request);
1.596.2.12.2.  0.2.4(ra 10287:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
1.473     albertel 10288:     my $result;
1.596.2.12.2.  1(raebur 10289:0): 
                   10290:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10291:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10292:0): 
          0.2.4(ra 10293:ul-23):     $result.=&selectfield(1,$is_tool).
          1(raebur 10294:0):             '<input type="hidden" name="command" value="viewgrades" />
                   10295:0):             <div>
                   10296:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10297:0):             </div>
                   10298:0):         </div>
                   10299:0):   </form>';
                   10300:0):     return $result;
                   10301:0): }
                   10302:0): 
                   10303:0): sub submit_options_download {
                   10304:0):     my ($request,$symb) = @_;
                   10305:0):     if (!$symb) {return '';}
                   10306:0): 
                   10307:0):     my $res_error;
                   10308:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10309:0):         &response_type($symb,\$res_error);
                   10310:0):     if ($res_error) {
                   10311:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10312:0):         return;
                   10313:0):     }
                   10314:0):     unless ($numessay) {
                   10315:0):         $request->print(&mt('No essayresponse items found'));
                   10316:0):         return;
                   10317:0):     }
                   10318:0):     my $table;
                   10319:0):     if (ref($partlist) eq 'ARRAY') {
                   10320:0):         if (scalar(@$partlist) > 1 ) {
                   10321:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10322:         }
                   10323:     }
                   10324: 
1.596.2.12.2.  0.2.4(ra 10325:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          1(raebur 10326:0):     &commonJSfunctions($request);
1.72      ng       10327: 
1.596.2.12.2.  1(raebur 10328:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10329:0):         $table."\n".
                   10330:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10331:     $result.='
1.533     bisitz   10332: <h2>
1.596.2.12.2.  3(raebur 10333:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          0.2.4(ra 10334:ul-23): </h2>'.&selectfield(1,$is_tool).'
          1(raebur 10335:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10336:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10337:0):             </div>
                   10338:0):           </div>
                   10339:0): 
                   10340:0): 
                   10341:0):   </form>';
                   10342:0):     return $result;
                   10343:0): }
                   10344:0): 
                   10345:0): #--- Displays the submissions first page -------
                   10346:0): sub submit_options {
                   10347:0):     my ($request,$symb) = @_;
                   10348:0):     if (!$symb) {return '';}
                   10349:0): 
          0.2.4(ra 10350:ul-23):     my $is_tool = ($symb =~ /ext\.tool$/);
          1(raebur 10351:0):     &commonJSfunctions($request);
                   10352:0):     my $result;
                   10353:0): 
                   10354:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10355:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
          0.2.4(ra 10356:ul-23):     $result.=&selectfield(1,$is_tool).'
          1(raebur 10357:0):                 <input type="hidden" name="command" value="submission" />
                   10358:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10359:0):             </div>
                   10360:0):           </div>
                   10361:0):   </form>';
                   10362:0):     return $result;
                   10363:0): }
                   10364:0): 
                   10365:0): sub selectfield {
          0.2.4(ra 10366:ul-23):    my ($full,$is_tool)=@_;
                   10367:ul-23):    my %options;
                   10368:ul-23):    if ($is_tool) {
                   10369:ul-23):        %options =
                   10370:ul-23):            (&transtatus_options,
                   10371:ul-23):             'select_form_order' => ['yes','incorrect','all']);
                   10372:ul-23):    } else {
                   10373:ul-23):        %options =
                   10374:ul-23):            (&substatus_options,
                   10375:ul-23):             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10376:ul-23):    }
          7(raebur 10377:1): 
                   10378:1):   #
                   10379:1):   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10380:1):   # for a different course from the @Sections global in lonstatistics.pm,
                   10381:1):   # populated by an earlier request.
                   10382:1):   #
                   10383:1):    &Apache::lonstatistics::PrepareClasslist();
                   10384:1): 
          1(raebur 10385:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10386: 
                   10387:     <fieldset>
                   10388:       <legend>
                   10389:        '.&mt('Sections').'
                   10390:       </legend>
1.596.2.12.2.  1(raebur 10391:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10392:     </fieldset>
1.596.2.12.2.  1(raebur 10393:0): 
1.533     bisitz   10394:     <fieldset>
                   10395:       <legend>
                   10396:         '.&mt('Groups').'
                   10397:       </legend>
                   10398:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10399:     </fieldset>
1.596.2.12.2.  1(raebur 10400:0):  
1.533     bisitz   10401:     <fieldset>
                   10402:       <legend>
                   10403:         '.&mt('Access Status').'
                   10404:       </legend>
1.596.2.12.2.  1(raebur 10405:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10406:0):     </fieldset>';
                   10407:0):     if ($full) {
          0.2.4(ra 10408:ul-23):         my $heading = &mt('Submission Status');
                   10409:ul-23):         if ($is_tool) {
                   10410:ul-23):             $heading = &mt('Transaction Status');
                   10411:ul-23):         }
          1(raebur 10412:0):         $result.='
1.533     bisitz   10413:     <fieldset>
                   10414:       <legend>
1.596.2.12.2.  0.2.4(ra 10415:ul-23):         '.$heading.'
          1(raebur 10416:0):       </legend>'.
                   10417:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10418:0):    '</fieldset>';
                   10419:0):     }
                   10420:0):     $result.='</div><br />';
1.44      ng       10421:     return $result;
1.2       albertel 10422: }
                   10423: 
1.596.2.12.2.  7(raebur 10424:6): sub substatus_options {
                   10425:6):     return &Apache::lonlocal::texthash(
                   10426:6):                                       'yes'       => 'with submissions',
                   10427:6):                                       'queued'    => 'in grading queue',
                   10428:6):                                       'graded'    => 'with ungraded submissions',
                   10429:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10430:7):                                       'all'       => 'with any status',
                   10431:7):                                       );
          7(raebur 10432:6): }
                   10433:6): 
          1(raebur 10434:0): sub transtatus_options {
                   10435:0):     return &Apache::lonlocal::texthash(
                   10436:0):                                        'yes'       => 'with score transactions',
                   10437:0):                                        'incorrect' => 'with less than full credit',
                   10438:0):                                        'all'       => 'with any status',
                   10439:0):                                       );
                   10440:0): }
                   10441:0): 
1.285     albertel 10442: sub reset_perm {
                   10443:     undef(%perm);
                   10444: }
                   10445: 
                   10446: sub init_perm {
                   10447:     &reset_perm();
1.300     albertel 10448:     foreach my $test_perm ('vgr','mgr','opa') {
                   10449: 
                   10450: 	my $scope = $env{'request.course.id'};
                   10451: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10452: 
                   10453: 	    $scope .= '/'.$env{'request.course.sec'};
                   10454: 	    if ( $perm{$test_perm}=
                   10455: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10456: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10457: 	    } else {
                   10458: 		delete($perm{$test_perm});
                   10459: 	    }
1.285     albertel 10460: 	}
                   10461:     }
                   10462: }
                   10463: 
1.596.2.12.2.  (raeburn 10464:): sub init_old_essays {
                   10465:):     my ($symb,$apath,$adom,$aname) = @_;
                   10466:):     if ($symb ne '') {
                   10467:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10468:):         if (keys(%essays) > 0) {
                   10469:):             $old_essays{$symb} = \%essays;
                   10470:):         }
                   10471:):     }
                   10472:):     return;
                   10473:): }
                   10474:): 
                   10475:): sub reset_old_essays {
                   10476:):     undef(%old_essays);
                   10477:): }
                   10478:): 
1.400     www      10479: sub gather_clicker_ids {
1.408     albertel 10480:     my %clicker_ids;
1.400     www      10481: 
                   10482:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10483: 
                   10484:     # Set up a couple variables.
1.407     albertel 10485:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10486:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10487:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10488: 
1.407     albertel 10489:     foreach my $student (keys(%$classlist)) {
1.438     www      10490:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10491:         my $username = $classlist->{$student}->[$username_idx];
                   10492:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10493:         my $clickers =
1.408     albertel 10494: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10495:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10496:             $id=~s/^[\#0]+//;
1.421     www      10497:             $id=~s/[\-\:]//g;
1.407     albertel 10498:             if (exists($clicker_ids{$id})) {
1.408     albertel 10499: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10500:             } else {
1.408     albertel 10501: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10502:             }
                   10503:         }
                   10504:     }
1.407     albertel 10505:     return %clicker_ids;
1.400     www      10506: }
                   10507: 
1.402     www      10508: sub gather_adv_clicker_ids {
1.408     albertel 10509:     my %clicker_ids;
1.402     www      10510:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10511:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10512:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10513:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10514:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10515:             my ($puname,$pudom)=split(/\:/,$person);
                   10516:             my $clickers =
1.408     albertel 10517: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10518:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10519: 		$id=~s/^[\#0]+//;
1.421     www      10520:                 $id=~s/[\-\:]//g;
1.408     albertel 10521: 		if (exists($clicker_ids{$id})) {
                   10522: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10523: 		} else {
                   10524: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10525: 		}
1.405     www      10526:             }
1.402     www      10527:         }
                   10528:     }
1.407     albertel 10529:     return %clicker_ids;
1.402     www      10530: }
                   10531: 
1.413     www      10532: sub clicker_grading_parameters {
                   10533:     return ('gradingmechanism' => 'scalar',
                   10534:             'upfiletype' => 'scalar',
                   10535:             'specificid' => 'scalar',
                   10536:             'pcorrect' => 'scalar',
                   10537:             'pincorrect' => 'scalar');
                   10538: }
                   10539: 
1.400     www      10540: sub process_clicker {
1.596.2.12.2.  1(raebur 10541:0):     my ($r,$symb)=@_;
1.400     www      10542:     if (!$symb) {return '';}
                   10543:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10544:0):     $result.=&Apache::loncommon::start_data_table().
                   10545:0):              &Apache::loncommon::start_data_table_header_row().
                   10546:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10547:0):              &Apache::loncommon::end_data_table_header_row().
                   10548:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10549: # Attempt to restore parameters from last session, set defaults if not present
                   10550:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10551:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10552:                                                  \%Saveable_Parameters);
                   10553:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10554:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10555:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10556:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10557: 
                   10558:     my %checked;
1.521     www      10559:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10560:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10561:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10562:        }
                   10563:     }
                   10564: 
1.596.2.12.2.  1(raebur 10565:0):     my $upload=&mt("Evaluate File");
1.400     www      10566:     my $type=&mt("Type");
1.402     www      10567:     my $attendance=&mt("Award points just for participation");
                   10568:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10569:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10570:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10571:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10572:     my $pcorrect=&mt("Percentage points for correct solution");
                   10573:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10574:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10575:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10576:):                                                     'interwrite' => 'interwrite PRS',
                   10577:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10578:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10579:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10580: function sanitycheck() {
                   10581: // Accept only integer percentages
                   10582:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10583:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10584: // Find out grading choice
                   10585:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10586:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10587:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10588:       }
                   10589:    }
                   10590: // By default, new choice equals user selection
                   10591:    newgradingchoice=gradingchoice;
                   10592: // Not good to give more points for false answers than correct ones
                   10593:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10594:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10595:    }
                   10596: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10597:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10598:       document.forms.gradesupload.pcorrect.value=100;
                   10599:       document.forms.gradesupload.pincorrect.value=100;
                   10600:    }
                   10601: // If the values are different, cannot be attendance only
                   10602:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10603:        (gradingchoice=='attendance')) {
                   10604:        newgradingchoice='personnel';
                   10605:    }
                   10606: // Change grading choice to new one
                   10607:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10608:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10609:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10610:       } else {
                   10611:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10612:       }
                   10613:    }
                   10614: // Remember the old state
                   10615:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10616: }
1.596.2.12.2.  1(raebur 10617:0): ENDUPFORM
                   10618:0):     $result.= <<ENDUPFORM;
1.400     www      10619: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10620: <input type="hidden" name="symb" value="$symb" />
                   10621: <input type="hidden" name="command" value="processclickerfile" />
                   10622: <input type="file" name="upfile" size="50" />
                   10623: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10624:0): ENDUPFORM
                   10625:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10626:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10627:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10628: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10629: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10630: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10631: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10632: <br />&nbsp;&nbsp;&nbsp;
                   10633: <input type="text" name="givenanswer" size="50" />
1.413     www      10634: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10635:0): ENDGRADINGFORM
                   10636:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10637:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10638:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10639: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10640: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10641: </form>
1.596.2.12.2.  1(raebur 10642:0): ENDPERCFORM
                   10643:0):     $result.='</td>'.
                   10644:0):              &Apache::loncommon::end_data_table_row().
                   10645:0):              &Apache::loncommon::end_data_table();
1.400     www      10646:     return $result;
                   10647: }
                   10648: 
                   10649: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10650:0):     my ($r,$symb) = @_;
1.400     www      10651:     if (!$symb) {return '';}
1.413     www      10652: 
                   10653:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10654:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10655:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10656:0):     my $result='';
1.404     www      10657:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10658: 	$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 10659:0): 	return $result;
1.404     www      10660:     }
1.522     www      10661:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10662:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10663:0):         return $result;
1.521     www      10664:     }
1.522     www      10665:     my $foundgiven=0;
1.521     www      10666:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10667:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10668:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10669:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10670:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10671:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10672:         $foundgiven=$#answers+1;
1.521     www      10673:     }
1.407     albertel 10674:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10675:     my %correct_ids;
1.404     www      10676:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10677: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10678:     }
                   10679:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10680: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10681: 	   $correct_id=~tr/a-z/A-Z/;
                   10682: 	   $correct_id=~s/\s//gs;
                   10683: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10684:            $correct_id=~s/[\-\:]//g;
1.414     www      10685:            if ($correct_id) {
                   10686: 	      $correct_ids{$correct_id}='specified';
                   10687:            }
                   10688:         }
1.400     www      10689:     }
1.404     www      10690:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10691: 	$result.=&mt('Score based on attendance only');
1.521     www      10692:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10693:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10694:     } else {
1.408     albertel 10695: 	my $number=0;
1.411     www      10696: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10697: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10698: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10699: 	    if ($correct_ids{$id} eq 'specified') {
                   10700: 		$result.=&mt('specified');
                   10701: 	    } else {
                   10702: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10703: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10704: 	    }
                   10705: 	    $number++;
                   10706: 	}
1.411     www      10707:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10708:3):         if ($number==0) {
                   10709:3):             $result .=
                   10710:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10711:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10712:0):             return $result;
          5(raebur 10713:3):         }
1.404     www      10714:     }
1.405     www      10715:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10716:3):         $result .=
                   10717:3):             &Apache::lonhtmlcommon::confirm_success(
                   10718:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10719:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10720:0):         return $result;
1.405     www      10721:     }
1.596.2.12.2.  7(raebur 10722:9):     my $mimetype;
                   10723:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10724:9):         my $mm = new File::MMagic;
                   10725:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10726:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10727:9):             $result.= '<p>'.
                   10728:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10729:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10730:0):             return $result;
          7(raebur 10731:9):         }
                   10732:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10733:9):         $result .= '<p>'.
                   10734:9):             &Apache::lonhtmlcommon::confirm_success(
                   10735:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10736:0):         return $result;
          7(raebur 10737:9):     }
1.410     www      10738: 
                   10739: # Were able to get all the info needed, now analyze the file
                   10740: 
1.411     www      10741:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10742:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10743:0):     $result.=&Apache::loncommon::start_data_table().
                   10744:0):              &Apache::loncommon::start_data_table_header_row().
                   10745:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10746:0):              &Apache::loncommon::end_data_table_header_row().
                   10747:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10748:0): <td>
1.410     www      10749: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10750: <input type="hidden" name="symb" value="$symb" />
                   10751: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10752: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10753: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10754: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10755: ENDHEADER
1.522     www      10756:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10757:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10758:     } 
1.408     albertel 10759:     my %responses;
                   10760:     my @questiontitles;
1.405     www      10761:     my $errormsg='';
                   10762:     my $number=0;
                   10763:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10764:9):         if ($mimetype eq 'text/plain') {
                   10765:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10766:9):         } elsif ($mimetype eq 'text/html') {
                   10767:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10768:9):         }
                   10769:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10770:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10771:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10772:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10773:):     }
1.411     www      10774:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10775:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10776:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10777:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10778:              '<br />';
1.522     www      10779:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10780:        $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 10781:0):        return $result;
1.522     www      10782:     } 
1.414     www      10783: # Remember Question Titles
                   10784: # FIXME: Possibly need delimiter other than ":"
                   10785:     for (my $i=0;$i<$number;$i++) {
                   10786:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10787:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10788:     }
1.411     www      10789:     my $correct_count=0;
                   10790:     my $student_count=0;
                   10791:     my $unknown_count=0;
1.414     www      10792: # Match answers with usernames
                   10793: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10794:     foreach my $id (keys(%responses)) {
1.410     www      10795:        if ($correct_ids{$id}) {
1.414     www      10796:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10797:           $correct_count++;
1.410     www      10798:        } elsif ($clicker_ids{$id}) {
1.437     www      10799:           if ($clicker_ids{$id}=~/\,/) {
                   10800: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10801:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10802:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10803:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10804:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10805:                            "<select name='multi".$id."'>";
                   10806:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10807:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10808:              }
                   10809:              $result.='</select>';
                   10810:              $unknown_count++;
                   10811:           } else {
                   10812: # Good: found one and only one user with the right clicker
                   10813:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10814:              $student_count++;
                   10815:           }
1.410     www      10816:        } else {
1.596.2.12.2.  1(raebur 10817:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10818:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10819:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10820:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10821:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10822:                    "\n".&mt("Domain").": ".
                   10823:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10824:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10825:           $unknown_count++;
1.410     www      10826:        }
1.405     www      10827:     }
1.412     www      10828:     $result.='<hr />'.
                   10829:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10830:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10831:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10832:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10833:        } elsif ($correct_count>1) {
1.414     www      10834:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10835:        }
                   10836:     }
1.428     www      10837:     if ($number<1) {
                   10838:        $errormsg.="Found no questions.";
                   10839:     }
1.412     www      10840:     if ($errormsg) {
                   10841:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10842:     } else {
                   10843:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10844:     }
1.596.2.12.2.  1(raebur 10845:0):     $result.='</form></td>'.
                   10846:0):              &Apache::loncommon::end_data_table_row().
                   10847:0):              &Apache::loncommon::end_data_table();
                   10848:0):     return $result;
1.400     www      10849: }
                   10850: 
1.405     www      10851: sub iclicker_eval {
1.406     www      10852:     my ($questiontitles,$responses)=@_;
1.405     www      10853:     my $number=0;
                   10854:     my $errormsg='';
                   10855:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10856:         my %components=&Apache::loncommon::record_sep($line);
                   10857:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10858: 	if ($entries[0] eq 'Question') {
                   10859: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10860: 		$$questiontitles[$number]=$entries[$i];
                   10861: 		$number++;
                   10862: 	    }
                   10863: 	}
                   10864: 	if ($entries[0]=~/^\#/) {
                   10865: 	    my $id=$entries[0];
                   10866: 	    my @idresponses;
                   10867: 	    $id=~s/^[\#0]+//;
                   10868: 	    for (my $i=0;$i<$number;$i++) {
                   10869: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10870:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10871: 		push(@idresponses,$entries[$idx]);
                   10872: 	    }
                   10873: 	    $$responses{$id}=join(',',@idresponses);
                   10874: 	}
1.405     www      10875:     }
                   10876:     return ($errormsg,$number);
                   10877: }
                   10878: 
1.596.2.12.2.  7(raebur 10879:9): sub iclickerxml_eval {
                   10880:9):     my ($questiontitles,$responses)=@_;
                   10881:9):     my $number=0;
                   10882:9):     my $errormsg='';
                   10883:9):     my @state;
                   10884:9):     my %respbyid;
                   10885:9):     my $p = HTML::Parser->new
                   10886:9):     (
                   10887:9):         xml_mode => 1,
                   10888:9):         start_h =>
                   10889:9):             [sub {
                   10890:9):                  my ($tagname,$attr) = @_;
                   10891:9):                  push(@state,$tagname);
                   10892:9):                  if ("@state" eq "ssn p") {
                   10893:9):                      my $title = $attr->{qn};
                   10894:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10895:9):                      $questiontitles->[$number]=$title;
                   10896:9):                  } elsif ("@state" eq "ssn p v") {
                   10897:9):                      my $id = $attr->{id};
                   10898:9):                      my $entry = $attr->{ans};
                   10899:9):                      $id=~s/^[\#0]+//;
                   10900:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10901:9):                      $respbyid{$id}[$number] = $entry;
                   10902:9):                  }
                   10903:9):             }, "tagname, attr"],
                   10904:9):          end_h =>
                   10905:9):                [sub {
                   10906:9):                    my ($tagname) = @_;
                   10907:9):                    if ("@state" eq "ssn p") {
                   10908:9):                        $number++;
                   10909:9):                    }
                   10910:9):                    pop(@state);
                   10911:9):                 }, "tagname"],
                   10912:9):     );
                   10913:9): 
                   10914:9):     $p->parse($env{'form.upfile'});
                   10915:9):     $p->eof;
                   10916:9):     foreach my $id (keys(%respbyid)) {
                   10917:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10918:9):     }
                   10919:9):     return ($errormsg,$number);
                   10920:9): }
                   10921:9): 
1.419     www      10922: sub interwrite_eval {
                   10923:     my ($questiontitles,$responses)=@_;
                   10924:     my $number=0;
                   10925:     my $errormsg='';
1.420     www      10926:     my $skipline=1;
                   10927:     my $questionnumber=0;
                   10928:     my %idresponses=();
1.419     www      10929:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10930:         my %components=&Apache::loncommon::record_sep($line);
                   10931:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10932:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10933:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10934:         next if $skipline;
                   10935:         if ($entries[0]!=$questionnumber) {
                   10936:            $questionnumber=$entries[0];
                   10937:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10938:            $number++;
1.419     www      10939:         }
1.420     www      10940:         my $id=$entries[4];
                   10941:         $id=~s/^[\#0]+//;
1.421     www      10942:         $id=~s/^v\d*\://i;
                   10943:         $id=~s/[\-\:]//g;
1.420     www      10944:         $idresponses{$id}[$number]=$entries[6];
                   10945:     }
1.524     raeburn  10946:     foreach my $id (keys(%idresponses)) {
1.420     www      10947:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10948:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10949:     }
                   10950:     return ($errormsg,$number);
                   10951: }
                   10952: 
1.596.2.12.2.  (raeburn 10953:): sub turning_eval {
                   10954:):     my ($questiontitles,$responses)=@_;
                   10955:):     my $number=0;
                   10956:):     my $errormsg='';
                   10957:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10958:):         my %components=&Apache::loncommon::record_sep($line);
                   10959:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10960:):         if ($#entries>$number) { $number=$#entries; }
                   10961:):         my $id=$entries[0];
                   10962:):         my @idresponses;
                   10963:):         $id=~s/^[\#0]+//;
                   10964:):         unless ($id) { next; }
                   10965:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10966:):             $entries[$idx]=~s/\,/\;/g;
                   10967:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10968:):             push(@idresponses,$entries[$idx]);
                   10969:):         }
                   10970:):         $$responses{$id}=join(',',@idresponses);
                   10971:):     }
                   10972:):     for (my $i=1; $i<=$number; $i++) {
                   10973:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10974:):     }
                   10975:):     return ($errormsg,$number);
                   10976:): }
                   10977:): 
1.414     www      10978: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10979:0):     my ($r,$symb) = @_;
1.414     www      10980:     if (!$symb) {return '';}
1.416     www      10981: # See which part we are saving to
1.582     raeburn  10982:     my $res_error;
                   10983:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10984:     if ($res_error) {
                   10985:         return &navmap_errormsg();
                   10986:     }
1.416     www      10987: # FIXME: This should probably look for the first handgradeable part
                   10988:     my $part=$$partlist[0];
                   10989: # Start screen output
1.596.2.12.2.  1(raebur 10990:0):     my $result = &Apache::loncommon::start_data_table(). 
                   10991:0):                  &Apache::loncommon::start_data_table_header_row().
                   10992:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10993:0):                  &Apache::loncommon::end_data_table_header_row().
                   10994:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10995: # Get correct result
                   10996: # FIXME: Possibly need delimiter other than ":"
                   10997:     my @correct=();
1.415     www      10998:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10999:     my $number=$env{'form.number'};
                   11000:     if ($gradingmechanism ne 'attendance') {
1.414     www      11001:        foreach my $key (keys(%env)) {
                   11002:           if ($key=~/^form\.correct\:/) {
                   11003:              my @input=split(/\,/,$env{$key});
                   11004:              for (my $i=0;$i<=$#input;$i++) {
                   11005:                  if (($correct[$i]) && ($input[$i]) &&
                   11006:                      ($correct[$i] ne $input[$i])) {
                   11007:                     $result.='<br /><span class="LC_warning">'.
                   11008:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11009:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  11010:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11011:                     $correct[$i]=$input[$i];
                   11012:                  }
                   11013:              }
                   11014:           }
                   11015:        }
1.415     www      11016:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  11017:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11018:              $result.='<br /><span class="LC_error">'.
                   11019:                       &mt('No correct result given for question "[_1]"!',
                   11020:                           $env{'form.question:'.$i}).'</span>';
                   11021:           }
                   11022:        }
1.596.2.4  raeburn  11023:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11024:     }
                   11025: # Start grading
1.415     www      11026:     my $pcorrect=$env{'form.pcorrect'};
                   11027:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11028:     my $storecount=0;
1.596.2.4  raeburn  11029:     my %users=();
1.415     www      11030:     foreach my $key (keys(%env)) {
1.420     www      11031:        my $user='';
1.415     www      11032:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11033:           $user=$1;
                   11034:        }
                   11035:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11036:           my $id=$1;
                   11037:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11038:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11039:           } elsif ($env{'form.multi'.$id}) {
                   11040:              $user=$env{'form.multi'.$id};
1.420     www      11041:           }
                   11042:        }
1.596.2.4  raeburn  11043:        if ($user) {
                   11044:           if ($users{$user}) {
                   11045:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 11046:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  11047:                       '</span><br />';
                   11048:           }
                   11049:           $users{$user}=1;
1.415     www      11050:           my @answer=split(/\,/,$env{$key});
                   11051:           my $sum=0;
1.522     www      11052:           my $realnumber=$number;
1.415     www      11053:           for (my $i=0;$i<$number;$i++) {
1.576     www      11054:              if  ($correct[$i] eq '-') {
                   11055:                 $realnumber--;
1.596.2.12.2.  1(raebur 11056:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11057:                 if ($gradingmechanism eq 'attendance') {
                   11058:                    $sum+=$pcorrect;
1.576     www      11059:                 } elsif ($correct[$i] eq '*') {
1.522     www      11060:                    $sum+=$pcorrect;
1.415     www      11061:                 } else {
1.596.2.4  raeburn  11062: # We actually grade if correct or not
                   11063:                    my $increment=$pincorrect;
                   11064: # Special case: numerical answer "0"
                   11065:                    if ($correct[$i] eq '0') {
                   11066:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11067:                          $increment=$pcorrect;
                   11068:                       }
                   11069: # General numerical answer, both evaluate to something non-zero
                   11070:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11071:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11072:                          $increment=$pcorrect;
                   11073:                       }
                   11074: # Must be just alphanumeric
                   11075:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11076:                       $increment=$pcorrect;
1.415     www      11077:                    }
1.596.2.4  raeburn  11078:                    $sum+=$increment;
1.415     www      11079:                 }
                   11080:              }
                   11081:           }
1.522     www      11082:           my $ave=$sum/(100*$realnumber);
1.416     www      11083: # Store
                   11084:           my ($username,$domain)=split(/\:/,$user);
                   11085:           my %grades=();
                   11086:           $grades{"resource.$part.solved"}='correct_by_override';
                   11087:           $grades{"resource.$part.awarded"}=$ave;
                   11088:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11089:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11090:                                                  $env{'request.course.id'},
                   11091:                                                  $domain,$username);
                   11092:           if ($returncode ne 'ok') {
                   11093:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11094:           } else {
                   11095:              $storecount++;
                   11096:           }
1.415     www      11097:        }
                   11098:     }
                   11099: # We are done
1.549     hauer    11100:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  11101:              '</td>'.
                   11102:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 11103:0):              &Apache::loncommon::end_data_table();
                   11104:0):     return $result;
1.414     www      11105: }
                   11106: 
1.582     raeburn  11107: sub navmap_errormsg {
                   11108:     return '<div class="LC_error">'.
                   11109:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11110:            &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  11111:            '</div>';
                   11112: }
                   11113: 
1.596.2.12.2.  (raeburn 11114:): sub startpage {
          5(raebur 11115:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
          9(raebur 11116:9):     my %args;
                   11117:9):     if ($onload) {
                   11118:9):          my %loaditems = (
                   11119:9):                         'onload' => $onload,
                   11120:9):                       );
                   11121:9):          $args{'add_entries'} = \%loaditems;
                   11122:9):     }
          (raeburn 11123:):     if ($nomenu) {
          9(raebur 11124:9):         $args{'only_body'} = 1;
          5(raebur 11125:0):         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
          (raeburn 11126:):     } else {
          8(raebur 11127:1):         if ($env{'request.course.id'}) {
                   11128:1):             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11129:1):         }
          9(raebur 11130:9):         $args{'bread_crumbs'} = $crumbs;
          5(raebur 11131:0):         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
          (raeburn 11132:):     }
                   11133:):     unless ($nodisplayflag) {
          1(raebur 11134:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 11135:):     }
                   11136:): }
                   11137:): 
          1(raebur 11138:0): sub select_problem {
                   11139:0):     my ($r)=@_;
                   11140:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   11141:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   11142:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11143:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11144:0): }
                   11145:0): 
1.1       albertel 11146: sub handler {
1.41      ng       11147:     my $request=$_[0];
1.434     albertel 11148:     &reset_caches();
1.596.2.4  raeburn  11149:     if ($request->header_only) {
                   11150:         &Apache::loncommon::content_type($request,'text/html');
                   11151:         $request->send_http_header;
                   11152:         return OK;
1.41      ng       11153:     }
                   11154:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  11155: 
1.596.2.12.2.  1(raebur 11156:0): # see what command we need to execute
                   11157:0):  
1.160     albertel 11158:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11159:     my $command=$commands[0];
1.447     foxr     11160: 
1.596.2.12.2.  1(raebur 11161:0):     &init_perm();
                   11162:0):     if (!$env{'request.course.id'}) {
                   11163:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11164:0):                 ($command =~ /^scantronupload/)) {
                   11165:0):             # Not in a course.
                   11166:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11167:0):             return HTTP_NOT_ACCEPTABLE;
                   11168:0):         }
                   11169:0):     } elsif (!%perm) {
                   11170:0):         $request->internal_redirect('/adm/quickgrades');
                   11171:0):         return OK;
                   11172:0):     }
                   11173:0):     &Apache::loncommon::content_type($request,'text/html');
                   11174:0):     $request->send_http_header;
                   11175:0): 
1.160     albertel 11176:     if ($#commands > 0) {
                   11177: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11178:     }
1.447     foxr     11179: 
1.596.2.12.2.  1(raebur 11180:0): # see what the symb is
                   11181:0): 
                   11182:0):     my $symb=$env{'form.symb'};
                   11183:0):     unless ($symb) {
                   11184:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11185:0):        $symb=&Apache::lonnet::symbread($url);
                   11186:0):     }
                   11187:0):     &Apache::lonenc::check_decrypt(\$symb);
                   11188:0): 
1.513     foxr     11189:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 11190:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   11191:0): #
                   11192:0): # Not called from a resource, but inside a course
                   11193:0): #
                   11194:0):         &startpage($request,undef,[],1,1);
                   11195:0):         &select_problem($request);
1.41      ng       11196:     } else {
1.596.2.12.2.  1(raebur 11197:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   11198:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 11199:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11200:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11201:):                     &choose_task_version_form($symb,$env{'form.student'},
                   11202:):                                               $env{'form.userdom'});
                   11203:):             }
          1(raebur 11204:0):             my $divforres;
                   11205:0):             if ($env{'form.student'} eq '') {
                   11206:0):                 $js .= &part_selector_js();
                   11207:0):                 $onload = "toggleParts('gradesub');";
                   11208:0):             } else {
                   11209:0):                 $divforres = 1;
                   11210:0):             }
          5(raebur 11211:0):             my $head_extra = $js;
                   11212:0):             unless ($env{'form.vProb'} eq 'no') {
                   11213:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11214:0):                 if ($csslinks) {
                   11215:0):                     $head_extra .= "\n$csslinks";
                   11216:0):                 }
                   11217:0):             }
                   11218:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11219:0):                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
          (raeburn 11220:):             if ($versionform) {
          2(raebur 11221:0):                 if ($divforres) {
                   11222:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11223:0):                 }
          (raeburn 11224:):                 $request->print($versionform);
                   11225:):             }
          1(raebur 11226:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 11227:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11228:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11229:):                 &choose_task_version_form($symb,$env{'form.student'},
                   11230:):                                           $env{'form.userdom'},
                   11231:):                                           $env{'form.inhibitmenu'});
          5(raebur 11232:0):             my $head_extra = $js;
                   11233:0):             unless ($env{'form.vProb'} eq 'no') {
                   11234:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11235:0):                 if ($csslinks) {
                   11236:0):                     $head_extra .= "\n$csslinks";
                   11237:0):                 }
                   11238:0):             }
                   11239:0):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11240:0):                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
          (raeburn 11241:):             if ($versionform) {
                   11242:):                 $request->print($versionform);
                   11243:):             }
                   11244:):             $request->print('<br clear="all" />');
                   11245:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 11246:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   11247:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11248:0):                                        {href=>'',text=>'Select student'}],1,1);
                   11249:0):             &pickStudentPage($request,$symb);
                   11250:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
          5(raebur 11251:0):             my $csslinks;
                   11252:0):             unless ($env{'form.vProb'} eq 'no') {
                   11253:0):                 $csslinks = &Apache::loncommon::css_links($symb,'map');
                   11254:0):             }
          1(raebur 11255:0):             &startpage($request,$symb,
                   11256:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11257:0):                                        {href=>'',text=>'Select student'},
          5(raebur 11258:0):                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
          1(raebur 11259:0):             &displayPage($request,$symb);
                   11260:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   11261:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11262:0):                                        {href=>'',text=>'Select student'},
                   11263:0):                                        {href=>'',text=>'Grade student'},
                   11264:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   11265:0):             &updateGradeByPage($request,$symb);
                   11266:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
          5(raebur 11267:0):             my $csslinks;
                   11268:0):             unless ($env{'form.vProb'} eq 'no') {
                   11269:0):                 $csslinks = &Apache::loncommon::css_links($symb);
                   11270:0):             }
          1(raebur 11271:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
          5(raebur 11272:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
          1(raebur 11273:0):             &processGroup($request,$symb);
                   11274:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   11275:0):             &startpage($request,$symb);
                   11276:0):             $request->print(&grading_menu($request,$symb));
                   11277:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   11278:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   11279:0):             $request->print(&submit_options($request,$symb));
                   11280:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   11281:0):             my $js = &part_selector_js();
                   11282:0):             my $onload = "toggleParts('gradesub');";
                   11283:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11284:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11285:0):             $request->print(&listStudents($request,$symb,'graded'));
                   11286:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   11287:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   11288:0):             $request->print(&submit_options_table($request,$symb));
                   11289:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   11290:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   11291:0):             $request->print(&submit_options_sequence($request,$symb));
                   11292:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   11293:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   11294:0):             $request->print(&viewgrades($request,$symb));
                   11295:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   11296:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11297:0):                                        {href=>'',text=>'Store grades'}]);
                   11298:0):             $request->print(&processHandGrade($request,$symb));
                   11299:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   11300:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11301:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11302:0):                                                                              text=>"Modify grades"},
                   11303:0):                                        {href=>'', text=>"Store grades"}]);
                   11304:0):             $request->print(&editgrades($request,$symb));
                   11305:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   11306:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   11307:0):             $request->print(&initialverifyreceipt($request,$symb));
                   11308:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   11309:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11310:0):                                        {href=>'',text=>'Verification Result'}]);
                   11311:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      11312:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11313:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   11314:0):             $request->print(&process_clicker($request,$symb));
1.400     www      11315:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11316:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11317:0):                                        {href=>'', text=>'Process clicker file'}]);
                   11318:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      11319:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11320:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11321:0):                                        {href=>'', text=>'Process clicker file'},
                   11322:0):                                        {href=>'', text=>'Store grades'}]);
                   11323:0):             $request->print(&assign_clicker_grades($request,$symb));
                   11324:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   11325:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11326:0):             $request->print(&upcsvScores_form($request,$symb));
                   11327:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   11328:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11329:0):             $request->print(&csvupload($request,$symb));
                   11330:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   11331:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11332:0):             $request->print(&csvuploadmap($request,$symb));
                   11333:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   11334:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   11335:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11336:0):                 $request->print(&csvuploadoptions($request,$symb));
                   11337:0):             } else {
                   11338:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11339:0):                     $env{'form.upfile_associate'} = 'reverse';
                   11340:0):                 } else {
                   11341:0):                     $env{'form.upfile_associate'} = 'forward';
                   11342:0):                 }
                   11343:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11344:0):                 $request->print(&csvuploadmap($request,$symb));
                   11345:0):             }
                   11346:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   11347:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11348:0):             $request->print(&csvuploadassign($request,$symb));
                   11349:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   11350:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11351:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11352:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   11353:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   11354:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11355:0):             $request->print(&scantron_do_warning($request,$symb));
                   11356:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11357:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11358:0):             $request->print(&scantron_validate_file($request,$symb));
                   11359:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11360:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11361:0):             $request->print(&scantron_process_students($request,$symb));
                   11362:0):         } elsif ($command eq 'scantronupload' &&
                   11363:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11364:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11365:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11366:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11367:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11368:0):         } elsif ($command eq 'scantronupload_save' &&
                   11369:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11370:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11371:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11372:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11373:0):         } elsif ($command eq 'scantron_download' &&
                   11374:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11375:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11376:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11377:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11378:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11379:0):             $request->print(&checkscantron_results($request,$symb));
                   11380:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11381:0):             my $js = &part_selector_js();
                   11382:0):             my $onload = "toggleParts('gradingMenu');";
                   11383:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11384:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11385:0):             $request->print(&submit_options_download($request,$symb));
                   11386:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11387:0):             &startpage($request,$symb,
                   11388:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11389:0):     {href=>'', text=>'Download submitted files'}],
                   11390:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11391:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11392:0):             &submit_download_link($request,$symb);
                   11393:0):         } elsif ($command) {
                   11394:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11395:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11396:0):         }
1.2       albertel 11397:     }
1.513     foxr     11398:     if ($ssi_error) {
                   11399: 	&ssi_print_error($request);
                   11400:     }
1.353     albertel 11401:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11402:     &reset_caches();
1.596.2.4  raeburn  11403:     return OK;
1.44      ng       11404: }
                   11405: 
1.1       albertel 11406: 1;
                   11407: 
1.13      albertel 11408: __END__;
1.531     jms      11409: 
                   11410: 
                   11411: =head1 NAME
                   11412: 
                   11413: Apache::grades
                   11414: 
                   11415: =head1 SYNOPSIS
                   11416: 
                   11417: Handles the viewing of grades.
                   11418: 
                   11419: This is part of the LearningOnline Network with CAPA project
                   11420: described at http://www.lon-capa.org.
                   11421: 
                   11422: =head1 OVERVIEW
                   11423: 
                   11424: Do an ssi with retries:
                   11425: While I'd love to factor out this with the vesrion in lonprintout,
                   11426: 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
                   11427: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11428: 
                   11429: At least the logic that drives this has been pulled out into loncommon.
                   11430: 
                   11431: 
                   11432: 
                   11433: ssi_with_retries - Does the server side include of a resource.
                   11434:                      if the ssi call returns an error we'll retry it up to
                   11435:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11436:4):                      If we still have a problem, no text is appended to the
1.531     jms      11437:                      output and we set some global variables.
                   11438:                      to indicate to the caller an SSI error occurred.  
                   11439:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11440:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11441:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11442:                      by informing the user that this happened.
                   11443: 
                   11444: Parameters:
                   11445:   resource   - The resource to include.  This is passed directly, without
                   11446:                interpretation to lonnet::ssi.
                   11447:   form       - The form hash parameters that guide the interpretation of the resource
                   11448:                
                   11449:   retries    - Number of retries allowed before giving up completely.
                   11450: Returns:
                   11451:   On success, returns the rendered resource identified by the resource parameter.
                   11452: Side Effects:
                   11453:   The following global variables can be set:
                   11454:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11455:                               It is up to the caller to initialize this to false
                   11456:                               if desired.
                   11457:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11458:                               of the resource that could not be rendered by the ssi
                   11459:                               call.
                   11460:    ssi_error_message   - The error string fetched from the ssi response
                   11461:                               in the event of an error.
                   11462: 
                   11463: 
                   11464: =head1 HANDLER SUBROUTINE
                   11465: 
                   11466: ssi_with_retries()
                   11467: 
                   11468: =head1 SUBROUTINES
                   11469: 
                   11470: =over
                   11471: 
                   11472: =item scantron_get_correction() : 
                   11473: 
                   11474:    Builds the interface screen to interact with the operator to fix a
                   11475:    specific error condition in a specific scanline
                   11476: 
                   11477:  Arguments:
                   11478:     $r           - Apache request object
                   11479:     $i           - number of the current scanline
                   11480:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11481:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11482:     $line        - full contents of the current scanline
                   11483:     $error       - error condition, valid values are
                   11484:                    'incorrectCODE', 'duplicateCODE',
                   11485:                    'doublebubble', 'missingbubble',
                   11486:                    'duplicateID', 'incorrectID'
                   11487:     $arg         - extra information needed
                   11488:        For errors:
                   11489:          - duplicateID   - paper number that this studentID was seen before on
                   11490:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11491:                            seen on before
                   11492:          - incorrectCODE - current incorrect CODE 
                   11493:          - doublebubble  - array ref of the bubble lines that have double
                   11494:                            bubble errors
                   11495:          - missingbubble - array ref of the bubble lines that have missing
                   11496:                            bubble errors
                   11497: 
1.596.2.12.2.  0(raebur 11498:2):    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   11499:2):    $randompick  - True if exam folder (or a sub-folder) has randompick set
          6(raebur 11500:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11501:3):                      for current line to question number used for same question
                   11502:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11503:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11504:3):                   and value is number of first bubble line for current student
                   11505:3):                   or code-based randompick and/or randomorder.
                   11506:3): 
                   11507:3): 
1.531     jms      11508: =item  scantron_get_maxbubble() : 
                   11509: 
1.582     raeburn  11510:    Arguments:
                   11511:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11512:                       failure to retrieve a navmap object.
                   11513:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11514:        calling routine should trap the error condition and display the warning
                   11515:        found in &navmap_errormsg().
                   11516: 
1.596.2.12.2.  (raeburn 11517:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11518:): 
1.531     jms      11519:    Returns the maximum number of bubble lines that are expected to
                   11520:    occur. Does this by walking the selected sequence rendering the
                   11521:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11522:    for what the current value of the problem counter is.
                   11523: 
                   11524:    Caches the results to $env{'form.scantron_maxbubble'},
                   11525:    $env{'form.scantron.bubble_lines.n'}, 
                   11526:    $env{'form.scantron.first_bubble_line.n'} and
                   11527:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11528:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11529:    lines for response n and number of the first bubble line for response n,
                   11530:    and a comma separated list of numbers of bubble lines for sub-questions
                   11531:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11532: 
                   11533: 
                   11534: =item  scantron_validate_missingbubbles() : 
                   11535: 
                   11536:    Validates all scanlines in the selected file to not have any
                   11537:     answers that don't have bubbles that have not been verified
                   11538:     to be bubble free.
                   11539: 
                   11540: =item  scantron_process_students() : 
                   11541: 
1.596.2.6  raeburn  11542:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11543: 
                   11544:    The parsed scanline hash is added to %env 
                   11545: 
                   11546:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11547:    foreach resource , with the form data of
                   11548: 
                   11549: 	'submitted'     =>'scantron' 
                   11550: 	'grade_target'  =>'grade',
                   11551: 	'grade_username'=> username of student
                   11552: 	'grade_domain'  => domain of student
                   11553: 	'grade_courseid'=> of course
                   11554: 	'grade_symb'    => symb of resource to grade
                   11555: 
                   11556:     This triggers a grading pass. The problem grading code takes care
                   11557:     of converting the bubbled letter information (now in %env) into a
                   11558:     valid submission.
                   11559: 
                   11560: =item  scantron_upload_scantron_data() :
                   11561: 
1.596.2.6  raeburn  11562:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11563: 
                   11564: =item  scantron_upload_scantron_data_save() : 
                   11565: 
                   11566:    Adds a provided bubble information data file to the course if user
                   11567:    has the correct privileges to do so. 
                   11568: 
                   11569: =item  valid_file() :
                   11570: 
                   11571:    Validates that the requested bubble data file exists in the course.
                   11572: 
                   11573: =item  scantron_download_scantron_data() : 
                   11574: 
                   11575:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11576:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11577:    course.
                   11578: 
                   11579: =item  scantron_validate_ID() : 
                   11580: 
                   11581:    Validates all scanlines in the selected file to not have any
1.556     weissno  11582:    invalid or underspecified student/employee IDs
1.531     jms      11583: 
1.582     raeburn  11584: =item navmap_errormsg() :
                   11585: 
                   11586:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11587:    Should be called whenever the request to instantiate a navmap object fails.  
                   11588: 
1.531     jms      11589: =back
                   11590: 
                   11591: =cut

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